/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/clockwork-tools@1.9.4/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
#!/usr/bin/env node
(function(){var fs=require("fs-extra"),path=require("path"),spawn=require("child_process").spawn,parseString=require("xml2js").parseString,ncp=require("ncp").ncp,archiver=require("archiver"),request=require("request"),prompt=require("prompt"),geardoc=require("@clockwork/geardoc"),exec=require("child_process").exec;prompt.start(),prompt.message="Some information is required";var rootPath="./",log=function(e){},showError=function(e){console.log(e)},getDataViaPrompt=function(e,o){return prompt.get(e,o)},userArguments=process.argv.slice(2),bridges={web:require("clockwork-web-bridge"),uwp:require("clockwork-uwp-bridge")};if(userArguments.length<1)console.log("No action was specified, use 'clockwork ?' to see the available actions");else switch(userArguments[0]){case"init":createProject(userArguments[1]);break;case"build":buildProject((function(e){console.log("The package has been successfully generated, you can find it at "+e)}));break;case"list":listPackages(userArguments[1]);break;case"add":addPackage(getDataViaPrompt,userArguments[1],userArguments[2]);break;case"update":updatePackage(userArguments[1]);break;case"register":prompt.get({properties:{username:{description:"Enter your username",required:!0},email:{description:"Enter your email",pattern:/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/,required:!0,message:"This must be a valid email"},password:{description:"Enter your password",hidden:!0,required:!0,replace:"*"}}},(function(e,o){register(o.username,o.email,o.password)}));break;case"publish":prompt.get({properties:{sourceFile:{description:"Enter the location of the source file",required:!0},packageId:{description:"Enter the package name",pattern:/^[a-zA-Z0-9]+$/,message:"Name must only contain alphanumeric characters",required:!0},packageVersion:{description:"Enter the package version",pattern:/^[a-zA-Z0-9\.\-]+$/,message:"Name must only contain alphanumeric characters, dots and dashes",required:!0}}},(function(e,o){tryPublish(o.sourceFile,o.packageId,o.packageVersion)}));break;case"bridge":runBridge(userArguments[1]);break;case"help":case"?":help();break;default:console.log("The specified action was not recognized")}function createProject(e){if(void 0!==e){var o=require("./template/newProject.js");o.folders.forEach(function e(o,r){o=o+"/"+r.name;try{fs.mkdirSync(rootPath+o)}catch(e){}r.folders&&r.folders.forEach(e.bind(null,o))}.bind(null,"")),o.files.forEach((function(o){fs.readFile(__dirname+"/"+o.file,"base64",(function(r,n){if(r)return console.log(r);if(o.template){var t=new Buffer(n,"base64"),s=t.toString().replace("#projectName#",e);n=(t=new Buffer(s)).toString("base64")}fs.writeFile(rootPath+o.name,n,"base64",(function(e){if(e)throw e}))}))}))}else console.log("No name was specified for the project")}function buildProject(e){var o=readManifest();if(null!=o)try{generatePackage(o).then(e)}catch(e){showError("Error:"+e)}else console.log("The current directory does not contain a Clockwork project")}function generatePackage(e){var o=path.resolve(rootPath);try{fs.mkdirSync(o+"/ClockworkPackageTemp")}catch(e){}return copyFileSync(o+"/manifest.json",o+"/ClockworkPackageTemp/manifest.json"),new Promise((function(r,n){console.log("Copying project files..."),ncp(o+"/"+e.scope,o+"/ClockworkPackageTemp/"+e.scope,(function(e){e?(console.error(e),n()):r()}))})).then((function(){return preprocessPackage(o+"/ClockworkPackageTemp")})).then((function(r){return new Promise((function(r,n){try{fs.unlinkSync(o+"/"+e.name+".cw")}catch(e){}var t=fs.createWriteStream(o+"/"+e.name+".cw"),s=archiver("zip");t.on("close",(function(){console.log("Deleting temporary files..."),deleteFolderRecursive(o+"/ClockworkPackageTemp/"),r()})),s.on("error",(function(e){throw e})),s.pipe(t),console.log("Creating package.."),s.glob("**",{cwd:o+"/ClockworkPackageTemp/"}),s.finalize()}))})).then((function(r){return o+"/"+e.name+".cw"}))}function readManifest(e){try{return JSON.parse(fs.readFileSync((e||path.resolve(rootPath))+"/manifest.json"))}catch(e){return null}}function writeManifest(e,o,r){fs.writeFile((r||path.resolve(rootPath))+"/manifest.json",JSON.stringify(e),(function(e){o&&o(e)}))}function preprocessPackage(path){var manifest=readManifest();return new Promise((function(resolvef,rejectf){console.log("Processing levels...");var levels=manifest.levels.map((function(e,o){if(-1!=e.indexOf(".xml")){var r=e.split(".xml").join(".json");return manifest.levels[o]=r,new Promise((function(o,n){log("Reading "+path+"/"+manifest.scope+"/"+e),fs.readFile(path+"/"+manifest.scope+"/"+e,(function(n,t){if(n)return console.error(n);parseString(t,(function(n,t){n?(showError("There are errors in "+e+", check your XML."),o()):(log("Writing "+path+"/"+manifest.scope+"/"+r),fs.writeFile(path+"/"+manifest.scope+"/"+r,JSON.stringify(XMLlevelsToJson(t,e)),(function(e){if(e)return console.error(e);o()})))}))}))}))}return new Promise((function(e,o){return e()}))})),spritesheets=manifest.spritesheets.map((function(oldName,i){if(console.log("Processing spritesheets..."),-1!=oldName.indexOf(".xml")){var newName=oldName.split(".xml").join(".json");return manifest.spritesheets[i]=newName,new Promise((function(e,o){fs.readFile(path+"/"+manifest.scope+"/"+oldName,(function(o,r){if(o)return console.error(o);parseString(r,(function(o,r){o?(showError("There are errors in "+oldName+", check your XML."),e()):fs.writeFile(path+"/"+manifest.scope+"/"+newName,JSON.stringify(XMLspritesheetsToJson(r)),(function(o){if(o)return console.error(o);e()}))}))}))}))}if(oldName.indexOf(".js")==oldName.length-3)return new Promise((function(resolve,reject){fs.readFile(path+"/"+manifest.scope+"/"+oldName,(function(err,data){if(err)return console.error(err);var spritesheetContent;eval("spritesheetContent = "+data),function e(o){for(x in o)"object"==typeof o[x]&&e(o[x]),"function"==typeof o[x]&&(o[x]=o[x].toString())}(spritesheetContent);var newName=oldName.split(".js").join(".json");fs.writeFile(path+"/"+manifest.scope+"/"+newName,JSON.stringify(spritesheetContent),(function(e){if(e)return console.error(e);resolve()}))}))}))}));Promise.all(levels.concat(spritesheets)).then((function(e){console.log("Updating manifest..."),fs.writeFile(path+"/manifest.json",JSON.stringify(manifest),(function(e){if(e)return console.error(e);resolvef()}))}))}))}function XMLlevelsToJson(e,o){try{return e.levels.level.map(XMLlevelToJson)}catch(e){showError(o+" does not contain a valid XML levels file")}}function XMLlevelToJson(e){var o={};return o.id=e.$.id,e.object?o.objects=e.object.map((function(e){var o={};o.name=e.$.name,e.type&&e.type.length>0?o.type=e.type.map((function(e){return e.$.id})):o.type=e.$.type,o.sprite=e.$.spritesheet?e.$.spritesheet:null,o.isstatic=e.$.static?e.$.static:null,o.x=+e.$.x,o.y=+e.$.y,o.z=e.$.z?+e.$.z:null;try{o.vars=e.$.vars?JSON.parse(e.$.vars):{}}catch(r){showError("This string should be a valid JSON object but it is not"),showError(e.$.vars),o.vars={}}return o})):o.objects=[],o}function XMLspritesheetsToJson(e){return e.spritesheets.spritesheet.map(XMLspritesheetToJson)}function Spritesheet(){this.name="",this.img,this.states={},this.layers={},this.frames={}}function State(){this.layers=[]}function Layer(){this.frames=[],this.x,this.y}function Frame(e,o,r,n,t){this.x=e,this.y=o,this.w=r,this.h=n,this.t=t}function XMLspritesheetToJson(e){var o=new Spritesheet;return o.name=e.$.name,null!=e.$.src&&(o.src=e.$.src),null!=e.$.positionBasedOptimizations&&(o.positionBasedOptimizations=e.$.positionBasedOptimizations),e.frames[0].frame.forEach((function(e){var r=new Frame;null==e.$.code?e.$.fullTexture?r.fullTexture=!0:(r.x=+e.$.x,r.y=+e.$.y,r.w=+e.$.w,r.h=+e.$.h):r.code=e.$.code,r.t=+e.$.t,o.frames[e.$.name]=r})),e.layers[0].layer.forEach((function(e){var r=new Layer;r.x=e.$.x,r.y=e.$.y,r.frames=e.frame?e.frame.map((function(e){return e.$.name})):[],o.layers[e.$.name]=r})),e.states[0].state.forEach((function(e){var r=new State;r.layers=e.layer?e.layer.map((function(e){return e.$.name})):[],e.$.flip&&(r.flip=e.$.flip),o.states[e.$.name]=r})),o}function copyFileSync(e,o){var r=fs.readFileSync(e);fs.writeFileSync(o,r)}function deleteFolderRecursive(e){fs.existsSync(e)&&(fs.readdirSync(e).forEach((function(o,r){var n=e+"/"+o;fs.lstatSync(n).isDirectory()?deleteFolderRecursive(n):fs.unlinkSync(n)})),fs.rmdirSync(e))}function listPackages(e){e?request("https://clockworkdev.github.io/ClockworkPackages/packages/"+e+"/versions.json",(function(o,r,n){o||200!=r.statusCode||(console.log("Versions of "+e+":"),JSON.parse(n).forEach((function(e){console.log(" "+e.version+" published at "+e.date)})))})):request("https://clockworkdev.github.io/ClockworkPackages/packages/packages.json",(function(e,o,r){e||200!=o.statusCode||(console.log("Packages published:"),JSON.parse(r).forEach((function(e){console.log(" "+e.id+" by "+e.by)})))}))}function register(e,o,r){request.post({url:"http://cwpm.azurewebsites.net/api/developers",form:{name:e,email:o,password:r}},(function(e,o,r){"OK"==JSON.parse(r).res?console.log("User registered successfully"):console.log("Error registering your account. Maybe that username is already taken?")}))}function tryPublish(e,o,r){fs.access("clockwork-packages.repo",fs.constants.F_OK,(n=>{n?console.log("Please execute this command in the Clockwork Packages root folder (where the clockwork-packages.repo is)"):fs.copy(e,`./packages/${o}/${r}/components.js`,(n=>{n?console.log(n):(console.log("Package saved"),fs.readFile(e,"utf8",((e,n)=>{if(e)console.log(e);else{fs.outputFile(`./doc/${o}/${r}/doc.html`,geardoc.generateDoc(n),(e=>{console.log(e||"Documentation saved")}));const e=`packages/${o}/versions.json`;fs.access(e,fs.constants.F_OK,(o=>{var n=o?[]:JSON.parse(fs.readFileSync(e,{encoding:"utf8"}));(n=n.filter((e=>e.version!=r))).push({version:r,date:new Date}),o?fs.appendFile(e,JSON.stringify(n,null,4),(e=>{console.log(e||"Version list updated")})):fs.writeFile(e,JSON.stringify(n,null,4),(e=>{console.log(e||"Version list updated")}))}));const t="packages/packages.json";fs.access(t,fs.constants.F_OK,(e=>{var r=e?[]:JSON.parse(fs.readFileSync(t,{encoding:"utf8"}));0==r.filter((e=>e.id==o)).length&&exec("git config --global user.name",((e,n,s)=>{var i=n.replace("\n","");r.push({id:o,by:i}),e?fs.appendFile(t,JSON.stringify(r,null,4),(e=>{console.log(e||"Package list updated")})):fs.writeFile(t,JSON.stringify(r,null,4),(e=>{console.log(e||"Package list updated")}))}))}))}})))}))}))}function addPackage(e,o,r){if(void 0!==o){var n=readManifest();null!=n?void 0===n.dependencies[o]?t():e({properties:{confirm:{description:"This package is already a dependency, do you want to change the version? (Y/N)",pattern:/Y|N/,required:!0}}},(function(e,o){"Y"==o.confirm&&t()})):console.log("There is no Clockwork project in the working folder")}else console.log("You must specify a module");function t(){request("http://cwpm.azurewebsites.net/api/packages/"+o,(function(e,t,s){if(!e&&200==t.statusCode){var i=JSON.parse(s);if(0==i.length)return void console.log("This package can't be found on the online repository.");if(void 0===r){var a=i.sort((function(e,o){return new Date(o.date)-new Date(e.date)}))[0].version;n.dependencies[o]=a,writeManifest(n,(function(e){e?console.log("An error happened while trying to update the manifest"):console.log("Version "+a+" of "+o+" added to the dependencies")}))}else i.filter((function(e){return e.version==r})).length>0?(n.dependencies[o]=r,writeManifest(n,(function(e){e?console.log("An error happened while trying to update the manifest"):console.log("Version "+r+" of "+o+" added to the dependencies")}))):console.log("This version can't be found. Please list all the published versions with 'clockwork list "+o+"'")}}))}}function updatePackage(e){var o=readManifest();function r(e){return new Promise((function(r,n){request("http://cwpm.azurewebsites.net/api/packages/"+e,(function(n,t,s){if(!n&&200==t.statusCode){var i=JSON.parse(s);if(0==i.length)console.log("No versions of the module "+e+" have been found in the online repository.");else{var a=i.sort((function(e,o){return new Date(o.date)-new Date(e.date)}))[0].version;o.dependencies[e]!=a?(console.log(e+" updated from "+o.dependencies[e]+" to "+a),o.dependencies[e]=a):console.log(e+" is already up to date")}r()}}))}))}null!=o?void 0===e?Promise.all(Object.keys(o.dependencies).map((function(e){return r(e)}))).then((function(){writeManifest(o)})):r(e).then((function(){writeManifest(o)})):console.log("There is no Clockwork project in the working folder")}function runBridge(e,o){if(bridges[e])buildProject((function(r){fs.existsSync(rootPath+e)||fs.mkdirSync(rootPath+e),bridges[e](r,rootPath+e),o&&o(!0)}));else{for(var r in console.log("This bridge can't be found, the following bridges are available:"),bridges)console.log(" "+r);o&&o(!1)}}function help(){console.log("The following commands are allowed:"),console.log("\n > clockwork init <projectName>"),console.log("   Creates an empty Clockwork project in the working directory"),console.log("\n > clockwork build"),console.log("   Builds the Clockwork project in the working directory, generating a .cw file"),console.log("\n > clockwork list"),console.log("   Lists the Clockwork modules available in the online repository"),console.log("\n > clockwork list <moduleName>"),console.log("   Lists the versions of that module available in the online repository"),console.log("\n > clockwork add <moduleName>"),console.log("   Adds the last version of the specified module as a dependency of the current project"),console.log("\n > clockwork add <moduleName> <moduleVersion>"),console.log("   Adds the specified version of the specified module as a dependency of the current project"),console.log("\n > clockwork update <moduleName>"),console.log("   Updates the dependency to the specified package to the latest published version"),console.log("\n > clockwork update"),console.log("   Updates the dependencies to all the packages to the latest published versions"),console.log("\n > clockwork publish"),console.log("   Publishes a module in the Clockwork online repository"),console.log("\n > clockwork bridge <bridgeName>"),console.log("   Uses the specified bridge to export the game")}module.exports=function(e,o,r,n){return rootPath=e,r&&(log=r),n&&(showError=n),{createProject:createProject,buildProject:buildProject,listPackages:listPackages,addPackage:addPackage.bind(null,o),updatePackage:updatePackage,register:register,tryPublish:tryPublish.bind(null,o),runBridge:runBridge}}})();
//# sourceMappingURL=/sm/2446be7f5559d04e3c183bdd896a1de946f0e772ee3f651366b9f6edaad4db5f.map