utiller 1.0.470 → 1.0.472

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 +1 @@
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")),_lodash=_interopRequireDefault(require("lodash")),_index2=require("../index.js"),_configerer=require("configerer"),_exceptioner=_interopRequireDefault(require("../exceptioner"));function _classPrivateFieldInitSpec(e,t,s){_checkPrivateRedeclaration(e,t),t.set(e,s)}function _checkPrivateRedeclaration(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function _classPrivateFieldGet(e,t){return e.get(_assertClassBrand(e,t))}function _assertClassBrand(e,t,s){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:s;throw new TypeError("Private element is not present on this object")}const SPECIFICITY_DEBUG=!1;var _run=new WeakMap;class InfinitePool{constructor(e=_configerer.configerer.POOLLER_WORKER_DEFAULT,t=_index2.utiller.getRandomValue(0,1e11)){(0,_defineProperty2.default)(this,"isRunInBackgroundMode",!1),(0,_defineProperty2.default)(this,"state",_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK),(0,_defineProperty2.default)(this,"enableOfTaskSleepByInterval",_configerer.configerer.POOLLER_ENABLE_TASK_SLEEP_BY_INTERVAL),(0,_defineProperty2.default)(this,"taskSleepInterval",_configerer.configerer.POOLLER_TASK_OF_INTERVAL_DEFAULT),(0,_defineProperty2.default)(this,"enableOfTaskTimeout",_configerer.configerer.POOLLER_ENABLE_TIMEOUT),(0,_defineProperty2.default)(this,"timeOfTaskTimeout",_configerer.configerer.POOLLER_TASK_TIMEOUT_DEFAULT),(0,_defineProperty2.default)(this,"handlerOfAssignTaskFail",void 0),(0,_defineProperty2.default)(this,"maximumOfWorker",void 0),(0,_defineProperty2.default)(this,"disableFirstRun",!1),(0,_defineProperty2.default)(this,"queueOfWaitingParam",[]),(0,_defineProperty2.default)(this,"countsOfRunByTimes",-1),(0,_defineProperty2.default)(this,"queueOfAssignTask",{}),(0,_defineProperty2.default)(this,"queueOfExecutingTask",[]),(0,_defineProperty2.default)(this,"isQueuePolling",!1),(0,_defineProperty2.default)(this,"initialTaskCompleted",!1),(0,_defineProperty2.default)(this,"mapOfHashNTask",{}),(0,_defineProperty2.default)(this,"mapOfHashNCallbackWrapper",{}),(0,_defineProperty2.default)(this,"nameOfCurrentPool",""),(0,_defineProperty2.default)(this,"atomicBgInstance",void 0),(0,_defineProperty2.default)(this,"setPoolId",(e=this.nameOfCurrentPool)=>{this.nameOfCurrentPool=e}),(0,_defineProperty2.default)(this,"getPoolId",()=>this.nameOfCurrentPool),(0,_defineProperty2.default)(this,"clearCache",()=>{this.isQueuePolling=!1,this.queueOfExecutingTask.length=0,this.mapOfHashNTask={},this.mapOfHashNCallbackWrapper={},this.initialTaskCompleted=!1;for(const e of _configerer.configerer.POOLLER_PRIORITY)this.queueOfAssignTask[e].length=0}),(0,_defineProperty2.default)(this,"stopInBackground",async()=>{this.terminate();let e=0;for(;_lodash.default.size(this.queueOfExecutingTask)>0&&e<30;)await _index2.utiller.syncDelay(500),this.printLogMessage(`784512, 卡在 stopInBackground 出不來,${this.getLogMessageOfExecutingTaskQueueCount()}`),this.showState(),e++;return!(_lodash.default.size(this.queueOfExecutingTask)>0&&(this.printLogMessage(`stopInBackground 超時,仍有 ${_lodash.default.size(this.queueOfExecutingTask)} 個任務在執行`,!0),1))}),(0,_defineProperty2.default)(this,"isRunning",()=>this.isQueuePolling),(0,_defineProperty2.default)(this,"getCountOfAssignTaskInQueue",()=>{let e=0;for(const t of _configerer.configerer.POOLLER_PRIORITY)e+=this.queueOfAssignTask[t].length;return e}),(0,_defineProperty2.default)(this,"add",(e,t="low")=>{if("function"==typeof e){if(_configerer.configerer.POOLLER_PRIORITY.indexOf(t)<0)throw new _exceptioner.default(4001,`priority can't be ${t}`);const s=_index2.utiller.getRandomHash(),i={task:e,hash:s};return this.appendHashTaskMap(i),this.queueOfAssignTask[t].push(i),s}throw new _exceptioner.default(4002,"task can't be "+typeof e)}),(0,_defineProperty2.default)(this,"updateExecuteTaskState",e=>{const t=_lodash.default.find(this.queueOfExecutingTask,t=>_lodash.default.isEqual(t.hash,e));t&&(this.printLogMessage(`847875153, 客端委託的任務: ${e},更改狀態為 'ING'`),t.state="ING")}),(0,_defineProperty2.default)(this,"taskWrapper",(e,t,s)=>()=>{const i=this;let a,n,r="",o=!0;return new Promise((u,f)=>{i.enableOfTaskTimeout&&(r=setTimeout(()=>{try{throw this.printLogMessage(`982532, taskWrapper執行中,發生timeout: ${i.timeOfTaskTimeout} ms`),new _exceptioner.default(4010,i.getPoollerLogFormat(`TASK HASH:${t} IS TIMEOUT ${i.timeOfTaskTimeout} ms ${s?`,PARAMS IS ${JSON.stringify(s)}`:""}`))}catch(e){f(e)}},i.timeOfTaskTimeout)),this.printLogMessage(`984135, 客端委託的task開始執行 ${t}`),i.updateExecuteTaskState(t),e(s).then(e=>{this.printLogMessage(`984545, 客端委託的任務(TASK HASH:${t}),resolve回應: ${e}`),a=e,o=!0}).catch(e=>{this.printLogMessage(`989652, 客端委託的任務,reject回應: ${e.message}`,!0,e),n=e,o=!1}).finally(()=>{clearTimeout(r),u(),this.printLogMessage(`98942,(TASK HASH:${t}) taskWrapper()裡面第一個promise(為了timeout設計)完成了`)})}).then(()=>{if(o)return this.printLogMessage(`9894841,(TASK HASH:${t}) taskWrapper()裡面第二個promise(整個任務)完成了`),`${this.getLogMessageOfTaskHash(t)} completed`;throw n}).catch(e=>{if(o=!1,n=e,!i.isWait4ResultTask(t))if(void 0!==i.handlerOfAssignTaskFail)try{i.handlerOfAssignTaskFail(n)}catch(e){this.printLogMessage(`錯誤處理器執行失敗: ${e.message}`,!0,e)}else this.printLogMessage(`任務執行失敗但未設置錯誤處理器: ${n.message}`,!0,n)}).finally(()=>{const e={assignedTaskCompleted:o,resolve:a,reject:n};i.removeResolveOrRejectPromiseByHash(t,e),this.printLogMessage(`98943213, ${this.getLogMessageOfTaskHash(t)} taskWrapper()裡面第2個promise完成了`,!1,e)})}),(0,_defineProperty2.default)(this,"adds",(e,t="low")=>{const s=[];if(!_lodash.default.isArray(e))throw new _exceptioner.default(4003,"should be async function array, not "+typeof e);for(const i of e)s.push(this.add(i,t));return s}),(0,_defineProperty2.default)(this,"removeTaskMapByHash",e=>{delete this.mapOfHashNTask[e]}),(0,_defineProperty2.default)(this,"beforeRun",()=>{this.isQueuePolling=!0}),(0,_defineProperty2.default)(this,"afterRun",()=>{this.clearCache()}),(0,_defineProperty2.default)(this,"runInInfinite",async(e=[],t)=>{if(this.beforeRun(),_lodash.default.isFunction(e))this.add(e);else{if(!_lodash.default.isArray(e))throw new _exceptioner.default(4006,"type of task is ===> "+typeof e);this.adds(e)}for(this.enableTaskSleepInterval(_lodash.default.isNumber(t),t),this.setState(_configerer.configerer.POOLLER_STATE.RUN_INFINITE);!this.ruleOfStopInfiniteRun();)this.printLogMessage(`415123, runInInfinite() 正在無限Loop中, ${this.getLogMessageOfExecutingTaskQueueCount()}`),await _classPrivateFieldGet(_run,this).call(this);this.isRunInBackgroundMode||this.afterRun()}),(0,_defineProperty2.default)(this,"ruleOfStopInfiniteRun",()=>!this.isRunning()&&this.isExecutingTaskQueueEmpty()),(0,_defineProperty2.default)(this,"isExecutingTaskQueueEmpty",()=>0===_lodash.default.size(this.queueOfExecutingTask)),(0,_defineProperty2.default)(this,"appendParamInToQueue",(...e)=>{this.triggerBgInstance(),this.queueOfWaitingParam.push(...e)}),(0,_defineProperty2.default)(this,"runByParams",async(e,...t)=>{if(void 0===e&&(e=this.queueOfAssignTask.low.shift().task),!_lodash.default.isFunction(e))throw new _exceptioner.default(4006,"runByParams error, typeof task can't be "+typeof e);if(!_lodash.default.isArray(t))throw new _exceptioner.default(4006,"runByParams error, typeof params can't be "+typeof t);for(this.beforeRun(),this.add(e),this.appendParamInToQueue(...t),this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS);_lodash.default.size(this.queueOfWaitingParam)>0;)await _classPrivateFieldGet(_run,this).call(this);for(;!this.isExecutingTaskQueueEmpty();)await _index2.utiller.syncDelay(33),this.printLogMessage(`等待執行中的任務完成,剩餘: ${_lodash.default.size(this.queueOfExecutingTask)}`);this.printLogMessage("951281952, runByParams() 結束了while()"),this.terminate(),this.isRunInBackgroundMode||this.afterRun()}),(0,_defineProperty2.default)(this,"runByEachTask",async(e=[])=>{for(this.id=_index2.utiller.getRandomHash(15),this.beforeRun(),this.adds(e),this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK);!this.ruleOfStopInfiniteRun();)await _classPrivateFieldGet(_run,this).call(this,this.id),this.getCountOfAssignTaskInQueue()<=0&&(this.terminate(),this.printLogMessage("788121, runByEachTask() 因為 taskOfWaitingQueue 清空而停止")),await _index2.utiller.syncDelay(10),this.printLogMessage("788143, runByEachTask() 為了讓while不要停止運算");this.printLogMessage("7881952, runByEachTask() 結束了while()"),this.isRunInBackgroundMode||this.afterRun()}),(0,_defineProperty2.default)(this,"runByTimes",async(e,t=1)=>{for(1!==this.maximumOfWorker&&this.printLogMessage(`警告: runByTimes 模式建議使用 1 個 worker,當前為 ${this.maximumOfWorker}`,!0),this.countsOfRunByTimes=t,this.add(e),this.beforeRun(),this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_TIMES);!this.ruleOfStopInfiniteRun()&&this.countsOfRunByTimes>0;)await _classPrivateFieldGet(_run,this).call(this);this.isRunInBackgroundMode||this.afterRun()}),(0,_defineProperty2.default)(this,"runInBackGround",(e,...t)=>{if(this.isRunInBackgroundMode=!0,"function"!=typeof e)throw new _exceptioner.default(4002,"_asyncfunc can't be "+typeof e);return setTimeout(async()=>{try{await e.apply(this,t)}catch(e){if(!(e instanceof _exceptioner.default))throw new _exceptioner.default(4009,{message:`${this.getPoollerLogFormat("")}`},e);this.printLogMessage(`7812123, runInBackGround() 執行錯誤: ${e.message}`,!0,e)}finally{this.terminate(),this.afterRun(),this.printLogMessage("7812123, runInBackGround() 走到finally")}},1)}),(0,_defineProperty2.default)(this,"getPoollerLogFormat",e=>`POOLLER NAME: ${this.getPoolId()}${_lodash.default.isEmpty(e)?"":" , "}${e}`),(0,_defineProperty2.default)(this,"setTaskFailHandler",(e=e=>console.log(e.message))=>{this.handlerOfAssignTaskFail=e}),(0,_defineProperty2.default)(this,"rulesOfAppendToExecutingTask",()=>{switch(this.state){case _configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK:return this.isRunning()&&!this.isExecutingQueueFull()&&this.getCountOfAssignTaskInQueue()>0;case _configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS:return this.isRunning()&&!this.isExecutingQueueFull()&&_lodash.default.size(this.queueOfWaitingParam)>0;case _configerer.configerer.POOLLER_STATE.RUN_BY_TIMES:case _configerer.configerer.POOLLER_STATE.RUN_INFINITE:return this.isRunning()&&!this.isExecutingQueueFull()&&this.getCountOfAssignTaskInQueue()>0;default:throw new _exceptioner.default(4005,`this.state ==> ${this.state}`)}}),(0,_defineProperty2.default)(this,"appendTaskToExecuteQueue",(e,t)=>{_lodash.default.isEqual(this.state,_configerer.configerer.POOLLER_STATE.RUN_BY_TIMES)&&(this.countsOfRunByTimes=this.countsOfRunByTimes-1);const s={state:"NOT",hash:e,task:t};this.printLogMessage(`4484451, 增加了一個assignedTask ${this.getLogMessageOfTaskHash(e)} 到 QueueOfExecutingTask ,${this.getLogMessageOfExecutingTaskQueueCount()}`,!1,s),this.queueOfExecutingTask.push(s)}),(0,_defineProperty2.default)(this,"getLogMessageOfExecutingTaskQueueCount",()=>`ExecutingTaskQueueCount: ${_lodash.default.size(this.queueOfExecutingTask)}`),(0,_defineProperty2.default)(this,"getLogMessageOfAssignTaskQueueCount",()=>`AssignTaskQueueCount: ${this.getCountOfAssignTaskInQueue()}`),(0,_defineProperty2.default)(this,"getLogMessageOfTaskHash",e=>`TASK HASH: ${e}`),(0,_defineProperty2.default)(this,"showState",()=>{_index2.utiller.appendInfo(this.getPoollerLogFormat(`workerCount: ${this.maximumOfWorker}`)),_index2.utiller.appendInfo(this.getPoollerLogFormat(`taskQueue(還在排隊的Task): ${this.getCountOfAssignTaskInQueue()}`)),_index2.utiller.appendInfo(this.getPoollerLogFormat(`QueueOfExecutingTask(正在執行的AsyncTask, 超過workerCount就是bug): ${_lodash.default.size(this.queueOfExecutingTask)}`)),_index2.utiller.appendInfo(this.getPoollerLogFormat(`mapOfHashNTask(還沒執行到的AsyncTask reference的暫存區): ${_lodash.default.size(this.mapOfHashNTask)}`))}),_classPrivateFieldInitSpec(this,_run,async()=>{const e=this;if(await this.syncTaskDispatcher(),0===this.maximumOfWorker)await async function(){e.printLogMessage("因為max count of worker為0,所以指派一個簡單的任務"),await _index2.utiller.syncDelay(10)}();else if(this.isExecutingTaskQueueEmpty())this.printLogMessage("4574152 不應該走到這裏,但是 minor issue",!0);else{this.printLogMessage(`4512211, 開始任務(taskWrapper): ${this.getLogMessageOfExecutingTaskQueueCount()}`);const t=await async function(){const t=_lodash.default.filter(e.queueOfExecutingTask,e=>_lodash.default.isEqual(e.state,"NOT")).map(e=>(0,e.task)());e.printLogMessage(`454652321, 開始任務(taskWrapper): run() 裡面的execute開始執行, task(state = NOT)的長度 ${_lodash.default.size(t)}`);const s=_lodash.default.size(t)>0?await Promise.race(t):"4542131684, task is empty";return e.printLogMessage("54121445161, 結束任務(taskWrapper): run() 裡面的execute結束執行"),s}();this.printLogMessage(`4512213 完畢任務(taskWrapper:${t}), ${this.getLogMessageOfExecutingTaskQueueCount()}, ${this.getLogMessageOfAssignTaskQueueCount()}`)}this.queueOfExecutingTask.length>this.maximumOfWorker&&this.printLogMessage(`4512214 一定是改壞了!!!!!!!!!!, ${this.getLogMessageOfExecutingTaskQueueCount} `,!0),e.printLogMessage("5478421212, 離開 run()")}),(0,_defineProperty2.default)(this,"getTaskInfoForRepetitiveRun",e=>{const t={task:e.task,hash:_index2.utiller.getRandomHash()};return this.appendHashTaskMap(t),t}),(0,_defineProperty2.default)(this,"getTaskInfoDependOnPriority",()=>{for(const e of _configerer.configerer.POOLLER_PRIORITY)if(this.queueOfAssignTask[e].length>0)switch(this.state){case _configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK:return this.queueOfAssignTask[e].shift();case _configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS:case _configerer.configerer.POOLLER_STATE.RUN_BY_TIMES:case _configerer.configerer.POOLLER_STATE.RUN_INFINITE:const t=this.queueOfAssignTask[e][0];return this.getTaskInfoForRepetitiveRun(t);default:throw new _exceptioner.default(4005,`this.state ==> ${this.state}`)}if(!_lodash.default.isEqual(this.state,_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK))throw new _exceptioner.default(4007)}),(0,_defineProperty2.default)(this,"removeResolveOrRejectPromiseByHash",(e,t)=>{const s=this.mapOfHashNCallbackWrapper[e];if(void 0!==s){this.printLogMessage(`5644153248, removeResolveOrRejectPromiseByHash 拿掉了完成的任務(${this.getLogMessageOfTaskHash(e)})`);try{s(t)}catch(e){this.printLogMessage(`回調執行失敗: ${e.message}`,!0,e)}finally{delete this.mapOfHashNCallbackWrapper[e]}}this.removePromiseFromExecutingQueue(e)}),(0,_defineProperty2.default)(this,"removePromiseFromExecutingQueue",e=>{this.printLogMessage(`56448412, QueueOfExecutingTask 拿掉了完成的任務 ${this.getLogMessageOfTaskHash(e)}`),_lodash.default.remove(this.queueOfExecutingTask,t=>_lodash.default.isEqual(e,t.hash))}),(0,_defineProperty2.default)(this,"runInfiniteInBackground",(e,t)=>this.invokeInstanceOfBackground(this.runInInfinite,e,t)),(0,_defineProperty2.default)(this,"runByParamInBackGround",(e,...t)=>this.invokeInstanceOfBackground(this.runByParams,e,...t)),(0,_defineProperty2.default)(this,"runByTimesInBackGround",(e,t)=>this.invokeInstanceOfBackground(this.runByTimes,e,t)),(0,_defineProperty2.default)(this,"runByEachTaskInBackGround",(...e)=>this.invokeInstanceOfBackground(this.runByEachTask,...e)),(0,_defineProperty2.default)(this,"invokeInstanceOfBackground",(e,...t)=>(void 0!==this.atomicBgInstance&&clearTimeout(this.atomicBgInstance),this.atomicBgInstance=this.runInBackGround(e,...t),this)),this.maximumOfWorker=e,this.setPoolId(_lodash.default.toString(t));for(const e of _configerer.configerer.POOLLER_PRIORITY)this.queueOfAssignTask[e]=[]}enableQueueTerminateBySleepCount(e=!0,t=_configerer.configerer.POOLLER_QUEUE_TIME_OF_SLEEP_INTERVAL_DEFAULT,s=_configerer.configerer.POOLLER_QUEUE_MAX_SLEEP_COUNTS_DEFAULT){this.enableOfQueueTerminateSleepCount=e,this.queueMaxSleepCounts=s,this.intervalOfQueueSleep=t}terminate(){this.isQueuePolling=!1}printLogMessage(e,t=!1,...s){}setWorker(e){this.maximumOfWorker=e}cleanTaskInterval(){this.taskSleepInterval={min:0,max:0}}enableTaskSleepInterval(e=!0,t=_configerer.configerer.POOLLER_TASK_OF_INTERVAL_DEFAULT){this.enableOfTaskSleepByInterval=e,_lodash.default.isNumber(t)&&(t={min:t,max:t}),this.taskSleepInterval=t}enableTaskTimeout(e=!0,t=_configerer.configerer.POOLLER_TASK_TIMEOUT_DEFAULT){this.enableOfTaskTimeout=e,this.timeOfTaskTimeout=t}async addTaskAndWait4Result(e,t="low",s="noName"){return this.triggerBgInstance(),new Promise((s,i)=>{const a=this.add(e,t);this.registerHash4Result(a,e=>{e.assignedTaskCompleted?s(e.resolve):i(e.reject)})})}registerHash4Result(e,t){this.mapOfHashNCallbackWrapper[e]=t}appendHashTaskMap(e){this.mapOfHashNTask[e.hash]=e}getTaskInfoByHash(e){return this.mapOfHashNTask[e]}remove(e){let t=this.getTaskInfoByHash(e);if(t){for(const s of _configerer.configerer.POOLLER_PRIORITY){const i=_lodash.default.indexOf(this.queueOfAssignTask[s],t);if(i>=0)return this.queueOfAssignTask[s].splice(i,1),this.removeTaskMapByHash(e),!0}return!1}throw new _exceptioner.default(4004,e)}setState(e){this.state=e}checkAndMarkInitialTaskStatus(){return this.initialTaskCompleted?this.initialTaskCompleted:(this.initialTaskCompleted=!0,!1)}setDisableFirstRun(e=!0){this.disableFirstRun=e}triggerBgInstance(){if(this.isRunInBackgroundMode&&!this.isQueuePolling)if(this.state!==_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK){if(this.state!==_configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS)throw new _exceptioner.default(4011,`this.state is ==> ${_index2.utiller.getItsKeyByValue(_configerer.configerer.POOLLER_STATE,this.state)}`);this.runByParamInBackGround()}else this.runByEachTaskInBackGround()}isExecutingQueueFull(){return _lodash.default.size(this.queueOfExecutingTask)>=this.maximumOfWorker}isTaskQueueEmpty(){return 0===this.getCountOfAssignTaskInQueue()}async syncTaskDispatcher(){this.printLogMessage("448984466, 走進來了 syncTaskDispatcher()");const e=this.disableFirstRun&&!this.checkAndMarkInitialTaskStatus(),t=this.queueOfExecutingTask.length>=this.maximumOfWorker-1,s=this.checkAndMarkInitialTaskStatus()&&t&&this.enableOfTaskSleepByInterval;if(e||s){const e=await _index2.utiller.syncDelayRandom(this.taskSleepInterval.min,this.taskSleepInterval.max);this.printLogMessage(`4484121, 走到睡覺區 enableOfTaskSleepByInterval:${this.enableOfTaskSleepByInterval} || ${e} ms`)}for(;this.rulesOfAppendToExecutingTask();){const e=this.getTaskInfoDependOnPriority();if(!e){this.printLogMessage("848451 也許有未知的issue,保險起見break",!0);break}{const t=this.taskWrapper(e.task,e.hash,this.queueOfWaitingParam.shift());this.state===_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK&&this.removeTaskMapByHash(e.hash),this.appendTaskToExecuteQueue(e.hash,t)}}this.printLogMessage("4489844821, 離開了 syncTaskDispatcher()")}isWait4ResultTask(e){return void 0!==this.mapOfHashNCallbackWrapper[e]}}var _default=exports.default=InfinitePool;
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")),_lodash=_interopRequireDefault(require("lodash")),_index2=require("../index.js"),_configerer=require("configerer"),_exceptioner=_interopRequireDefault(require("../exceptioner"));function _classPrivateFieldInitSpec(e,t,s){_checkPrivateRedeclaration(e,t),t.set(e,s)}function _checkPrivateRedeclaration(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function _classPrivateFieldGet(e,t){return e.get(_assertClassBrand(e,t))}function _assertClassBrand(e,t,s){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:s;throw new TypeError("Private element is not present on this object")}const SPECIFICITY_DEBUG=!0;var _run=new WeakMap;class InfinitePool{constructor(e=_configerer.configerer.POOLLER_WORKER_DEFAULT,t=_index2.utiller.getRandomValue(0,1e11)){(0,_defineProperty2.default)(this,"isRunInBackgroundMode",!1),(0,_defineProperty2.default)(this,"state",_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK),(0,_defineProperty2.default)(this,"enableOfTaskSleepByInterval",_configerer.configerer.POOLLER_ENABLE_TASK_SLEEP_BY_INTERVAL),(0,_defineProperty2.default)(this,"taskSleepInterval",_configerer.configerer.POOLLER_TASK_OF_INTERVAL_DEFAULT),(0,_defineProperty2.default)(this,"enableOfTaskTimeout",_configerer.configerer.POOLLER_ENABLE_TIMEOUT),(0,_defineProperty2.default)(this,"timeOfTaskTimeout",_configerer.configerer.POOLLER_TASK_TIMEOUT_DEFAULT),(0,_defineProperty2.default)(this,"handlerOfAssignTaskFail",void 0),(0,_defineProperty2.default)(this,"maximumOfWorker",void 0),(0,_defineProperty2.default)(this,"disableFirstRun",!1),(0,_defineProperty2.default)(this,"queueOfWaitingParam",[]),(0,_defineProperty2.default)(this,"countsOfRunByTimes",-1),(0,_defineProperty2.default)(this,"queueOfAssignTask",{}),(0,_defineProperty2.default)(this,"queueOfExecutingTask",[]),(0,_defineProperty2.default)(this,"isQueuePolling",!1),(0,_defineProperty2.default)(this,"initialTaskCompleted",!1),(0,_defineProperty2.default)(this,"mapOfHashNTask",{}),(0,_defineProperty2.default)(this,"mapOfHashNCallbackWrapper",{}),(0,_defineProperty2.default)(this,"nameOfCurrentPool",""),(0,_defineProperty2.default)(this,"atomicBgInstance",void 0),(0,_defineProperty2.default)(this,"setPoolId",(e=this.nameOfCurrentPool)=>{this.nameOfCurrentPool=e}),(0,_defineProperty2.default)(this,"getPoolId",()=>this.nameOfCurrentPool),(0,_defineProperty2.default)(this,"clearCache",()=>{this.isQueuePolling=!1,this.queueOfExecutingTask.length=0,this.mapOfHashNTask={},this.mapOfHashNCallbackWrapper={},this.initialTaskCompleted=!1;for(const e of _configerer.configerer.POOLLER_PRIORITY)this.queueOfAssignTask[e].length=0}),(0,_defineProperty2.default)(this,"stopInBackground",async()=>{this.terminate();let e=0;for(;_lodash.default.size(this.queueOfExecutingTask)>0&&e<30;)await _index2.utiller.syncDelay(500),this.printLogMessage(`784512, 卡在 stopInBackground 出不來,${this.getLogMessageOfExecutingTaskQueueCount()}`),this.showState(),e++;return!(_lodash.default.size(this.queueOfExecutingTask)>0&&(this.printLogMessage(`stopInBackground 超時,仍有 ${_lodash.default.size(this.queueOfExecutingTask)} 個任務在執行`,!0),1))}),(0,_defineProperty2.default)(this,"isRunning",()=>this.isQueuePolling),(0,_defineProperty2.default)(this,"getCountOfAssignTaskInQueue",()=>{let e=0;for(const t of _configerer.configerer.POOLLER_PRIORITY)e+=this.queueOfAssignTask[t].length;return e}),(0,_defineProperty2.default)(this,"add",(e,t="low")=>{if("function"==typeof e){if(_configerer.configerer.POOLLER_PRIORITY.indexOf(t)<0)throw new _exceptioner.default(4001,`priority can't be ${t}`);const s=_index2.utiller.getRandomHash(),i={task:e,hash:s};return this.appendHashTaskMap(i),this.queueOfAssignTask[t].push(i),s}throw new _exceptioner.default(4002,"task can't be "+typeof e)}),(0,_defineProperty2.default)(this,"updateExecuteTaskState",e=>{const t=_lodash.default.find(this.queueOfExecutingTask,t=>_lodash.default.isEqual(t.hash,e));t&&(this.printLogMessage(`847875153, 客端委託的任務: ${e},更改狀態為 'ING'`),t.state="ING")}),(0,_defineProperty2.default)(this,"taskWrapper",(e,t,s)=>()=>{const i=this;let a,n,r="",o=!0;return new Promise((u,f)=>{i.enableOfTaskTimeout&&(r=setTimeout(()=>{try{throw this.printLogMessage(`982532, taskWrapper執行中,發生timeout: ${i.timeOfTaskTimeout} ms`),new _exceptioner.default(4010,i.getPoollerLogFormat(`TASK HASH:${t} IS TIMEOUT ${i.timeOfTaskTimeout} ms ${s?`,PARAMS IS ${JSON.stringify(s)}`:""}`))}catch(e){f(e)}},i.timeOfTaskTimeout)),this.printLogMessage(`984135, 客端委託的task開始執行 ${t}`),i.updateExecuteTaskState(t),e(s).then(e=>{this.printLogMessage(`984545, 客端委託的任務(TASK HASH:${t}),resolve回應: ${e}`),a=e,o=!0}).catch(e=>{this.printLogMessage(`989652, 客端委託的任務,reject回應: ${e.message}`,!0,e),n=e,o=!1}).finally(()=>{clearTimeout(r),u(),this.printLogMessage(`98942,(TASK HASH:${t}) taskWrapper()裡面第一個promise(為了timeout設計)完成了`)})}).then(()=>{if(o)return this.printLogMessage(`9894841,(TASK HASH:${t}) taskWrapper()裡面第二個promise(整個任務)完成了`),`${this.getLogMessageOfTaskHash(t)} completed`;throw n}).catch(e=>{if(o=!1,n=e,!i.isWait4ResultTask(t))if(void 0!==i.handlerOfAssignTaskFail)try{i.handlerOfAssignTaskFail(n)}catch(e){this.printLogMessage(`錯誤處理器執行失敗: ${e.message}`,!0,e)}else this.printLogMessage(`任務執行失敗但未設置錯誤處理器: ${n.message}`,!0,n)}).finally(()=>{const e={assignedTaskCompleted:o,resolve:a,reject:n};i.removeResolveOrRejectPromiseByHash(t,e),this.printLogMessage(`98943213, ${this.getLogMessageOfTaskHash(t)} taskWrapper()裡面第2個promise完成了`,!1,e)})}),(0,_defineProperty2.default)(this,"adds",(e,t="low")=>{const s=[];if(!_lodash.default.isArray(e))throw new _exceptioner.default(4003,"should be async function array, not "+typeof e);for(const i of e)s.push(this.add(i,t));return s}),(0,_defineProperty2.default)(this,"removeTaskMapByHash",e=>{delete this.mapOfHashNTask[e]}),(0,_defineProperty2.default)(this,"beforeRun",()=>{this.isQueuePolling=!0}),(0,_defineProperty2.default)(this,"afterRun",()=>{this.clearCache()}),(0,_defineProperty2.default)(this,"runInInfinite",async(e=[],t)=>{if(this.beforeRun(),_lodash.default.isFunction(e))this.add(e);else{if(!_lodash.default.isArray(e))throw new _exceptioner.default(4006,"type of task is ===> "+typeof e);this.adds(e)}for(this.enableTaskSleepInterval(_lodash.default.isNumber(t),t),this.setState(_configerer.configerer.POOLLER_STATE.RUN_INFINITE);!this.ruleOfStopInfiniteRun();)this.printLogMessage(`415123, runInInfinite() 正在無限Loop中, ${this.getLogMessageOfExecutingTaskQueueCount()}`),await _classPrivateFieldGet(_run,this).call(this);this.isRunInBackgroundMode||this.afterRun()}),(0,_defineProperty2.default)(this,"ruleOfStopInfiniteRun",()=>!this.isRunning()&&this.isExecutingTaskQueueEmpty()),(0,_defineProperty2.default)(this,"isExecutingTaskQueueEmpty",()=>0===_lodash.default.size(this.queueOfExecutingTask)),(0,_defineProperty2.default)(this,"appendParamInToQueue",(...e)=>{this.triggerBgInstance(),this.queueOfWaitingParam.push(...e)}),(0,_defineProperty2.default)(this,"runByParams",async(e,...t)=>{if(void 0===e&&(e=this.queueOfAssignTask.low.shift().task),!_lodash.default.isFunction(e))throw new _exceptioner.default(4006,"runByParams error, typeof task can't be "+typeof e);if(!_lodash.default.isArray(t))throw new _exceptioner.default(4006,"runByParams error, typeof params can't be "+typeof t);for(this.beforeRun(),this.add(e),this.appendParamInToQueue(...t),this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS);_lodash.default.size(this.queueOfWaitingParam)>0;)await _classPrivateFieldGet(_run,this).call(this);for(;!this.isExecutingTaskQueueEmpty();)await _index2.utiller.syncDelay(33),this.printLogMessage(`等待執行中的任務完成,剩餘: ${_lodash.default.size(this.queueOfExecutingTask)}`);this.printLogMessage("951281952, runByParams() 結束了while()"),this.terminate(),this.isRunInBackgroundMode||this.afterRun()}),(0,_defineProperty2.default)(this,"runByEachTask",async(e=[])=>{for(this.id=_index2.utiller.getRandomHash(15),this.beforeRun(),this.adds(e),this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK);!this.ruleOfStopInfiniteRun();)await _classPrivateFieldGet(_run,this).call(this,this.id),this.getCountOfAssignTaskInQueue()<=0&&(this.terminate(),this.printLogMessage("788121, runByEachTask() 因為 taskOfWaitingQueue 清空而停止")),await _index2.utiller.syncDelay(10),this.printLogMessage("788143, runByEachTask() 為了讓while不要停止運算");this.printLogMessage("7881952, runByEachTask() 結束了while()"),this.isRunInBackgroundMode||this.afterRun()}),(0,_defineProperty2.default)(this,"runByTimes",async(e,t=1)=>{for(1!==this.maximumOfWorker&&this.printLogMessage(`警告: runByTimes 模式建議使用 1 個 worker,當前為 ${this.maximumOfWorker}`,!0),this.countsOfRunByTimes=t,this.add(e),this.beforeRun(),this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_TIMES);!this.ruleOfStopInfiniteRun()&&this.countsOfRunByTimes>0;)await _classPrivateFieldGet(_run,this).call(this);this.isRunInBackgroundMode||this.afterRun()}),(0,_defineProperty2.default)(this,"runInBackGround",(e,...t)=>{if(this.isRunInBackgroundMode=!0,"function"!=typeof e)throw new _exceptioner.default(4002,"_asyncfunc can't be "+typeof e);return setTimeout(async()=>{try{await e.apply(this,t)}catch(e){if(!(e instanceof _exceptioner.default))throw new _exceptioner.default(4009,{message:`${this.getPoollerLogFormat("")}`},e);this.printLogMessage(`7812123, runInBackGround() 執行錯誤: ${e.message}`,!0,e)}finally{this.terminate(),this.afterRun(),this.printLogMessage("7812123, runInBackGround() 走到finally")}},1)}),(0,_defineProperty2.default)(this,"getPoollerLogFormat",e=>`POOLLER NAME: ${this.getPoolId()}${_lodash.default.isEmpty(e)?"":" , "}${e}`),(0,_defineProperty2.default)(this,"setTaskFailHandler",(e=e=>console.log(e.message))=>{this.handlerOfAssignTaskFail=e}),(0,_defineProperty2.default)(this,"rulesOfAppendToExecutingTask",()=>{switch(this.state){case _configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK:return this.isRunning()&&!this.isExecutingQueueFull()&&this.getCountOfAssignTaskInQueue()>0;case _configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS:return this.isRunning()&&!this.isExecutingQueueFull()&&_lodash.default.size(this.queueOfWaitingParam)>0;case _configerer.configerer.POOLLER_STATE.RUN_BY_TIMES:case _configerer.configerer.POOLLER_STATE.RUN_INFINITE:return this.isRunning()&&!this.isExecutingQueueFull()&&this.getCountOfAssignTaskInQueue()>0;default:throw new _exceptioner.default(4005,`this.state ==> ${this.state}`)}}),(0,_defineProperty2.default)(this,"appendTaskToExecuteQueue",(e,t)=>{_lodash.default.isEqual(this.state,_configerer.configerer.POOLLER_STATE.RUN_BY_TIMES)&&(this.countsOfRunByTimes=this.countsOfRunByTimes-1);const s={state:"NOT",hash:e,task:t};this.printLogMessage(`4484451, 增加了一個assignedTask ${this.getLogMessageOfTaskHash(e)} 到 QueueOfExecutingTask ,${this.getLogMessageOfExecutingTaskQueueCount()}`,!1,s),this.queueOfExecutingTask.push(s)}),(0,_defineProperty2.default)(this,"getLogMessageOfExecutingTaskQueueCount",()=>`ExecutingTaskQueueCount: ${_lodash.default.size(this.queueOfExecutingTask)}`),(0,_defineProperty2.default)(this,"getLogMessageOfAssignTaskQueueCount",()=>`AssignTaskQueueCount: ${this.getCountOfAssignTaskInQueue()}`),(0,_defineProperty2.default)(this,"getLogMessageOfTaskHash",e=>`TASK HASH: ${e}`),(0,_defineProperty2.default)(this,"showState",()=>{_index2.utiller.appendInfo(this.getPoollerLogFormat(`workerCount: ${this.maximumOfWorker}`)),_index2.utiller.appendInfo(this.getPoollerLogFormat(`taskQueue(還在排隊的Task): ${this.getCountOfAssignTaskInQueue()}`)),_index2.utiller.appendInfo(this.getPoollerLogFormat(`QueueOfExecutingTask(正在執行的AsyncTask, 超過workerCount就是bug): ${_lodash.default.size(this.queueOfExecutingTask)}`)),_index2.utiller.appendInfo(this.getPoollerLogFormat(`mapOfHashNTask(還沒執行到的AsyncTask reference的暫存區): ${_lodash.default.size(this.mapOfHashNTask)}`))}),_classPrivateFieldInitSpec(this,_run,async()=>{const e=this;if(await this.syncTaskDispatcher(),0===this.maximumOfWorker)await async function(){e.printLogMessage("因為max count of worker為0,所以指派一個簡單的任務"),await _index2.utiller.syncDelay(10)}();else if(this.isExecutingTaskQueueEmpty())this.printLogMessage("4574152 不應該走到這裏,但是 minor issue",!0);else{this.printLogMessage(`4512211, 開始任務(taskWrapper): ${this.getLogMessageOfExecutingTaskQueueCount()}`);const t=await async function(){const t=_lodash.default.filter(e.queueOfExecutingTask,e=>_lodash.default.isEqual(e.state,"NOT")).map(e=>(0,e.task)());e.printLogMessage(`454652321, 開始任務(taskWrapper): run() 裡面的execute開始執行, task(state = NOT)的長度 ${_lodash.default.size(t)}`);const s=_lodash.default.size(t)>0?await Promise.race(t):"4542131684, task is empty";return e.printLogMessage("54121445161, 結束任務(taskWrapper): run() 裡面的execute結束執行"),s}();this.printLogMessage(`4512213 完畢任務(taskWrapper:${t}), ${this.getLogMessageOfExecutingTaskQueueCount()}, ${this.getLogMessageOfAssignTaskQueueCount()}`)}this.queueOfExecutingTask.length>this.maximumOfWorker&&this.printLogMessage(`4512214 一定是改壞了!!!!!!!!!!, ${this.getLogMessageOfExecutingTaskQueueCount} `,!0),e.printLogMessage("5478421212, 離開 run()")}),(0,_defineProperty2.default)(this,"getTaskInfoForRepetitiveRun",e=>{const t={task:e.task,hash:_index2.utiller.getRandomHash()};return this.appendHashTaskMap(t),t}),(0,_defineProperty2.default)(this,"getTaskInfoDependOnPriority",()=>{for(const e of _configerer.configerer.POOLLER_PRIORITY)if(this.queueOfAssignTask[e].length>0)switch(this.state){case _configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK:return this.queueOfAssignTask[e].shift();case _configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS:case _configerer.configerer.POOLLER_STATE.RUN_BY_TIMES:case _configerer.configerer.POOLLER_STATE.RUN_INFINITE:const t=this.queueOfAssignTask[e][0];return this.getTaskInfoForRepetitiveRun(t);default:throw new _exceptioner.default(4005,`this.state ==> ${this.state}`)}if(!_lodash.default.isEqual(this.state,_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK))throw new _exceptioner.default(4007)}),(0,_defineProperty2.default)(this,"removeResolveOrRejectPromiseByHash",(e,t)=>{const s=this.mapOfHashNCallbackWrapper[e];if(void 0!==s){this.printLogMessage(`5644153248, removeResolveOrRejectPromiseByHash 拿掉了完成的任務(${this.getLogMessageOfTaskHash(e)})`);try{s(t)}catch(e){this.printLogMessage(`回調執行失敗: ${e.message}`,!0,e)}finally{delete this.mapOfHashNCallbackWrapper[e]}}this.removePromiseFromExecutingQueue(e)}),(0,_defineProperty2.default)(this,"removePromiseFromExecutingQueue",e=>{this.printLogMessage(`56448412, QueueOfExecutingTask 拿掉了完成的任務 ${this.getLogMessageOfTaskHash(e)}`),_lodash.default.remove(this.queueOfExecutingTask,t=>_lodash.default.isEqual(e,t.hash))}),(0,_defineProperty2.default)(this,"runInfiniteInBackground",(e,t)=>this.invokeInstanceOfBackground(this.runInInfinite,e,t)),(0,_defineProperty2.default)(this,"runByParamInBackGround",(e,...t)=>this.invokeInstanceOfBackground(this.runByParams,e,...t)),(0,_defineProperty2.default)(this,"runByTimesInBackGround",(e,t)=>this.invokeInstanceOfBackground(this.runByTimes,e,t)),(0,_defineProperty2.default)(this,"runByEachTaskInBackGround",(...e)=>this.invokeInstanceOfBackground(this.runByEachTask,...e)),(0,_defineProperty2.default)(this,"invokeInstanceOfBackground",(e,...t)=>(void 0!==this.atomicBgInstance&&clearTimeout(this.atomicBgInstance),this.atomicBgInstance=this.runInBackGround(e,...t),this)),this.maximumOfWorker=e,this.setPoolId(_lodash.default.toString(t));for(const e of _configerer.configerer.POOLLER_PRIORITY)this.queueOfAssignTask[e]=[]}enableQueueTerminateBySleepCount(e=!0,t=_configerer.configerer.POOLLER_QUEUE_TIME_OF_SLEEP_INTERVAL_DEFAULT,s=_configerer.configerer.POOLLER_QUEUE_MAX_SLEEP_COUNTS_DEFAULT){this.enableOfQueueTerminateSleepCount=e,this.queueMaxSleepCounts=s,this.intervalOfQueueSleep=t}terminate(){this.isQueuePolling=!1}printLogMessage(e,t=!1,...s){_index2.utiller.printLogMessage(this.getPoollerLogFormat(e),t,...s)}setWorker(e){this.maximumOfWorker=e}cleanTaskInterval(){this.taskSleepInterval={min:0,max:0}}enableTaskSleepInterval(e=!0,t=_configerer.configerer.POOLLER_TASK_OF_INTERVAL_DEFAULT){this.enableOfTaskSleepByInterval=e,_lodash.default.isNumber(t)&&(t={min:t,max:t}),this.taskSleepInterval=t}enableTaskTimeout(e=!0,t=_configerer.configerer.POOLLER_TASK_TIMEOUT_DEFAULT){this.enableOfTaskTimeout=e,this.timeOfTaskTimeout=t}async addTaskAndWait4Result(e,t="low",s="noName"){return this.triggerBgInstance(),new Promise((s,i)=>{const a=this.add(e,t);this.registerHash4Result(a,e=>{e.assignedTaskCompleted?s(e.resolve):i(e.reject)})})}registerHash4Result(e,t){this.mapOfHashNCallbackWrapper[e]=t}appendHashTaskMap(e){this.mapOfHashNTask[e.hash]=e}getTaskInfoByHash(e){return this.mapOfHashNTask[e]}remove(e){let t=this.getTaskInfoByHash(e);if(t){for(const s of _configerer.configerer.POOLLER_PRIORITY){const i=_lodash.default.indexOf(this.queueOfAssignTask[s],t);if(i>=0)return this.queueOfAssignTask[s].splice(i,1),this.removeTaskMapByHash(e),!0}return!1}throw new _exceptioner.default(4004,e)}setState(e){this.state=e}checkAndMarkInitialTaskStatus(){return this.initialTaskCompleted?this.initialTaskCompleted:(this.initialTaskCompleted=!0,!1)}setDisableFirstRun(e=!0){this.disableFirstRun=e}triggerBgInstance(){if(this.isRunInBackgroundMode&&!this.isQueuePolling)if(this.state!==_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK){if(this.state!==_configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS)throw new _exceptioner.default(4011,`this.state is ==> ${_index2.utiller.getItsKeyByValue(_configerer.configerer.POOLLER_STATE,this.state)}`);this.runByParamInBackGround()}else this.runByEachTaskInBackGround()}isExecutingQueueFull(){return _lodash.default.size(this.queueOfExecutingTask)>=this.maximumOfWorker}isTaskQueueEmpty(){return 0===this.getCountOfAssignTaskInQueue()}async syncTaskDispatcher(){this.printLogMessage("448984466, 走進來了 syncTaskDispatcher()");const e=this.disableFirstRun&&!this.checkAndMarkInitialTaskStatus(),t=this.queueOfExecutingTask.length>=this.maximumOfWorker-1,s=this.checkAndMarkInitialTaskStatus()&&t&&this.enableOfTaskSleepByInterval;if(e||s){const e=await _index2.utiller.syncDelayRandom(this.taskSleepInterval.min,this.taskSleepInterval.max);this.printLogMessage(`4484121, 走到睡覺區 enableOfTaskSleepByInterval:${this.enableOfTaskSleepByInterval} || ${e} ms`)}for(;this.rulesOfAppendToExecutingTask();){const e=this.getTaskInfoDependOnPriority();if(!e){this.printLogMessage("848451 也許有未知的issue,保險起見break",!0);break}{const t=this.taskWrapper(e.task,e.hash,this.queueOfWaitingParam.shift());this.state===_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK&&this.removeTaskMapByHash(e.hash),this.appendTaskToExecuteQueue(e.hash,t)}}this.printLogMessage("4489844821, 離開了 syncTaskDispatcher()")}isWait4ResultTask(e){return void 0!==this.mapOfHashNCallbackWrapper[e]}}var _default=exports.default=InfinitePool;
@@ -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")),_pdfParse=_interopRequireDefault(require("pdf-parse")),_del=_interopRequireDefault(require("del")),_fsExtra=_interopRequireDefault(require("fs-extra")),_prompt=_interopRequireDefault(require("prompt"));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,a,n)=>{if(t.appendInfo(`${a}`),t.appendInfo(`${n}`),e)return t.appendError(`執行錯誤: ${e}`),void s(e);i(a.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&&
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(`錯誤: 偵測到重複的 ${e},請檢查資料來源。`),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.470",
3
+ "version": "1.0.472",
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
- "pdf-parse": "^1.1.1",
27
- "prompt": "^1.1.0",
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",
@@ -11,7 +11,7 @@
11
11
  "license": "ISC",
12
12
  "dependencies": {
13
13
  "configerer": "^1.0.25",
14
- "utiller": "^1.0.469",
14
+ "utiller": "^1.0.471",
15
15
  "linepayer": "^1.0.28",
16
16
  "databazer": "^1.0.21",
17
17
  "lodash": "^4.17.20",