utiller 1.0.470 → 1.0.471
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_path2=_interopRequireDefault(require("path")),_fs=_interopRequireDefault(require("fs")),_promises=_interopRequireDefault(require("fs/promises")),_lodash=_interopRequireDefault(require("lodash")),_child_process=_interopRequireDefault(require("child_process")),_configerer=require("configerer"),_index=_interopRequireDefault(require("./index")),_index2=_interopRequireDefault(require("../exceptioner/index")),
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_path2=_interopRequireDefault(require("path")),_fs=_interopRequireDefault(require("fs")),_promises=_interopRequireDefault(require("fs/promises")),_lodash=_interopRequireDefault(require("lodash")),_child_process=_interopRequireDefault(require("child_process")),_configerer=require("configerer"),_index=_interopRequireDefault(require("./index")),_index2=_interopRequireDefault(require("../exceptioner/index")),_del=_interopRequireDefault(require("del")),_fsExtra=_interopRequireDefault(require("fs-extra")),_inquirer=_interopRequireDefault(require("inquirer"));class NodeUtiller extends _index.default{constructor(...e){super(...e),(0,_defineProperty2.default)(this,"isPersistIntoLogFile",!0),(0,_defineProperty2.default)(this,"findFilePathByExtension",(e,t=[],...i)=>{const s=new RegExp(`^[^.].+.(${_lodash.default.join(t,"|")})$`);return this.findFilePathBy(e,e=>s.test(e.fileNameExtension),...i)}),(0,_defineProperty2.default)(this,"executeCommandLine",async e=>{const t=this;return this.appendInfo(`執行腳本 ${e}`),new Promise(function(i,s){_child_process.default.exec(e,(e,n,a)=>{if(t.appendInfo(`${n}`),t.appendInfo(`${a}`),e)return t.appendError(`執行錯誤: ${e}`),void s(e);i(n.trim())})})}),(0,_defineProperty2.default)(this,"getStringOfTerserCommandLine",e=>{const t=[];if(e.compress){const i=[];e.compress.drop_console&&i.push("drop_console=true"),e.compress.drop_debugger&&i.push("drop_debugger=true"),e.compress.passes&&i.push(`passes=${e.compress.passes}`),e.compress.dead_code&&i.push("dead_code=true"),e.compress.unused&&i.push("unused=true"),i.length>0&&t.push(`--compress ${i.join(",")}`)}return!0===e.mangle&&t.push("--mangle"),e.format&&(!0===e.format.beautify&&t.push("--beautify"),!1===e.format.comments?t.push("--no-comments"):"all"===e.format.comments?t.push("--comments all"):e.format.comments&&
|
|
2
2
|
// 例如:comments: /@license|@preserve/
|
|
3
|
-
t.push(`--comments "${e.format.comments}"`),e.format.indent_level&&t.push(`--format indent_level=${e.format.indent_level}`)),t.join(" ")}),(0,_defineProperty2.default)(this,"getPathAfterSpecificFolder",(e,t="src")=>{const i=e.split(_path2.default.sep);for(let e=i.length-1;e>=0;e--)if(i[e]===t)return"/"+i.slice(e+1).join("/");return""}),(0,_defineProperty2.default)(this,"getPathAfterSrc",e=>this.getPathAfterSpecificFolder(e))}findSpecificFolderByPath(e,t){const i=_path2.default.resolve(e).split(_path2.default.sep);for(;i.length;){const e=_path2.default.join(...i,t);if(_fs.default.existsSync(e))return e;i.pop()}return null}async getPDFText(e){let t=_fs.default.readFileSync(e);return(0,_pdfParse.default)(t).then(e=>e)}printf(){this.appendInfo("i can use in node.js only yo yo")}findFilePathBy(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return[];const s=[],a=_fs.default.readdirSync(e,{withFileTypes:!0});for(const n of a){if(i.includes(n.name))continue;const a=_path2.default.join(e,n.name);if(n.isDirectory())s.push(...this.findFilePathBy(a,t,...i));else if(n.isFile()){const e=this.getPathInfo(a);t(e)&&s.push(e)}}return s}isPathExist(e){return _fs.default.existsSync(e)}renameFile(e,t="fileName"){if(!this.isFile(e)||!t)return void this.appendError(`renameFile 錯誤, path: ${e}, newName: ${t}`);const i=_path2.default.dirname(e),s=_path2.default.extname(e),a=_path2.default.join(i,`${t}${s}`);_fs.default.renameSync(e,a)}getPathInfo(e){const t=_path2.default.resolve(e),i={path:e,absolute:t,isFile:!1,isDirectory:!0,dirName:void 0,folderName:void 0,dirPath:void 0,folderPath:void 0,extension:void 0,fileName:void 0,fileNameExtension:void 0,lastModifiedTime:void 0,name:void 0};if(this.isFile(t)){i.extension=t.split(".").pop();const e=t.split("/").pop().split(".");e.pop(),i.fileName=e.join("."),i.name=e.join("."),i.dirName=_lodash.default.nth(t.split("/"),-2),i.folderName=_lodash.default.nth(t.split("/"),-2),i.isFile=!0,i.dirPath=this.getFolderPathOfSpecificPath(t),i.folderPath=this.getFolderPathOfSpecificPath(t),i.isDirectory=!1,i.fileNameExtension=`${i.fileName}.${i.extension}`,i.lastModifiedTime=this.getFileLastModifiedTime(t)}return this.isDirectory(t)&&(i.dirName=t.split("/").pop()),i}syncExecuteCommandLine(e){const t=this;this.appendInfo(`執行腳本 ${e}`),_child_process.default.exec(`${e}`,(e,i,s)=>{t.appendInfo(`${i}`),t.appendInfo(`${s}`),null!==e&&t.appendError(`exec error: ${e}`)})}persistByPath(e){const t=_path2.default.isAbsolute(e),i=e.split("/").filter(Boolean),s=i[i.length-1],a=""!==_path2.default.extname(s);let n=t?_path2.default.sep:"";for(let e=0;e<i.length;e++)n=_path2.default.join(n,i[e]),_fs.default.existsSync(n)||(e===i.length-1&&a?_fs.default.writeFileSync(n,""):_fs.default.mkdirSync(n,{recursive:!1}));return _path2.default.resolve(e)}async copyFromFolderToDestFolder(e,t,i=!0,s=!1,a=()=>!0){if(!_fs.default.existsSync(e)||!_fs.default.existsSync(e))throw new _index2.default(8009,`${e} or ${t} is not exist!`);this.appendInfo(`正在複製ing ${e}/* => ${t}/* succeed`),_fsExtra.default.copySync(e,t,{preserveTimestamps:s,override:i,filter:a}),this.appendInfo(`複製成功 ${e}/* => ${t}/* succeed`)}cleanAllFiles(e){this.isDirectory(e)&&(this.appendInfo(`準備清除底下的所有 ${e}`),_fsExtra.default.emptyDirSync(e),this.appendInfo(`成功清除底下的所有 ${e}`))}async deleteSelfByPath(e,t){_fs.default.existsSync(e)&&(this.appendInfo(`準備刪掉 ${e},{force:${t}}`),await(0,_del.default)(e,{force:t}),this.appendInfo(`成功刪掉了 ${e}`))}async deleteFileOrFolder(e){this.appendInfo(`刪掉了 ${e}`),await(0,_del.default)(e)}async deleteChildByPath(e,t=!1){const i=this.getChildPathByPath(e);for(const e of i)await this.deleteSelfByPath(e.absolute,t)}getFileCountsOfFolder(e){return this.isDirectory(e)?_fs.default.readdirSync(e).length:-1}async reinstallNodeModules(e="../",...t){const i=[...t,"node_modules","utiller","configerer"],s=this.findFilePathBy(e,e=>_lodash.default.isEqual(e.fileNameExtension,"package.json"),...i);for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`,s=`${t}package-lock.json`;await(0,_del.default)(s),this.appendInfo(`刪掉了 ${s}`),await(0,_del.default)(i),this.appendInfo(`刪掉了 ${i}`)}for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`;_fs.default.existsSync(i)||await this.executeCommandLine(`cd ${t} && npm install`)}}getNamesOfFolderChild(e){return this.getChildPathByPath(e).filter(e=>e.isDirectory).map(e=>e.dirName)}getChildPathByPath(e){try{return _fs.default.readdirSync(e).map(t=>this.getPathInfo(_path2.default.join(e,t)))}catch(e){throw new _index2.default(8002,e)}}copySingleFile(e,t,i,s=!1){const a=i&&i.trim()?_path2.default.join(t,i):t;if(_fs.default.existsSync(a)&&!s)throw new _index2.default(8006,a);_fs.default.copyFileSync(e,a)}ensureFolderExists(e){const t=_path2.default.resolve(e);_fs.default.existsSync(t)||_fs.default.mkdirSync(t,{recursive:!0})}getNodeEnvVariable(e,t=void 0){const i=process.env[e];return void 0===i?t:i}isDirectory(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isDirectory()}isFile(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isFile()}isImageFile(e){return["svg","png","jpg","jpeg"].includes(e.extension)}async cleanChildFiles(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return!1;const s=this.findFilePathBy(e,t,...i),a=s.filter(e=>!this.isImageFile(e));return await Promise.allSettled(a.map(e=>(this.cleanFileContent(e.absolute),this.appendInfo(`成功 cleanChildFiles() -> '${e.path}'`),Promise.resolve()))),s}cleanFileContent(e){this.syncDeleteFile(e)}async syncWithExistPackage(e="../"){const t=this.findFilePathBy(e,e=>_lodash.default.isEqual(e.fileNameExtension,"package.json"),"node_modules");for(let e of t)try{_lodash.default.isEqual(e.dirName,"..")||this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${e.dirName}`,`cd ${this.getFolderPathOfSpecificPath(e.absolute)}`)}catch(e){this.appendInfo(e.message)}}async packageTemplatify(e,t){const i=this.getChildPathByPath(e).map(e=>e.absolute.split("/").pop());if(this.has(i,t))throw new _index2.default(8004,` packageName ===> '${t}'`);const s=`${e}/${t}`;_fs.default.mkdirSync(s),_fs.default.copyFileSync("./template/sample.babel.config.js",`${s}/babel.config.js`),_fs.default.copyFileSync("./template/sample.terser.config.js",`${s}/terser.config.js`);const a=this.getJsonObjByFilePath("./template/sample.package.json");a.name=t,this.writeFileInJSON(`${s}/package.json`,a),this.persistByPath(`${s}/src`);const n=String.format(this.getFileContextInRaw("./template/sample.src.index.js"),t,"明悅",new Date);_fs.default.writeFileSync(`${s}/src/index.js`,n);const r=`${this.findSpecificFolderByPath(s,".idea")}/workspace.xml`;if(this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${t}`,`cd ${_path2.default.resolve(s)}`),_fs.default.existsSync(r)){const e=this.getFileContextInRaw(r).split("\n"),i=_lodash.default.findIndex(e,e=>this.has(e,'name="RunManager'));this.insertToArray(e,i,`<configuration name="${t}" \n type="NodeJSConfigurationType" \n path-to-node="$USER_HOME$/.nvm/versions/node/v20.19.5/bin/node" \n node-parameters="--require @babel/register" \n path-to-js-file="${_path2.default.resolve(s)}/src/index.js" \n working-dir="${_path2.default.resolve(s)}" >`," <envs>",' <env name="self_debug" value="true" />',' <env name="is_node" value="true" />'," </envs>",' <method v="2" />',"</configuration>");const a=_lodash.default.findIndex(e,e=>_lodash.default.isEqual(_lodash.default.trim(e),"<list>"),i);this.insertToArray(e,a,` <item itemvalue="Node.js.${t}" />`),_fs.default.writeFileSync(r,e.join("\n"))}else this.appendError(`${r} not exist`);await this.executeCommandLine(`cd ${_path2.default.resolve(s)} && npm install`),this.appendInfo(`build ${t} succeed!`)}appendInfo(...e){return this.appendLog(_configerer.configerer.PATH_INFO_LOG,e,!1)}appendError(...e){return this.appendLog(_configerer.configerer.PATH_ERROR_LOG,e,!0)}appendLog(e,t,i=!1){const s=`${this.getCurrentTimeFormat()} ${i?"ERROR":"LOG"} : ${t.map(this.stringifyLog).join(" ,")}`;this.isProductionEnvironment()||(i?console.error(...t):console.log(...t)),this.isPersistIntoLogFile&&this.appendFile(e,s)}stringifyLog(e){return"object"==typeof e?JSON.stringify(e):String(e)}appendFile(e,t,i=!0,s=!1){try{const a=_path2.default.resolve(e);s&&_fs.default.existsSync(a)&&_fs.default.unlinkSync(a),_fs.default.existsSync(a)||this.persistByPath(a);const n=`${i?"\n":""}${t}`;_fs.default.appendFileSync(a,n)}catch(e){throw new _index2.default(8001,e)}}disableLogMessagePersistent(){this.isPersistIntoLogFile=!1}getLogString(e){return e.map(e=>this.isJson(e)||_lodash.default.isObject(e)||_lodash.default.isArray(e)?this.deepFlat(e):e).join(" ,")}async persistJsonFilePrettier(e,t,i=!1){e=_path2.default.resolve(e),this.appendFile(e,JSON.stringify(t),!0,!0),i||await this.prettier(e,120)}printCollectionToFile(e){const t=`./logs/__temp_${this.getCurrentTimeFormat()}.txt`;this.persistByPath("./logs/"),this.appendFile(t,this.deepFlat(e," \n\n, ")),this.appendInfo(`collectionToFile succeed, file name ==> ${t}`)}async readFileContentByPath(e,t={}){return t[e]??(t[e]=await _promises.default.readFile(e,"utf-8"))}singleFileTemplatify(e="./"){const t=this.findFilePathByExtension(e,["js"],"node_modules");for(const e of t){const t=this.getFileContextInRaw(e.absolute).trim();if(_lodash.default.isEmpty(t)){this.appendInfo(e.fileName,e.absolute);const t=_lodash.default.isEqual(e.fileName,"index")?e.dirName:e.fileName;_fs.default.writeFileSync(e.absolute,String.format(this.getFileContextInRaw(".\n /template/s\n ample.src.index.js"),t,"明悅",new Date))}}}isFileEmpty(e){const t=this.getFileContextInRaw(e);return!t||!t.trim()}copySingleFileConservative(e,t){const{absolute:i,lastModifiedTime:s}=t;if(!this.isPathExist(i)||this.isFileEmpty(i))return void this.appendInfo(`${i} is empty file, ignore copy behavior`);const a=_fs.default.existsSync(e);a&&this.getFileLastModifiedTime(e)>s?this.appendInfo(`${e} is the latest, ignore this run`):(a||this.appendInfo(`${e} does not exist, safe to copy.`),this.ensureFolderExists(_path2.default.dirname(e)),this.copySingleFile(i,e,void 0,!0))}syncDeleteFile(e){_fs.default.existsSync(e)&&_fs.default.unlinkSync(e)}getFileContextInJSON(e){try{if(_fs.default.existsSync(e))return JSON.parse(_fs.default.readFileSync(e,"utf-8"))}catch(e){throw new _index2.default(9999,e.message)}return{}}getFileContextInRaw(e){return _fs.default.existsSync(e)?_fs.default.readFileSync(e,"utf-8"):""}writeFileInJSON(e,t){let i=JSON.stringify(t,null,2);_fs.default.writeFileSync(e,i)}async generatePackage(e="./",t=!1,i=!0,...s){let a=this.findFilePathByExtension(e,["json"],"node_modules","release");a=_lodash.default.filter(a,e=>_lodash.default.isEqual(e.fileName,"package")),a=a.map(e=>this.getFolderPathOfSpecificPath(e.absolute));for(const e of a)if(this.isAndEquals(...s.map(t=>()=>!this.has(e,t)))){const s=await this.generateTempFolderWithCleanSrc(e);await this.deleteSelfByPath(_path2.default.join(e,"release"),!0);const a=this.persistByPath(_path2.default.join(e,"release"));await this.executeCommandLine(`cd ${e} && babel ./temp --out-dir ./release/lib --config-file ./babel.config.js`);const n=require(_path2.default.join(e,"./terser.config.js")),r=this.getStringOfTerserCommandLine(n);await this.executeCommandLine(`cd ${e}/release/lib && find . -type f -name "*.js" -exec terser {} -o {} ${r} \\;`);const o=_path2.default.join(e,"package.json");try{const s="sample.npm.module.index.js";this.copySingleFile(`/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/${s}`,a,"index.js",!0);const n=`${e}/release/index.js`;await this.executeCommandLine(`terser ${n} -o ${n} ${r}`);const l=_path2.default.join(e,"template");if(this.isPathExist(l)&&await this.copyFromFolderToDestFolder(l,this.persistByPath(_path2.default.join(a,"template"))),t){const{moduleName:e,version:t}=await this.upgradePackageJsonVersion(o);await this.updateVersionOfTemplate(e,t)}this.copySingleFile(o,_path2.default.join(a,"package.json"),void 0,!0),i||!this.isPathExist(_path2.default.join(a,"node_module"))?await this.executeCommandLine(`cd ${a} && yarn install --production`):this.appendInfo("ignore node-module install behavior"),this.appendInfo(`build ${e} succeed`),t&&await this.executeCommandLine(`cd ${a} && npm publish`)}catch(e){throw await this.deleteSelfByPath(a,!0),new _index2.default(9999,`generatePackage 報錯, ${e.message}`)}finally{await this.deleteSelfByPath(s,!0)}}}async updateVersionOfTemplate(e,t){const i=["/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/admin.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/web.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/functions.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/sample.package.json","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/package.json"];for(const s of i)if(this.isPathExist(s)){console.log("🦴正在修改以下 path的版本 => ",s);let i=!1;const a=this.getJsonObjByFilePath(s);if(a&&a.dependencies&&a.dependencies[e]){a.dependencies[e]=`^${t}`;try{await this.writeJsonThanPrettier(s,a),i=!0}catch(e){i=!1}}i||await this.updateFileOfSpecificLine(s,i=>` "${e}":"^${t}"${_lodash.default.endsWith(_lodash.default.trim(i),",")?",":""}`,t=>_lodash.default.startsWith(_lodash.default.trim(t),`"${e}"`)),console.log("💯成功修改以下 path的版本 => ",s)}console.log("離開updateVersionOfTemplate()的迴圈"),await this.copyFromFolderToDestFolder("/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/","/Users/davidtu/cross-achieve/high/idea-inventer/newp/template/",!0,!0)}async updateFileOfSpecificLine(e,t=e=>"updated",i=e=>!0){const s=this.getFileContextInRaw(e).split("\n"),a=s.findIndex(i);-1!==a&&(s[a]=t(s[a]),this.appendFile(e,s.join("\n"),!0,!0),await this.prettier(e))}async writeJsonThanPrettier(e,t){this.writeFileInJSON(e,t),await this.prettier(e)}async enrichEachPackageJson(e){const t=new Set(["package","admin.package","web.package","functions.package"]),i=this.findFilePathByExtension(e,["json"],"gen","node_modules","release").filter(e=>t.has(e.fileName));if(0!==i.length)for(const{absolute:e}of i){const t=this.getJsonObjByFilePath(e);t.scripts||={},t.scripts.updateConfigerer="npm update configerer --save",await this.writeJsonThanPrettier(e,t)}}insertShellCommand(e=_configerer.configerer.BASE_SHELL_SCRIPT,t,i){if(this.isStringContainInLines(this.getFileContextInRaw(e),t))throw new _index2.default(8007,`alias ${t} is exist`);{const s=`alias ${t}='${i}'`;this.appendFile(e,s)}}getAdminCredential(){return this.getJsonObjByFilePath("/Users/davidtu/cross-achieve/mimi/idea-inventer/firebaser/key/mimi19up-firebase-adminsdk.json")}isEmptyFile(e){return!this.isPathExist(e)||_lodash.default.isEmpty(this.getFileContextInRaw(e).trim())}isEmptyFolder(e){return 0===_fs.default.readdirSync(e).length}async prettier(e,t=250,i=[".mustache"]){const s=_path2.default.resolve(e),a=_path2.default.resolve("."),n=i.find(t=>e.endsWith(t));let r=s,o=!!n;try{if(o){const e=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t=new RegExp(`${e}$`);r=s.replace(t,""),await _fs.default.rename(s,r)}await this.executeCommandLine(`cd "${a}" && npx prettier --write "${r}" --print-width ${t} --ignore-unknown`)}catch(t){console.error(`Prettier 執行錯誤 [${e}]:`,t.message)}finally{if(o&&r!==s)try{await _fs.default.access(r),await _fs.default.rename(r,s)}catch(e){}}}getFileLastModifiedTime(e){return _fs.default.statSync(e).mtimeMs}getJsonObjByFilePath(e){return this.appendInfo(`ready to json path:${e}`),JSON.parse(this.getFileContextInRaw(e))}async upgradePackageJsonVersion(e){if(_lodash.default.isEqual("json",this.getPathInfo(e).extension)){const t=this.getJsonObjByFilePath(e);return t.version=this.getStringOfVersionIncrement(t.version),await this.writeJsonThanPrettier(e,t),{version:t.version,moduleName:t.name}}throw new _index2.default(8020,`path is not package.json, which is ${e}`)}async reWriteJsonAttribute(e,...t){const{extension:i}=this.getPathInfo(e);if("json"!==i)throw new _index2.default(9999,`reWriteJsonAttribute() => path is not package.json, which is ${e}`);const s=t.find(e=>"object"!=typeof e||null===e);if(s)throw new _index2.default(9999,`84451515 attr is not object, which is 'type=${typeof s} => ${s}'`);const a=this.getJsonObjByFilePath(e);for(const e of t)a[this.getObjectKey(e)]=this.getObjectValue(e);return await this.writeJsonThanPrettier(e,a),{version:a.version,moduleName:a.name}}getVersionOfPackageJson(e){return this.getAttributeValueOfJson(e,"version","1.0.0")}getAttributeValueOfJson(e,t,i=void 0){if(_lodash.default.isEqual("json",this.getPathInfo(e).extension))return this.getJsonObjByFilePath(e)[t]??i;throw new _index2.default(8020,`path is not package.json, which is ${e}`)}getVersionOfJsFile(e){return this.getAttributeValueOfJsFile(e,"version","project without version notice")}getAttributeValueOfJsFile(e,t,i=void 0){if(_lodash.default.isEqual(this.getExtensionFromPath(e),"js"))return require(_path2.default.resolve(e)).default[t]??i;throw new _index2.default(8020,`path is not js file, which is ${e}`)}async rewriteAttributeOfSourceJs(e,...t){if(!this.isPathExist(e))throw new _index2.default(9999,`4849813 ${e} is not exist`);for(const i of t){if(!_lodash.default.isObject(i))throw new _index2.default(9999,`4984651 attr is not object, which is 'type=${typeof i} => ${i}'`);const t=this.getObjectKey(i),s=this.getObjectValue(i),a=this.getFileContextInRaw(e).split("\n");a[_lodash.default.findIndex(a,e=>_lodash.default.startsWith(_lodash.default.trim(e),`${t}`))]=` ${t}: '${s}',`,this.appendFile(e,a.join("\n"),!0,!0)}return t}async getAnswerFromPromptQ(e=[{name:"name",require:!0,description:"type the name"}]){return _prompt.default.start(),await _prompt.default.get(e)}async getObjectFromPromptQ(...e){return _prompt.default.start(),await _prompt.default.get(e)}async generateTempFolderWithCleanSrc(e){this.appendInfo("generateTempFolderWithCleanSrc",e);const t=_path2.default.join(e,"src"),i=_path2.default.join(e,"temp");if(!_fs.default.existsSync(t))return i;this.appendInfo("generateTempFolderWithCleanSrc","source",t),this.persistByPath(i),await this.copyFromFolderToDestFolder(t,i);const s=this.findFilePathBy(i);for(const{absolute:e}of s){const t=this.getFileContextInRaw(e).split("\n"),i=t.map(e=>e.trim()),s=i.findIndex(e=>e.startsWith("if (configerer.DEBUG_MODE)")),a=i.lastIndexOf("}");if(s>=0&&a>s){t.splice(s,a-s+1);const i=t.join("\n");this.appendFile(e,i,!0,!0),await this.executeCommandLine(`cd ${_path2.default.dirname(e)} && npx prettier --write "${e}"`)}}return i}rewriteFile2File(e,t){const i=this.getFileContextInRaw(e);if(!i.trim())throw new _index2.default(9999,`${e} 為空,避免覆蓋`);this.appendFile(t,i,!0,!0),this.appendInfo(`rewrite from:${e} => to:${t} 成功`)}getStringOfHeadOfFile(e){if(this.isPathExist(e)){const t=this.getFileContextInRaw(e);return _lodash.default.head(t.split("\n"))}return""}isFileEditSucceed(e){if(!this.isPathExist(e))return!1;const t=this.getPathInfo(e),i=this.getFileContextInRaw(e).trim();if(""===i)return this.appendInfo(`74985465 path ${t.path} is empty file, file would not persist`),!1;try{const e=i.split("\n")[0].match(/const\s+([a-zA-Z_]\w*)\s*=\s*(true|false)\s*;?/);if(!e||_lodash.default.size(e)<3)return!1;if(!0==("true"===e[2]))return!0}catch(e){return this.appendError(`66445411 ${e.message}`),!1}return!1}joinRespectingDot(...e){const t=e[0]?.startsWith("./"),i=e[0]?.startsWith("./")?[e[0].slice(2),...e.slice(1)]:e,s=_path2.default.join(...i);return t&&!_path2.default.isAbsolute(s)?`./${s}`:s}}var _default=exports.default=NodeUtiller;
|
|
3
|
+
t.push(`--comments "${e.format.comments}"`),e.format.indent_level&&t.push(`--format indent_level=${e.format.indent_level}`)),t.join(" ")}),(0,_defineProperty2.default)(this,"transformConfigs",e=>e.map(e=>({type:"input",name:e.name,message:e.description||e.name,validate:t=>!(e.require&&!t.trim())||`${e.name} is required!`}))),(0,_defineProperty2.default)(this,"getAnswerFromPromptQ",async(e=[{name:"name",require:!0,description:"type the name"}])=>{const t=this.transformConfigs(e);return _inquirer.default.prompt(t)}),(0,_defineProperty2.default)(this,"interactionByTerminalQ",async e=>{const t=e.map(e=>e.name),i=e.map(e=>e.path),s=new Set(t).size!==t.length,n=new Set(i).size!==i.length;if(s||n){const e=s?"專案「陣列裡」名稱 (name)":"專案「陣列裡」路徑 (path)";console.error(`[31m錯誤: 偵測到重複的 ${e},請檢查資料來源。[0m`),process.exit(1)}const a=e.map(e=>({name:`${e.name} (${e.path})`,value:e}));try{return(await _inquirer.default.prompt([{type:"checkbox",name:"selectedProjects",message:'請選擇要執行的子項 (空白鍵勾選,"a" 鍵全選,Enter 確認):',choices:a,validate:e=>!(e?.length<1)||"請至少選擇一個子項!"}])).selectedProjects}catch(e){return console.error("執行選單時發生錯誤:",e?.message??"未知錯誤"),[]}}),(0,_defineProperty2.default)(this,"getPathAfterSpecificFolder",(e,t="src")=>{const i=e.split(_path2.default.sep);for(let e=i.length-1;e>=0;e--)if(i[e]===t)return"/"+i.slice(e+1).join("/");return""}),(0,_defineProperty2.default)(this,"getPathAfterSrc",e=>this.getPathAfterSpecificFolder(e))}findSpecificFolderByPath(e,t){const i=_path2.default.resolve(e).split(_path2.default.sep);for(;i.length;){const e=_path2.default.join(...i,t);if(_fs.default.existsSync(e))return e;i.pop()}return null}printf(){this.appendInfo("i can use in node.js only yo yo")}findFilePathBy(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return[];const s=[],n=_fs.default.readdirSync(e,{withFileTypes:!0});for(const a of n){if(i.includes(a.name))continue;const n=_path2.default.join(e,a.name);if(a.isDirectory())s.push(...this.findFilePathBy(n,t,...i));else if(a.isFile()){const e=this.getPathInfo(n);t(e)&&s.push(e)}}return s}isPathExist(e){return _fs.default.existsSync(e)}renameFile(e,t="fileName"){if(!this.isFile(e)||!t)return void this.appendError(`renameFile 錯誤, path: ${e}, newName: ${t}`);const i=_path2.default.dirname(e),s=_path2.default.extname(e),n=_path2.default.join(i,`${t}${s}`);_fs.default.renameSync(e,n)}getPathInfo(e){const t=_path2.default.resolve(e),i={path:e,absolute:t,isFile:!1,isDirectory:!0,dirName:void 0,folderName:void 0,dirPath:void 0,folderPath:void 0,extension:void 0,fileName:void 0,fileNameExtension:void 0,lastModifiedTime:void 0,name:void 0};if(this.isFile(t)){i.extension=t.split(".").pop();const e=t.split("/").pop().split(".");e.pop(),i.fileName=e.join("."),i.name=e.join("."),i.dirName=_lodash.default.nth(t.split("/"),-2),i.folderName=_lodash.default.nth(t.split("/"),-2),i.isFile=!0,i.dirPath=this.getFolderPathOfSpecificPath(t),i.folderPath=this.getFolderPathOfSpecificPath(t),i.isDirectory=!1,i.fileNameExtension=`${i.fileName}.${i.extension}`,i.lastModifiedTime=this.getFileLastModifiedTime(t)}return this.isDirectory(t)&&(i.dirName=t.split("/").pop()),i}syncExecuteCommandLine(e){const t=this;this.appendInfo(`執行腳本 ${e}`),_child_process.default.exec(`${e}`,(e,i,s)=>{t.appendInfo(`${i}`),t.appendInfo(`${s}`),null!==e&&t.appendError(`exec error: ${e}`)})}persistByPath(e){const t=_path2.default.isAbsolute(e),i=e.split("/").filter(Boolean),s=i[i.length-1],n=""!==_path2.default.extname(s);let a=t?_path2.default.sep:"";for(let e=0;e<i.length;e++)a=_path2.default.join(a,i[e]),_fs.default.existsSync(a)||(e===i.length-1&&n?_fs.default.writeFileSync(a,""):_fs.default.mkdirSync(a,{recursive:!1}));return _path2.default.resolve(e)}async copyFromFolderToDestFolder(e,t,i=!0,s=!1,n=()=>!0){if(!_fs.default.existsSync(e)||!_fs.default.existsSync(e))throw new _index2.default(8009,`${e} or ${t} is not exist!`);this.appendInfo(`正在複製ing ${e}/* => ${t}/* succeed`),_fsExtra.default.copySync(e,t,{preserveTimestamps:s,override:i,filter:n}),this.appendInfo(`複製成功 ${e}/* => ${t}/* succeed`)}cleanAllFiles(e){this.isDirectory(e)&&(this.appendInfo(`準備清除底下的所有 ${e}`),_fsExtra.default.emptyDirSync(e),this.appendInfo(`成功清除底下的所有 ${e}`))}async deleteSelfByPath(e,t){_fs.default.existsSync(e)&&(this.appendInfo(`準備刪掉 ${e},{force:${t}}`),await(0,_del.default)(e,{force:t}),this.appendInfo(`成功刪掉了 ${e}`))}async deleteFileOrFolder(e){this.appendInfo(`刪掉了 ${e}`),await(0,_del.default)(e)}async deleteChildByPath(e,t=!1){const i=this.getChildPathByPath(e);for(const e of i)await this.deleteSelfByPath(e.absolute,t)}getFileCountsOfFolder(e){return this.isDirectory(e)?_fs.default.readdirSync(e).length:-1}async reinstallNodeModules(e="../",...t){const i=[...t,"node_modules","utiller","configerer"],s=this.findFilePathBy(e,e=>_lodash.default.isEqual(e.fileNameExtension,"package.json"),...i);for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`,s=`${t}package-lock.json`;await(0,_del.default)(s),this.appendInfo(`刪掉了 ${s}`),await(0,_del.default)(i),this.appendInfo(`刪掉了 ${i}`)}for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`;_fs.default.existsSync(i)||await this.executeCommandLine(`cd ${t} && npm install`)}}getNamesOfFolderChild(e){return this.getChildPathByPath(e).filter(e=>e.isDirectory).map(e=>e.dirName)}getChildPathByPath(e){try{return _fs.default.readdirSync(e).map(t=>this.getPathInfo(_path2.default.join(e,t)))}catch(e){throw new _index2.default(8002,e)}}copySingleFile(e,t,i,s=!1){const n=i&&i.trim()?_path2.default.join(t,i):t;if(_fs.default.existsSync(n)&&!s)throw new _index2.default(8006,n);_fs.default.copyFileSync(e,n)}ensureFolderExists(e){const t=_path2.default.resolve(e);_fs.default.existsSync(t)||_fs.default.mkdirSync(t,{recursive:!0})}getNodeEnvVariable(e,t=void 0){const i=process.env[e];return void 0===i?t:i}isDirectory(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isDirectory()}isFile(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isFile()}isImageFile(e){return["svg","png","jpg","jpeg"].includes(e.extension)}async cleanChildFiles(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return!1;const s=this.findFilePathBy(e,t,...i),n=s.filter(e=>!this.isImageFile(e));return await Promise.allSettled(n.map(e=>(this.cleanFileContent(e.absolute),this.appendInfo(`成功 cleanChildFiles() -> '${e.path}'`),Promise.resolve()))),s}cleanFileContent(e){this.syncDeleteFile(e)}async syncWithExistPackage(e="../"){const t=this.findFilePathBy(e,e=>_lodash.default.isEqual(e.fileNameExtension,"package.json"),"node_modules");for(let e of t)try{_lodash.default.isEqual(e.dirName,"..")||this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${e.dirName}`,`cd ${this.getFolderPathOfSpecificPath(e.absolute)}`)}catch(e){this.appendInfo(e.message)}}async packageTemplatify(e,t){const i=this.getChildPathByPath(e).map(e=>e.absolute.split("/").pop());if(this.has(i,t))throw new _index2.default(8004,` packageName ===> '${t}'`);const s=`${e}/${t}`;_fs.default.mkdirSync(s),_fs.default.copyFileSync("./template/sample.babel.config.js",`${s}/babel.config.js`),_fs.default.copyFileSync("./template/sample.terser.config.js",`${s}/terser.config.js`);const n=this.getJsonObjByFilePath("./template/sample.package.json");n.name=t,this.writeFileInJSON(`${s}/package.json`,n),this.persistByPath(`${s}/src`);const a=String.format(this.getFileContextInRaw("./template/sample.src.index.js"),t,"明悅",new Date);_fs.default.writeFileSync(`${s}/src/index.js`,a);const r=`${this.findSpecificFolderByPath(s,".idea")}/workspace.xml`;if(this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${t}`,`cd ${_path2.default.resolve(s)}`),_fs.default.existsSync(r)){const e=this.getFileContextInRaw(r).split("\n"),i=_lodash.default.findIndex(e,e=>this.has(e,'name="RunManager'));this.insertToArray(e,i,`<configuration name="${t}" \n type="NodeJSConfigurationType" \n path-to-node="$USER_HOME$/.nvm/versions/node/v20.19.5/bin/node" \n node-parameters="--require @babel/register" \n path-to-js-file="${_path2.default.resolve(s)}/src/index.js" \n working-dir="${_path2.default.resolve(s)}" >`," <envs>",' <env name="self_debug" value="true" />',' <env name="is_node" value="true" />'," </envs>",' <method v="2" />',"</configuration>");const n=_lodash.default.findIndex(e,e=>_lodash.default.isEqual(_lodash.default.trim(e),"<list>"),i);this.insertToArray(e,n,` <item itemvalue="Node.js.${t}" />`),_fs.default.writeFileSync(r,e.join("\n"))}else this.appendError(`${r} not exist`);await this.executeCommandLine(`cd ${_path2.default.resolve(s)} && npm install`),this.appendInfo(`build ${t} succeed!`)}appendInfo(...e){return this.appendLog(_configerer.configerer.PATH_INFO_LOG,e,!1)}appendError(...e){return this.appendLog(_configerer.configerer.PATH_ERROR_LOG,e,!0)}appendLog(e,t,i=!1){const s=`${this.getCurrentTimeFormat()} ${i?"ERROR":"LOG"} : ${t.map(this.stringifyLog).join(" ,")}`;this.isProductionEnvironment()||(i?console.error(...t):console.log(...t)),this.isPersistIntoLogFile&&this.appendFile(e,s)}stringifyLog(e){return"object"==typeof e?JSON.stringify(e):String(e)}appendFile(e,t,i=!0,s=!1){try{const n=_path2.default.resolve(e);s&&_fs.default.existsSync(n)&&_fs.default.unlinkSync(n),_fs.default.existsSync(n)||this.persistByPath(n);const a=`${i?"\n":""}${t}`;_fs.default.appendFileSync(n,a)}catch(e){throw new _index2.default(8001,e)}}disableLogMessagePersistent(){this.isPersistIntoLogFile=!1}getLogString(e){return e.map(e=>this.isJson(e)||_lodash.default.isObject(e)||_lodash.default.isArray(e)?this.deepFlat(e):e).join(" ,")}async persistJsonFilePrettier(e,t,i=!1){e=_path2.default.resolve(e),this.appendFile(e,JSON.stringify(t),!0,!0),i||await this.prettier(e,120)}printCollectionToFile(e){const t=`./logs/__temp_${this.getCurrentTimeFormat()}.txt`;this.persistByPath("./logs/"),this.appendFile(t,this.deepFlat(e," \n\n, ")),this.appendInfo(`collectionToFile succeed, file name ==> ${t}`)}async readFileContentByPath(e,t={}){return t[e]??(t[e]=await _promises.default.readFile(e,"utf-8"))}singleFileTemplatify(e="./"){const t=this.findFilePathByExtension(e,["js"],"node_modules");for(const e of t){const t=this.getFileContextInRaw(e.absolute).trim();if(_lodash.default.isEmpty(t)){this.appendInfo(e.fileName,e.absolute);const t=_lodash.default.isEqual(e.fileName,"index")?e.dirName:e.fileName;_fs.default.writeFileSync(e.absolute,String.format(this.getFileContextInRaw(".\n /template/s\n ample.src.index.js"),t,"明悅",new Date))}}}isFileEmpty(e){const t=this.getFileContextInRaw(e);return!t||!t.trim()}copySingleFileConservative(e,t){const{absolute:i,lastModifiedTime:s}=t;if(!this.isPathExist(i)||this.isFileEmpty(i))return void this.appendInfo(`${i} is empty file, ignore copy behavior`);const n=_fs.default.existsSync(e);n&&this.getFileLastModifiedTime(e)>s?this.appendInfo(`${e} is the latest, ignore this run`):(n||this.appendInfo(`${e} does not exist, safe to copy.`),this.ensureFolderExists(_path2.default.dirname(e)),this.copySingleFile(i,e,void 0,!0))}syncDeleteFile(e){_fs.default.existsSync(e)&&_fs.default.unlinkSync(e)}getFileContextInJSON(e){try{if(_fs.default.existsSync(e))return JSON.parse(_fs.default.readFileSync(e,"utf-8"))}catch(e){throw new _index2.default(9999,e.message)}return{}}getFileContextInRaw(e){return _fs.default.existsSync(e)?_fs.default.readFileSync(e,"utf-8"):""}writeFileInJSON(e,t){let i=JSON.stringify(t,null,2);_fs.default.writeFileSync(e,i)}async generatePackage(e="./",t=!1,i=!0,...s){let n=this.findFilePathByExtension(e,["json"],"node_modules","release");n=_lodash.default.filter(n,e=>_lodash.default.isEqual(e.fileName,"package")),n=n.map(e=>this.getFolderPathOfSpecificPath(e.absolute));for(const e of n)if(this.isAndEquals(...s.map(t=>()=>!this.has(e,t)))){const s=await this.generateTempFolderWithCleanSrc(e);await this.deleteSelfByPath(_path2.default.join(e,"release"),!0);const n=this.persistByPath(_path2.default.join(e,"release"));await this.executeCommandLine(`cd ${e} && babel ./temp --out-dir ./release/lib --config-file ./babel.config.js`);const a=require(_path2.default.join(e,"./terser.config.js")),r=this.getStringOfTerserCommandLine(a);await this.executeCommandLine(`cd ${e}/release/lib && find . -type f -name "*.js" -exec terser {} -o {} ${r} \\;`);const o=_path2.default.join(e,"package.json");try{const s="sample.npm.module.index.js";this.copySingleFile(`/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/${s}`,n,"index.js",!0);const a=`${e}/release/index.js`;await this.executeCommandLine(`terser ${a} -o ${a} ${r}`);const l=_path2.default.join(e,"template");if(this.isPathExist(l)&&await this.copyFromFolderToDestFolder(l,this.persistByPath(_path2.default.join(n,"template"))),t){const{moduleName:e,version:t}=await this.upgradePackageJsonVersion(o);await this.updateVersionOfTemplate(e,t)}this.copySingleFile(o,_path2.default.join(n,"package.json"),void 0,!0),i||!this.isPathExist(_path2.default.join(n,"node_module"))?await this.executeCommandLine(`cd ${n} && yarn install --production`):this.appendInfo("ignore node-module install behavior"),this.appendInfo(`build ${e} succeed`),t&&await this.executeCommandLine(`cd ${n} && npm publish`)}catch(e){throw await this.deleteSelfByPath(n,!0),new _index2.default(9999,`generatePackage 報錯, ${e.message}`)}finally{await this.deleteSelfByPath(s,!0)}}}async updateVersionOfTemplate(e,t){const i=["/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/admin.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/web.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/functions.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/sample.package.json","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/package.json"];for(const s of i)if(this.isPathExist(s)){console.log("🦴正在修改以下 path的版本 => ",s);let i=!1;const n=this.getJsonObjByFilePath(s);if(n&&n.dependencies&&n.dependencies[e]){n.dependencies[e]=`^${t}`;try{await this.writeJsonThanPrettier(s,n),i=!0}catch(e){i=!1}}i||await this.updateFileOfSpecificLine(s,i=>` "${e}":"^${t}"${_lodash.default.endsWith(_lodash.default.trim(i),",")?",":""}`,t=>_lodash.default.startsWith(_lodash.default.trim(t),`"${e}"`)),console.log("💯成功修改以下 path的版本 => ",s)}console.log("離開updateVersionOfTemplate()的迴圈"),await this.copyFromFolderToDestFolder("/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/","/Users/davidtu/cross-achieve/high/idea-inventer/newp/template/",!0,!0)}async updateFileOfSpecificLine(e,t=e=>"updated",i=e=>!0){const s=this.getFileContextInRaw(e).split("\n"),n=s.findIndex(i);-1!==n&&(s[n]=t(s[n]),this.appendFile(e,s.join("\n"),!0,!0),await this.prettier(e))}async writeJsonThanPrettier(e,t){this.writeFileInJSON(e,t),await this.prettier(e)}async enrichEachPackageJson(e){const t=new Set(["package","admin.package","web.package","functions.package"]),i=this.findFilePathByExtension(e,["json"],"gen","node_modules","release").filter(e=>t.has(e.fileName));if(0!==i.length)for(const{absolute:e}of i){const t=this.getJsonObjByFilePath(e);t.scripts||={},t.scripts.updateConfigerer="npm update configerer --save",await this.writeJsonThanPrettier(e,t)}}insertShellCommand(e=_configerer.configerer.BASE_SHELL_SCRIPT,t,i){if(this.isStringContainInLines(this.getFileContextInRaw(e),t))throw new _index2.default(8007,`alias ${t} is exist`);{const s=`alias ${t}='${i}'`;this.appendFile(e,s)}}getAdminCredential(){return this.getJsonObjByFilePath("/Users/davidtu/cross-achieve/mimi/idea-inventer/firebaser/key/mimi19up-firebase-adminsdk.json")}isEmptyFile(e){return!this.isPathExist(e)||_lodash.default.isEmpty(this.getFileContextInRaw(e).trim())}isEmptyFolder(e){return 0===_fs.default.readdirSync(e).length}async prettier(e,t=250,i=[".mustache"]){const s=_path2.default.resolve(e),n=_path2.default.resolve("."),a=i.find(t=>e.endsWith(t));let r=s,o=!!a;try{if(o){const e=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t=new RegExp(`${e}$`);r=s.replace(t,""),await _fs.default.rename(s,r)}await this.executeCommandLine(`cd "${n}" && npx prettier --write "${r}" --print-width ${t} --ignore-unknown`)}catch(t){console.error(`Prettier 執行錯誤 [${e}]:`,t.message)}finally{if(o&&r!==s)try{await _fs.default.access(r),await _fs.default.rename(r,s)}catch(e){}}}getFileLastModifiedTime(e){return _fs.default.statSync(e).mtimeMs}getJsonObjByFilePath(e){return this.appendInfo(`ready to json path:${e}`),JSON.parse(this.getFileContextInRaw(e))}async upgradePackageJsonVersion(e){if(_lodash.default.isEqual("json",this.getPathInfo(e).extension)){const t=this.getJsonObjByFilePath(e);return t.version=this.getStringOfVersionIncrement(t.version),await this.writeJsonThanPrettier(e,t),{version:t.version,moduleName:t.name}}throw new _index2.default(8020,`path is not package.json, which is ${e}`)}async reWriteJsonAttribute(e,...t){const{extension:i}=this.getPathInfo(e);if("json"!==i)throw new _index2.default(9999,`reWriteJsonAttribute() => path is not package.json, which is ${e}`);const s=t.find(e=>"object"!=typeof e||null===e);if(s)throw new _index2.default(9999,`84451515 attr is not object, which is 'type=${typeof s} => ${s}'`);const n=this.getJsonObjByFilePath(e);for(const e of t)n[this.getObjectKey(e)]=this.getObjectValue(e);return await this.writeJsonThanPrettier(e,n),{version:n.version,moduleName:n.name}}getVersionOfPackageJson(e){return this.getAttributeValueOfJson(e,"version","1.0.0")}getAttributeValueOfJson(e,t,i=void 0){if(_lodash.default.isEqual("json",this.getPathInfo(e).extension))return this.getJsonObjByFilePath(e)[t]??i;throw new _index2.default(8020,`path is not package.json, which is ${e}`)}getVersionOfJsFile(e){return this.getAttributeValueOfJsFile(e,"version","project without version notice")}getAttributeValueOfJsFile(e,t,i=void 0){if(_lodash.default.isEqual(this.getExtensionFromPath(e),"js"))return require(_path2.default.resolve(e)).default[t]??i;throw new _index2.default(8020,`path is not js file, which is ${e}`)}async rewriteAttributeOfSourceJs(e,...t){if(!this.isPathExist(e))throw new _index2.default(9999,`4849813 ${e} is not exist`);for(const i of t){if(!_lodash.default.isObject(i))throw new _index2.default(9999,`4984651 attr is not object, which is 'type=${typeof i} => ${i}'`);const t=this.getObjectKey(i),s=this.getObjectValue(i),n=this.getFileContextInRaw(e).split("\n");n[_lodash.default.findIndex(n,e=>_lodash.default.startsWith(_lodash.default.trim(e),`${t}`))]=` ${t}: '${s}',`,this.appendFile(e,n.join("\n"),!0,!0)}return t}async generateTempFolderWithCleanSrc(e){this.appendInfo("generateTempFolderWithCleanSrc",e);const t=_path2.default.join(e,"src"),i=_path2.default.join(e,"temp");if(!_fs.default.existsSync(t))return i;this.appendInfo("generateTempFolderWithCleanSrc","source",t),this.persistByPath(i),await this.copyFromFolderToDestFolder(t,i);const s=this.findFilePathBy(i);for(const{absolute:e}of s){const t=this.getFileContextInRaw(e).split("\n"),i=t.map(e=>e.trim()),s=i.findIndex(e=>e.startsWith("if (configerer.DEBUG_MODE)")),n=i.lastIndexOf("}");if(s>=0&&n>s){t.splice(s,n-s+1);const i=t.join("\n");this.appendFile(e,i,!0,!0),await this.executeCommandLine(`cd ${_path2.default.dirname(e)} && npx prettier --write "${e}"`)}}return i}rewriteFile2File(e,t){const i=this.getFileContextInRaw(e);if(!i.trim())throw new _index2.default(9999,`${e} 為空,避免覆蓋`);this.appendFile(t,i,!0,!0),this.appendInfo(`rewrite from:${e} => to:${t} 成功`)}getStringOfHeadOfFile(e){if(this.isPathExist(e)){const t=this.getFileContextInRaw(e);return _lodash.default.head(t.split("\n"))}return""}isFileEditSucceed(e){if(!this.isPathExist(e))return!1;const t=this.getPathInfo(e),i=this.getFileContextInRaw(e).trim();if(""===i)return this.appendInfo(`74985465 path ${t.path} is empty file, file would not persist`),!1;try{const e=i.split("\n")[0].match(/const\s+([a-zA-Z_]\w*)\s*=\s*(true|false)\s*;?/);if(!e||_lodash.default.size(e)<3)return!1;if(!0==("true"===e[2]))return!0}catch(e){return this.appendError(`66445411 ${e.message}`),!1}return!1}joinRespectingDot(...e){const t=e[0]?.startsWith("./"),i=e[0]?.startsWith("./")?[e[0].slice(2),...e.slice(1)]:e,s=_path2.default.join(...i);return t&&!_path2.default.isAbsolute(s)?`./${s}`:s}}var _default=exports.default=NodeUtiller;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "utiller",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.471",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -23,10 +23,8 @@
|
|
|
23
23
|
"fs-extra": "^9.1.0",
|
|
24
24
|
"lodash": "^4.17.20",
|
|
25
25
|
"node-html-parser": "^7.0.1",
|
|
26
|
-
"
|
|
27
|
-
"
|
|
28
|
-
"puppeteer": "^24.31.0",
|
|
29
|
-
"uuid": "^8.3.2"
|
|
26
|
+
"uuid": "^8.3.2",
|
|
27
|
+
"inquirer": "^13.1.0"
|
|
30
28
|
},
|
|
31
29
|
"devDependencies": {
|
|
32
30
|
"@babel/core": "^7.28.5",
|