utiller 1.0.486 → 1.0.488
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.
package/lib/pooller/index.js
CHANGED
|
@@ -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=!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,r,n="",o=!0;return new Promise((u,f)=>{n=i.enableOfTaskTimeout?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):setTimeout(()=>{try{throw this.printLogMessage("982533, taskWrapper執行中,發生極限保底超時: 3600000 ms",!0),new _exceptioner.default(4010,i.getPoollerLogFormat(`TASK HASH:${t} REACHED ABSOLUTE TIMEOUT 3600000 ms`))}catch(e){f(e)}},36e5),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),r=e,o=!1}).finally(()=>{clearTimeout(n),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 r}).catch(e=>{if(o=!1,r=e,!i.isWait4ResultTask(t))if(void 0!==i.handlerOfAssignTaskFail)try{i.handlerOfAssignTaskFail(r)}catch(e){this.printLogMessage(`錯誤處理器執行失敗: ${e.message}`,!0,e)}else this.printLogMessage(`任務執行失敗但未設置錯誤處理器: ${r.message}`,!0,r)}).finally(()=>{const e={assignedTaskCompleted:o,resolve:a,reject:r};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){const t=this.queueOfAssignTask.low.shift();t&&(e=t.task)}if(void 0!==e&&!_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(),e&&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)());let s;return e.printLogMessage(`454652321, 開始任務(taskWrapper): run() 裡面的execute開始執行, task(state = NOT)的長度 ${_lodash.default.size(t)}`),_lodash.default.size(t)>0?s=await Promise.race(t):e.queueOfExecutingTask.length>0?(await _index2.utiller.syncDelay(50),s="waiting for ING tasks"):s="4542131684, task is empty",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),this.mapOfHashNCallbackWrapper[e]&&(this.mapOfHashNCallbackWrapper[e]({assignedTaskCompleted:!1,reject:new _exceptioner.default(4012,`Task ${e} removed before execution`)}),delete this.mapOfHashNCallbackWrapper[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;
|
package/lib/utiller/index.js
CHANGED
|
@@ -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")),_cryptoJs=_interopRequireDefault(require("crypto-js")),_configerer=require("configerer"),_exceptioner=_interopRequireDefault(require("../exceptioner")),_uuid=require("uuid"),_nodeHtmlParser=require("node-html-parser"),_dayjs=_interopRequireDefault(require("dayjs"));require("dayjs/locale/zh-tw"),require("dayjs/locale/en");var _utc=_interopRequireDefault(require("dayjs/plugin/utc")),_timezone=_interopRequireDefault(require("dayjs/plugin/timezone")),_duration=_interopRequireDefault(require("dayjs/plugin/duration")),_customParseFormat=_interopRequireDefault(require("dayjs/plugin/customParseFormat")),_relativeTime=_interopRequireDefault(require("dayjs/plugin/relativeTime")),_isBetween=_interopRequireDefault(require("dayjs/plugin/isBetween"));_dayjs.default.extend(_utc.default),_dayjs.default.extend(_timezone.default),_dayjs.default.extend(_duration.default),_dayjs.default.extend(_customParseFormat.default),_dayjs.default.extend(_relativeTime.default),_dayjs.default.extend(_isBetween.default),_dayjs.default.locale("zh-tw"),String.format=function(){let e=[];for(let t=0,r=arguments.length;t<r;t++)e.push(arguments[t]);let t=e[0];return e.shift(),t.replace(/\{(\d+)\}/g,function(t,r){return e[r]})};class Utiller{removeAttributeBy(e,t=e=>_lodash.default.isUndefined(e)){for(const r in e)t(e[r])&&delete e[r]}getUrlPath(...e){return e.filter(e=>null!=e&&""!==e).map(e=>String(e)).map(e=>e.replace(/^\/+|\/+$/g,"")).filter(e=>""!==e).join("/").replace(/^(https?):\/(?!\/)/,"$1://")}getStringsOfFlatten(e=[]){return _lodash.default.chain(e).flatten().filter(e=>null!=e&&""!==e).value()}getNumberOfNormalize(e,t=0){if(_lodash.default.isNumber(e))return e;try{const r=_lodash.default.toNumber(e);return _lodash.default.isNumber(r)&&!isNaN(r)?r:t}catch(e){this.appendError(`448561684561 ${e.message}`)}return t}getStringOfNormalize(e,t="",r=!1){if(_lodash.default.isString(e))return r?_lodash.default.trim(e):e;try{const a=_lodash.default.toString(e);return this.isOrEquals(a,"","undefined")?t:r?_lodash.default.trim(a):a}catch(e){thisappendError(`448616845453 ${e.message}`)}return t}isValidVersionOfString(e){if(this.isUndefinedNullEmpty(e))return!1;const t=e.split(".");for(const e of t){const t=_lodash.default.toNumber(e);if(!_lodash.default.isNumber(t)||isNaN(t))return!1}return!0}getSeparatorOfUnique(){return"།།"}getStringOfVersionIncrement(e,t=1){const r=e.split(".").map(e=>_lodash.default.toNumber(e)),a=r.length-1;return r[a]=r[a]+t,r.join(".")}setLocaleOfDate(e="en"){_dayjs.default.locale(e.toLowerCase())}getUuidOfV4(){return(0,_uuid.v4)()}constructor(){(0,_defineProperty2.default)(this,"mapOfIdNTimeoutId",{}),(0,_defineProperty2.default)(this,"compactConsecutive",e=>_lodash.default.isArray(e)?_lodash.default.sortedUniq(e):[]),(0,_defineProperty2.default)(this,"getEnvironment",()=>this.env),(0,_defineProperty2.default)(this,"isProductionEnvironment",()=>_lodash.default.isEqual(this.getEnvironment(),"prod")),(0,_defineProperty2.default)(this,"asyncUnitTaskFunction",(e=2e3,t="預設的param",r)=>async(a=this.getRandomHash(10))=>{const n=this.getRandomValue(e,1.2*e);try{const e=n;if(this.appendInfo(`before executed ===> i'm symbol of ${e}, ready to be executed, inner param = ${t}`),await this.syncDelay(n),_lodash.default.isFunction(r)&&r(a))throw Error("force to made error happen");return this.appendInfo(`after executed ===> i'm symbol of ${e}, the task cost ${n} million-seconds ${a?`i hav params ===> ${a}`:""}`),{randomValue:n,symbol:e,param:a}}catch(e){this.appendError(new Error(`asyncUnitTask() catch error ${e.message}`))}finally{this.appendInfo("wow.... finally got you")}}),(0,_defineProperty2.default)(this,"findLowestValue",(e,t="price")=>{const r=_lodash.default.minBy(e,t)[t];return Math.floor(r)}),(0,_defineProperty2.default)(this,"findHighestValue",(e,t="price")=>{const r=_lodash.default.maxBy(e,t)[t];return Math.floor(r)}),(0,_defineProperty2.default)(this,"getStringOfValueRange",(e,t="price",r="$")=>{const a=_lodash.default.minBy(e,t)[t],n=_lodash.default.maxBy(e,t)[t];return n===a?`$${a}`:`${r}${a} - ${r}${n}`}),(0,_defineProperty2.default)(this,"getCallersName",()=>{let e;try{throw new Error}catch(t){let r,a=/(\w+)@|at (\w+) \(/g,n=t.stack;a.exec(n),r=a.exec(n),_lodash.default.isNull(r)||(e=r[1]||r[2])}return _lodash.default.startsWith("asyncGeneratorStep",e)&&(e=""),e}),(0,_defineProperty2.default)(this,"getRandomValue",(e,t)=>(e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e)),(0,_defineProperty2.default)(this,"insertToArray",(e,t,...r)=>{if(!Array.isArray(e))throw new Error("First argument must be an array.");const a=Math.max(0,Math.min(t+1,e.length));e.splice(a,0,...r)}),(0,_defineProperty2.default)(this,"getStringOfYearADConvertToMinguoYear",(e,t=!1)=>{const r=e-1911;return r>0?`${t?"民國":""}${r}${t?"年":""}`:`${t?"民國":""}前${Math.abs(r)}${t?"年":""}`}),(0,_defineProperty2.default)(this,"merO",(...e)=>_lodash.default.merge(...e)),(0,_defineProperty2.default)(this,"merO4",(...e)=>{if(0===e.length)return{};const t=e[0],r=e.slice(1),a=_lodash.default.cloneDeep(t);return _lodash.default.merge(a,...r)}),(0,_defineProperty2.default)(this,"convertDateToTimestamp",e=>(0,_dayjs.default)(e).valueOf()),(0,_defineProperty2.default)(this,"measureExecutionTime",async(e,...t)=>{const r=Date.now();await e(...t);const a=Date.now()-r,n=_dayjs.default.duration(a),s=Math.floor(n.asHours()),i=n.minutes(),o=n.seconds(),l=n.milliseconds(),d=(a/1e3).toFixed(3);return{second:d,zh_TW:`${s}小時 ${i}分 ${o}.${l.toString().padStart(3,"0")}秒 (合計 ${d} 秒)`}}),(0,_defineProperty2.default)(this,"formatPriceWithCurrency",(e,t)=>{if("number"!=typeof e||"string"!=typeof t)throw new TypeError("Invalid input: number must be a number and locale must be a string.");return new Intl.NumberFormat(t,{style:"currency",currency:new Intl.Locale(t).maximize().currency||"USD",minimumFractionDigits:0}).format(e)}),(0,_defineProperty2.default)(this,"formatPrice",(e,t)=>{if("number"!=typeof e)throw new TypeError("Invalid input: number must be a number.");return t?new Intl.NumberFormat(t,{style:"currency",currency:new Intl.Locale(t).maximize().currency||"USD",minimumFractionDigits:0}).format(e):e.toLocaleString("en-US")}),(0,_defineProperty2.default)(this,"generateUniversalKeywords",(e,t=50,r=4)=>{if(!e||"string"!=typeof e)return[];if(void 0===_lodash.default)return console.error("Lodash is not available. Please ensure it is imported."),[];let a=e.trim(),n=[];r=Math.max(2,r),a.length>t&&(console.warn(`警告:輸入字串長度為 ${a.length},已根據 maxLength: ${t} 截斷。`),a=a.substring(0,t)),(a.match(/[a-zA-Z]+/g)||[]).forEach(e=>{if(e.length>=2){n.push(e.toUpperCase()),n.push(e.toLowerCase());const t=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase();n.push(t)}});const s=(a.match(/\b[0-9]+[a-zA-Z]{1,4}\b|\b[0-9]{1,3}(w|ml|g|oz|k)\b|[\u4e00-\u9fa5a-zA-Z0-9]{1,4}(色|號)[\u4e00-\u9fa5a-zA-Z0-9]{0,2}/gi)||[]).filter(e=>e.length>=2).map(e=>e.toLowerCase());n.push(...s);let i=a.toLowerCase();i=i.replace(/[0-9]+([\u4e00-\u9fa5a-z]{1,4}|[\/\-\~\\])/g," ").replace(/\b[a-z]{1,4}\b/g," ").replace(/\b[0-9]{1,3}\b/g," "),i=i.replace(/[!@#$%^&*()_+={}\[\]:;"'<>,.?\/\\|`~]/g," ").replace(/系列|一組|單色|多款|套組|全套|專用|迷你|頂級|高品質|超閃|奢華|最新|款式|新款|超亮|的|與|和|閃|美甲/g," ").replace(/\s+/g,"").trim();for(let e=2;e<=r;e++)for(let t=0;t<=i.length-e;t++){const r=i.substring(t,t+e);n.push(r)}return _lodash.default.chain(n).filter(e=>e.length>=2).filter(e=>e.length>2||!/^[\u4e00-\u9fa5a-z0-9]$/.test(e)).uniq().sortBy().value()}),(0,_defineProperty2.default)(this,"mutateIndexOfArrayItem",(e,t,r=0)=>{if(!Array.isArray(e)||!_lodash.default.isObject(t))return e;const a=_lodash.default.findIndex(e,e=>_lodash.default.isEqual(e,t));if(-1===a)return e;e.splice(a,1);const n=_lodash.default.clamp(r,0,e.length);return e.splice(n,0,t),e}),(0,_defineProperty2.default)(this,"getArrayOfModifyObject2Index",(e,t,r=0)=>{if(!Array.isArray(e)||!_lodash.default.isObject(t))return e;const a=_lodash.default.cloneDeep(e),n=_lodash.default.findIndex(a,e=>_lodash.default.isEqual(e,t));if(-1===n)return e;a.splice(n,1);const s=_lodash.default.clamp(r,0,a.length);return a.splice(s,0,t),a}),(0,_defineProperty2.default)(this,"generateLabelValuePairsWithOrigin",(e=[{label:"aa",value:1203},{label:"cc",value:1204},{label:"gg",value:2}],t=["aa","bb"])=>{const r=new Set(e.map(e=>e.value));return _lodash.default.chain(t).uniq().map(t=>{const a=_lodash.default.find(e,{label:t});if(a)return{label:t,value:a.value};let n;do{n=_lodash.default.random(2,999999999)}while(r.has(n));return r.add(n),{label:t,value:n}}).value()}),(0,_defineProperty2.default)(this,"getItemsOfMarkMatching",(e=[],t=[],r="value",a="belong")=>{const n=new Set(t);return _lodash.default.map(e,e=>({...e,[a]:n.has(e[r])}))}),(0,_defineProperty2.default)(this,"generateVariants",(e,t="|",r="-")=>{const a=e.filter(e=>e.length>0);return 0===a.length?[]:1===a.length?a[0].map(e=>({label:e.label,value:e.value})):_lodash.default.reduce(a,(e,t)=>_lodash.default.flatMap(e,e=>t.map(t=>[...e,t])),[[]]).map(e=>({label:e.map(e=>e.label).join(t),value:e.map(e=>e.value).join(r)}))}),(0,_defineProperty2.default)(this,"renameKeysInArray",(e,...t)=>{const r=Object.fromEntries(t);return e.map(e=>_lodash.default.mapKeys(e,(e,t)=>r[t]||t))}),(0,_defineProperty2.default)(this,"getArrayOfMergeBySpecificId",(e,t,r="id")=>{if(!Array.isArray(t))return e;const a=_lodash.default.keyBy(t,e=>_lodash.default.get(e,r));return e.map(e=>{const t=_lodash.default.get(e,r),n=a[t];return n?_lodash.default.merge({},e,n):e})}),(0,_defineProperty2.default)(this,"toPercentageDecimal",e=>{if(_lodash.default.isNil(e))return 1;_lodash.default.isString(e)&&(e=e.replace(/%/g,"").trim());const t=_lodash.default.toNumber(e);return _lodash.default.isFinite(t)?_lodash.default.round(t/100,10):1}),(0,_defineProperty2.default)(this,"getNumberOfMultiplyCeil",(e,t,r=0)=>{const a=Math.pow(10,r);return Math.ceil(e*t*a)/a}),(0,_defineProperty2.default)(this,"generateGoogleCalendarLink",({title:e,startDate:t,startTime:r,endDate:a,endTime:n,location:s,details:i})=>{const o="YYYYMMDDTHHmmss",l=(0,_dayjs.default)(`${t} ${r}`,"YYYY/MM/DD HH:mm").format(o),d=(0,_dayjs.default)(`${a} ${n}`,"YYYY/MM/DD HH:mm").format(o),u=new URLSearchParams;return e&&u.append("text",e),l&&d&&u.append("dates",`${l}/${d}`),i&&u.append("details",i),s&&u.append("location",s),u.append("ctz","Asia/Taipei"),u.append("trp","true"),`https://calendar.google.com/calendar/r/eventedit?${u.toString()}`}),(0,_defineProperty2.default)(this,"generateTimeTreeLink",({title:e,startDate:t,startTime:r,endDate:a,endTime:n,location:s,memo:i})=>{const o=new URLSearchParams;return e&&o.append("title",e),t&&o.append("start_date",t.replace(/\//g,"-")),r&&o.append("start_time",r),a&&o.append("end_date",a.replace(/\//g,"-")),n&&o.append("end_time",n),s&&o.append("location",s),i&&o.append("memo",i),`https://timetreeapp.com/plans/new?${o.toString()}`}),(0,_defineProperty2.default)(this,"generateIcsContent",({title:e,startDate:t,startTime:r,endDate:a,endTime:n,location:s,details:i})=>{const o="Asia/Taipei",l="YYYYMMDDTHHmmss",d=_dayjs.default.tz(`${t} ${r}`,"YYYY/MM/DD HH:mm",o).format(l),u=_dayjs.default.tz(`${a} ${n}`,"YYYY/MM/DD HH:mm",o).format(l),f=(0,_dayjs.default)().utc().format(l)+"Z",c=e=>(e||"").replace(/\\/g,"\\\\").replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/\n/g,"\\n"),h=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//Gemini AI//NONSGML v1.0//EN","BEGIN:VEVENT","UID:"+(Date.now().toString(36)+Math.random().toString(36).substring(2,5)+"@gemini-app.com"),`DTSTAMP:${f}`];return d&&h.push(`DTSTART;TZID=${o}:${d}`),u&&h.push(`DTEND;TZID=${o}:${u}`),e&&h.push(`SUMMARY:${c(e)}`),s&&h.push(`LOCATION:${c(s)}`),i&&h.push(`DESCRIPTION:${c(i)}`),h.push("END:VEVENT","END:VCALENDAR"),h.join("\r\n")}),(0,_defineProperty2.default)(this,"generateAllCalendarLinks",e=>{const t=this.generateGoogleCalendarLink(e),r={...e,memo:e.details},a=this.generateTimeTreeLink(r),n=this.generateIcsContent(e);return{google:t,timeTree:a,ics:`data:text/calendar;charset=utf8,${encodeURIComponent(n)}`}}),(0,_defineProperty2.default)(this,"getArrayOfMappingRef",(e,t)=>_lodash.default.map(e,e=>{const r=_lodash.default.find(t,{value:e.value});return r?_lodash.default.merge({},e,r):e})),(0,_defineProperty2.default)(this,"areAllValuesTheSameOnKeys",(e,...t)=>{if(!e||e.length<=1||0===t.length)return!0;for(const r of t){const t=e[0]?.[r];if(!_lodash.default.every(e,e=>e[r]===t))return!1}return!0}),(0,_defineProperty2.default)(this,"getArrayOfUniqBy",(e,t)=>{if(!Array.isArray(e))return console.error("Input must be an array."),[];if("string"!=typeof t||0===t.length)return console.error("Key must be a non-empty string."),[...e];const r=e.reduce((e,r)=>{const a=r[t];return e.has(a)||e.set(a,r),e},new Map);return Array.from(r.values())}),(0,_defineProperty2.default)(this,"execute4Tasks",async(e=[],t)=>{if(!t||"function"!=typeof t)throw new Error("Task function is required and must be a function.");if("AsyncFunction"!==t.constructor.name)throw new Error("Task function must be an asynchronous function (async function) to ensure proper Promise handling.");return 0===e.length?Promise.resolve([]):await Promise.all(e.map(async(r,a)=>t(r,a,e)))}),(0,_defineProperty2.default)(this,"getReadableOfFileS",(e,t=2)=>{if(0===e)return"0 Bytes";const r=t<0?0:t,a=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,a)).toFixed(r))+" "+["Bytes","KB","MB","GB","TB"][a]}),(0,_defineProperty2.default)(this,"getNumOfFileS",e=>{if(null==e)throw new Error("輸入不能為空");const t=String(e).toUpperCase().trim().match(/^(\d+(\.\d+)?)\s*([A-Z]*)$/);if(!t)throw new Error(`[Invalid Format] 無法解析:'${e}'。請確保格式如 '5MB'`);const r=parseFloat(t[1]),a=t[3],n={"":1,B:1,K:1024,KB:1024,M:1048576,MB:1048576,G:1024**3,GB:1024**3,T:1024**4,TB:1024**4};if(!(a in n))throw new Error(`[Unknown Unit] 未知的容量單位:'${a}'`);return r*n[a]}),(0,_defineProperty2.default)(this,"isCallable",e=>{if("function"==typeof e)return!0;if(e&&"object"==typeof e){const t=Object.prototype.toString.call(e);return!!["[object Function]","[object AsyncFunction]","[object GeneratorFunction]"].includes(t)||"function"==typeof e.call&&"function"==typeof e.apply}return!1}),(0,_defineProperty2.default)(this,"isP",e=>{if(!e)return!1;const t=Object.prototype.toString.call(e);if("[object AsyncFunction]"===t||"function"==typeof e&&"AsyncFunction"===e.constructor?.name)throw new Error("[isPromise Error]: You passed an AsyncFunction instead of a Promise. Did you forget to execute it? (e.g., use 'isPromise(task())' instead of 'isPromise(task)')");return"[object Promise]"===t||e instanceof Promise||("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}),(0,_defineProperty2.default)(this,"exeAsyncT",(e,{thenDo:t,catchDo:r,finallyDo:a,ignore:n=!1}={})=>{if(!this.isP(e))throw console.error("Task validation failed:",e),new Error("[exeAsyncT]: task must be a Promise. Did you forget to call the async function?");return e.then(async e=>{this.isCallable(t)&&await t(e)}).catch(async e=>{if(this.isCallable(r))await r(e);else if(!n)throw console.error("[exeAsyncT Catch]:",e),e}).finally(async()=>{this.isCallable(a)&&await a()})}),this.init(),this.env="dev"}performActionWithoutTimingIssue(e=()=>!0,t=10){this.syncDelay(t).then(()=>e())}executeTimeoutTask(e,t=1e3,r=this.getRandomHash(),...a){const n=this,s=this.mapOfIdNTimeoutId[r];s&&clearTimeout(s);const i=setTimeout(async(...t)=>{await e(),delete n.mapOfIdNTimeoutId[r]},t,...a);n.mapOfIdNTimeoutId[r]=i}printLogMessage(e,t=!1,...r){this.isProductionEnvironment()||(t?this.appendError(e,...r):this.appendInfo(e,...r))}init(){}setEnvironment(e){this.env=e}appendInfo(...e){this.isProductionEnvironment()||console.log(...e)}appendError(...e){this.isProductionEnvironment()||console.error(...e)}async syncDelay(e=2e3){return new Promise(t=>{setTimeout(()=>{t(e)},e)})}startWithRegex(e="",t="."){return new RegExp(`^${t}`,"i").test(e)}accumulate(e,t){let r=e;for(const e of t)void 0!==e&&_lodash.default.isFunction(e)&&(r=e(r));return r}isOrEquals(e,...t){for(const r of t)if(_lodash.default.isEqual(e,r))return!0;return!1}isAndEquals(...e){for(const t of e)if(!t())return!1;return!0}getStringOfHeadMatch(e,t,r="g"){const a=e.match(new RegExp(t,r));return this.isUndefinedNullEmpty(a)?void 0:a[0]}or(...e){for(const t of e)if(_lodash.default.isBoolean(t)&&t)return!0;return!1}and(...e){for(const t of e)if(!t)return!1;return!0}nth(e,t=-1){return _lodash.default.nth(e,t%_lodash.default.size(e))}getExistOne(...e){for(const t of e)if(t)return t}getStringOfDropHeadSign(e,t){return _lodash.default.dropWhile(Array.from(e),e=>_lodash.default.isEqual(e,t)).join("")}isAndWith(e,t,...r){for(const a of r)if(!t(e,a))return!1;return!0}async syncDelayRandom(e=3e3,t=5e3){const r=this.getRandomValue(e,t);return await this.syncDelay(r),r}has(e,t,r=!1){return _lodash.default.isArray(e)?r?_lodash.default.findIndex(e,e=>_lodash.default.isEqual(t,e))>-1:_lodash.default.indexOf(e,t)>-1:_lodash.default.isObject(t)?e[t]:!!_lodash.default.isString(e)&&e.indexOf(t)>-1}containsBy(e,t){return _lodash.default.findIndex(e,e=>_lodash.default.isEqual(e,t))>=0}getStringOfInsideParentheses(e,t="."){return this.getStringOfRule(e,t,"(",")")}getStringOfInsideBrackets(e,t="."){return this.getStringOfRule(e,t,"[","]")}getStringOfInsideBraces(e,t="."){return this.getStringOfRule(e,t,"{","}")}getStringOfRule(e,t=".",r="{",a="}"){return this.getStringOfHeadMatch(e,`(?<=\\${r})${t}+?(?=\\${a})`)}getRandomHash(e=20){const t=_cryptoJs.default.lib.WordArray.random(e);return _cryptoJs.default.enc.Base64.stringify(t).substring(0,e)}getRandomHashV2(e){let t="";for(let r=0;r<e;r++){const e=Math.floor(62*Math.random());t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(e)}return t}getEncryptString(e,t=_configerer.configerer.ENCRYPT_KEY,r=!1){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const a=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue"),n=r?_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`):t;return _cryptoJs.default.AES.encrypt(e,n,{iv:a}).toString()}getEncryptStringV2(e,t=_configerer.configerer.ENCRYPT_KEY,r=!1){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const a=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue"),n=r?_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`):t;return _cryptoJs.default.AES.encrypt(JSON.stringify({content:e}),n,{iv:a}).toString()}getDecryptString(e,t=_configerer.configerer.ENCRYPT_KEY){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const r=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const a=_cryptoJs.default.AES.decrypt(e,t,{iv:r}).toString(_cryptoJs.default.enc.Utf8);if(!_lodash.default.isEmpty(a.trim()))return a}catch(e){}return _cryptoJs.default.AES.decrypt(e,_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`),{iv:r}).toString(_cryptoJs.default.enc.Utf8)}getDecryptStringV2(e,t=_configerer.configerer.ENCRYPT_KEY){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const r=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const a=_cryptoJs.default.AES.decrypt(e,t,{iv:r}).toString(_cryptoJs.default.enc.Utf8);if(!_lodash.default.isEmpty(a.trim()))return JSON.parse(a).content}catch(e){}const a=_cryptoJs.default.AES.decrypt(e,_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`),{iv:r}).toString(_cryptoJs.default.enc.Utf8);return JSON.parse(a).content}getFirebaseFormattedString(e){return _lodash.default.replace(e,/[\.\#\$\[\]]/g,"-").trim()}formalizeNamesToArray(e){let t=e;for(t=t.split(_configerer.configerer.SEPARATE_TONE_SINGER)[0].trim(),t=_lodash.default.replace(t,/[,\/#!$%\^&\*;:{}=_`、~()()]/g,"_").trim(),t=this.getFirebaseFormattedString(t),t=_lodash.default.replace(t,/\_\_+/g,"_").trim();_lodash.default.endsWith(t,"_");)t=t.slice(0,-1).trim();const r=t.split("_");return _lodash.default.map(r,e=>_lodash.default.trim(e))}getShuffledArrayWithLimitCountHighPerformance(e,t){let r=new Array(t),a=e.length,n=new Array(a);for(t>a&&(t=a);t--;){let s=Math.floor(Math.random()*a);r[t]=e[s in n?n[s]:s],n[s]=--a in n?n[a]:a}return r}getFileNameFromPath(e,t=!1){const r=e.split("/").pop();return t?r:r.split(".").shift()}getFileNameExtensionFromPath(e){return e.split("/").pop()}getPathOfReplaceLastDir(e,t){const r=e.split("/");return r.pop(),r.push(t),r.join("/")}getExtensionFromPath(e){const t=e.split("/").pop().split(".");return _lodash.default.size(t)>1?t.pop():""}getFolderPathOfSpecificPath(e){const t=e.split("/");return t.pop(),t.join("/")}getFolderNameOfFilePath(e){if(this.isValidFilePath(e)){const t=e.split("/");return _lodash.default.nth(t,-2)}throw new _exceptioner.default(9999,`64255615 path is not valid '${e}'`)}isUnderTargetPath(e,t){const r=e.split("/");return this.has(r,t)}getFileDirPath(e,t=!0){return _lodash.default.join(_lodash.default.initial(_lodash.default.split(e,"/")),"/")+(t?"/":"")}isPathEqualsFileType(e,t){const r=e.split(".").pop();return _lodash.default.isEqual(r,t)}isValidFilePath(e){const t=this.getExtensionFromPath(e);return _lodash.default.size(t)>0}getArrayOfSize(e,t=1){return _lodash.default.take(e,t)}getShuffledArrayWithLimitCount(e,t){return this.getShuffledArrayWithLimitCountHighPerformance(e,t)}getRandomItemOfArray(e,...t){if(!_lodash.default.isArray(e))throw new _exceptioner.default(9999,`why are you so stupid, typeof array should be array, not ==> ${e} `);const r=_lodash.default.without(e,...t),a=_lodash.default.size(r)>0?r:e,n=this.getShuffledArrayWithLimitCount(a,1);return n.length>0?n[0]:void 0}appendMapOfKeyArray(e,t,...r){this.isUndefinedNullEmpty(e[t])?e[t]=[...r]:e[t].push(...r)}getMergedArrayBy(e=[],t=[],r){if(!r||0===e.length||0===t.length)return[...e];const a=new Map(t.map(e=>[e[r],e]));return e.map(e=>({...a.get(e[r])||{},...e}))}getShuffledItemFromArray(e){return _lodash.default.shuffle(e)[0]}getShuffledArray(e){return _lodash.default.shuffle(e)}isJson(e){e="string"!=typeof e?JSON.stringify(e):e;try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e}getObjectValue(e){return _lodash.default.isObject(e)?Object.values(e)[0]:""}getObject(e,t){const r={};return r[e]=t,r}getStringOfCreditCardFormatted(e=0){return e.replace(/\D/g,"").replace(/(\d{4})(?=\d)/g,"$1-").slice(0,19)}getObjectKey(e){return _lodash.default.isObject(e)?Object.keys(e)[0]:""}printf(){this.appendInfo("i can use in web || react.js")}isKeywordRule(e){if(_lodash.default.isUndefined(e)||_lodash.default.isEmpty(e))throw new Error("PARAMS CAN NOT BE EMPTY");if(!_lodash.default.isString(e))throw new Error("PARAMS SHOULD BE STRING");if(e.length>20)throw new Error("EXCEED 20 WORDS IS NOT ALLOWED")}getItsKeyByValue(e,t){return Object.keys(e).find(r=>e[r]===t)}startWiths(e,t=[]){for(const r of t)if(_lodash.default.startsWith(e,r))return!0;return!1}replaceAll(e,t,r){return _lodash.default.replace(e,new RegExp(`${t}`,"g"),r)}replaceAllWithSets(e="",...t){let r=e;for(const e of t){if(this.isOrEquals(void 0,e.from,e.to))throw(0,_exceptioner.default)(9999,"from or to can't be empty");r=this.replaceAll(r,e.from,e.to)}return r}replaceArrayByContentIndex(e,t,r){e[_lodash.default.indexOf(e,t)]=r}deepFlat(e,t="_"){let r="";const a=[[e,""]];for(;a.length>0;){const[e,n]=a.pop();if(_lodash.default.isArray(e))for(let t=e.length-1;t>=0;t--)a.push([e[t],n]);else if(_lodash.default.isObject(e)){const r=Object.keys(e);for(let s=r.length-1;s>=0;s--){const i=r[s];a.push([e[i],n+i+t])}}else{const a=_lodash.default.trim(String(e));a.length>0?r+=(r.length>0?t:"")+n+a:n.length>0&&r.length>0?r+=t:n.length>0&&0===r.length&&(r+=n.endsWith(t)?n.slice(0,-t.length):n)}}return r.endsWith(t)&&(r=r.slice(0,-t.length)),r}joinEscapeChar(e){return(e+"").replace(/[\\"']/g,"\\$&").replace(/\u0000/g,"\\0")}getValueWithIntegerType(e){try{const t=parseInt(e);return isNaN(t)?0:t}catch(e){return 0}}getValueOfPriority(...e){for(const t of e)if(!this.isUndefinedNullEmpty(t))return t}async asyncPool(e,t,r){const a=[],n=[];for(const s of t){const i=Promise.resolve().then(()=>r(s,t));if(a.push(i),e<=t.length){const t=i.then(()=>n.splice(n.indexOf(t),1));n.push(t),n.length>=e&&await Promise.race(n)}}return Promise.all(a)}getAttrValueInSequence(e,...t){for(const r of t)if(!_lodash.default.isEmpty(e[r]))return e[r];return e}toDBC(e){for(var t="",r=0;r<e.length;r++)32===e.charCodeAt(r)&&(t+=String.fromCharCode(12288)),e.charCodeAt(r)<127&&(t+=String.fromCharCode(e.charCodeAt(r)+65248));return t}toCDB(e){for(var t="",r=0;r<e.length;r++)12288!==e.charCodeAt(r)?e.charCodeAt(r)>65280&&e.charCodeAt(r)<65375?t+=String.fromCharCode(e.charCodeAt(r)-65248):t+=String.fromCharCode(e.charCodeAt(r)):t+=String.fromCharCode(e.charCodeAt(r)-12256);return t}findIndexes(e,t){const r=[];let a=!0,n=0;for(;a;)n=_lodash.default.findIndex(e,t,n+1),n>-1?r.push(n):a=!1;return r}getSliceArrayOfSpecificIndexes(e,...t){const r=[],a=_lodash.default.size(e);for(const n of t){if(!_lodash.default.isNumber(n))throw new _exceptioner.default(9999,`59941278 index should be number => ${n}, ${e}`);if(n>a-1)throw new _exceptioner.default(9999,`5994123 index=>${n} is not valid, exceed than array size=${a}, ${e}`);r.push(_lodash.default.nth(e,n))}return r}indexesOf(e,t){const r=[];let a=-1;for(;-1!==(a=e.indexOf(t,a+1));)r.push(a);return r}getIndexOfContext(e,t){return _lodash.default.findIndex(e,e=>_lodash.default.isEqual(e.trim(),t))}toOneLineString(e){return _lodash.default.join(_lodash.default.split(e,"\n"),"")}toSpaceLessString(e){return _lodash.default.split(e,"").map(e=>_lodash.default.trim(e)).join("")}toNewLineLessString(e){return _lodash.default.split(e,"\n").map(e=>_lodash.default.trim(e)).join("")}exist(e){return!_lodash.default.isNull(e)&&!_lodash.default.isUndefined(e)}isUndefinedNullEmpty(e){const t=null==e,r=!!(_lodash.default.isString(e)||_lodash.default.isArray(e)||_lodash.default.isObject(e))&&_lodash.default.isEmpty(e);return t||r}isAndConditionOfUndefinedNullEmpty(...e){for(const t of e)if(!this.isUndefinedNullEmpty(t))return!1;return!0}isOrConditionOfUndefinedNullEmpty(...e){for(const t of e)if(this.isUndefinedNullEmpty(t))return!0;return!1}getStringHandledByEachLine(e,t=(e,t,r)=>!0,r="\n"){const a=e.split(r);for(const e of a)t(e,_lodash.default.indexOf(a,e),a);return a.join(r)}getSegmentsOfEachLine(e){return e.split("\n")}getNormalizedStringEndWith(e,t){e=this.toCDB(e),t=this.toCDB(t);const r=_lodash.default.join(_lodash.default.dropRightWhile(e,e=>!_lodash.default.isEqual(e,t)),"");return _lodash.default.isEmpty(r)?e:r}getNormalizedStringNotStartWith(e,...t){e=this.toCDB(e);const r=_lodash.default.join(_lodash.default.dropWhile(e,e=>this.has(t,e)),"");return _lodash.default.isEmpty(r)?e:r}getNormalizedStringNotEndWith(e,...t){e=this.toCDB(e);const r=_lodash.default.join(_lodash.default.dropRightWhile(e,e=>this.has(t,e)),"");return _lodash.default.isEmpty(r)?e:r}getTodayTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY-MM-DD")}getCustomFormatOfDatePresent(e,t="YY/MM"){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format(t)}getSimpleDateYYMMDDFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YY/MM/DD")}getSimpleTimeYYMMDDHHmmFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YY/MM/DD HH:mm")}getECPayCurrentTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatV2(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatYMDHM(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm")}getCurrentTimeFormatYMDHMS(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY-MM-DD-HH-mm-ss")}getCurrentMillionSecTimeFormat(e){return(0,_dayjs.default)(e||void 0).format("YYYY-MM-DD-HH-mm-ss-SSS")}isBetweenTimeStamp(e=this.getCurrentTimeStamp(),t,r){return(0,_dayjs.default)(e).isBetween(t,r)}isBeforeTimeStamp(e=this.getCurrentTimeStamp(),t){return(0,_dayjs.default)(e).isBefore(t)}isAfterTimeStamp(e=this.getCurrentTimeStamp(),t){return(0,_dayjs.default)(e).isAfter(t)}formatTimeByLocale(e,t="zh-tw",r="Asia/Taipei",a=!0){const n=t.toLowerCase(),s=a?"YYYY/MM/DD HH:mm":"YYYY/MM/DD hh:mm A";return(0,_dayjs.default)(e).tz(r).locale(n).format(s)}getTimeStampWithConditions(e={days:0,months:0,years:0,minutes:0,seconds:0,hours:0},t=(0,_dayjs.default)().valueOf()){let r=(0,_dayjs.default)(t);return Object.entries(e).forEach(([e,t])=>{0!==t&&(r=r.add(t,e))}),r.valueOf()}getTimeStampWithConditions(e={days:0,months:0,years:0,minutes:0,seconds:0,hours:0},t=(0,_dayjs.default)().valueOf()){let r=(0,_dayjs.default)(t);return Object.entries(e).forEach(([e,t])=>{0!==t&&(r=r.add(t,e))}),r.valueOf()}getTimeStampByStringFormat(e){return this.getTimeStampFromSpecificFormat(e,"YYYY/MM/DD HH:mm:ss")}getTimeStampFromSpecificFormat(e,t="YYYY/MM/DD HH:mm:ss"){return(0,_dayjs.default)(e,t).valueOf()}getTimeStampFromECPayStringFormat(e){return this.getTimeStampFromSpecificFormat(e,"YYYY/MM/DD HH:mm:ss")}getTimeFormatOfDurationToMillionSecond(e){return _dayjs.default.utc(e).format("HH小時mm分鐘ss秒SSS")}getTimeFormatOfDurationToSecond(e){return _dayjs.default.utc(e).format("HH小時mm分鐘ss秒")}getTimeFormatOfDurationToDay(e){return _dayjs.default.utc(e).format("DD天HH小時mm分鐘ss秒")}getChineseTimeFormat(e){return(0,_dayjs.default)(e).format("LLLL")}getMinuteFormatOfDuration(e){return _dayjs.default.duration(e).asMinutes()}getSecondFormatOfDuration(e){return _dayjs.default.duration(e).asSeconds()}getDayFormatOfDuration(e){return _dayjs.default.duration(e).asDays()}getDurationOfMillionSec(e){const t=(0,_dayjs.default)(),r=(0,_dayjs.default)(e);return Math.abs(t.diff(r))}getCurrentTimeStamp(){return(0,_dayjs.default)().valueOf()}isStringContainInLines(e,t){for(let r of _lodash.default.split(e,"\n"))if(this.has(r,t))return!0;return!1}camel(...e){return _lodash.default.camelCase(e.join("_"))}upperCamel(...e){return _lodash.default.upperFirst(this.camel(...e))}array2Obj(e){const t={};for(const r of e)t[`${this.getObjectKey(r)}`]=this.getObjectValue(r);return t}arrayToObjWith(e,t){const r={};for(const a of e){const e=t(a),n=r[e];n&&_lodash.default.isArray(n)?n.push(a):r[e]=[a]}return r}isEmptyString(e){return _lodash.default.isEqual(_lodash.default.trim(e),"")}syncSetTimeout(e,t,r=()=>{}){!function a(n){n?r():setTimeout(function(){e(),a(!0)},t)}()}mergeArrayBy(e="id",...t){return Object.values(t.flat().reduce((t,r)=>(r[e]&&(t[r[e]]={...t[r[e]]||{},...r}),t),{}))}getRelativePath(e,t){return _lodash.default.dropWhile(e,(e,r)=>_lodash.default.isEqual(e,t[r])).join("")}dropItemsByIndex(e,t,r){_lodash.default.remove(e,(e,a,n)=>r>=a&&a>=t)}isEven(e){return e%2==0}isOdd(e){return 1===Math.abs(e%2)}getVisibleOrHidden(e){return{visibility:e?"visible":"hidden"}}getNumberOfPercentageToFloat(e){let t=e.replace("%","");return parseFloat(t)/100}getVisibleOrNone(e,t=!1){return{display:e?t?"flex":"inherit":"none"}}stringToInteger(e){switch(e=_lodash.default.toUpper(e)){case"A":return 0;case"B":return 1;case"C":return 2;case"D":return 3;case"E":return 4;case"F":return 5;case"G":return 6;case"H":return 7;case"I":return 8;case"J":return 9;case"K":return 10;case"L":return 11;case"M":return 12;case"N":return 13;default:return 101}}integerToString(e){switch(e){case 0:return"A";case 1:return"B";case 2:return"C";case 3:return"D";case 4:return"E";case 5:return"F";case 6:return"G";case 7:return"H";case 8:return"I";case 9:return"J";case 10:return"K";case 11:return"L";case 12:return"M";case 13:return"N";default:return"Z"}}toObjectMap(e,...t){const r=[];for(const a of e){const e={};for(const r of t){const t=r.func?r.func:e=>e;e[r.to]=this.isUndefinedNullEmpty(r.from)||!_lodash.default.isObject(a)?t(a):t(a[r.from])}r.push(e)}return r}exeAll(e,...t){if(_lodash.default.isArray(e))for(const r of e)for(const e of t)e(r);else{if(!_lodash.default.isObject(e))throw new _exceptioner.default(9999,"7841212 type can't be array or object");for(const r in e)for(const a of t)e[r]=a(e[r])}return e}getObjectWhile(e,t,r=e=>!0){const a={};for(const n in e)r(e,t,n)&&(a[n]=e[n]);return a}getIntersectionObject(e,t){return this.getObjectWhile(e,t,(e,t,r)=>void 0!==t[r])}getDifferenceObject(e,t){return this.getObjectWhile(e,t,(e,t,r)=>void 0===t[r])}isObjectContainAndEqual(e,t){let r=!0;for(const a in e)if(void 0===t[a]||t[a]!==e[a]){r=!1;break}return r}getStringOfPop(e,t){if(!_lodash.default.isString(e))throw new _exceptioner.default(9999,"445115,type should be string but ==> "+typeof e);const r=e.split(t);return r.pop(),r.join(t)}getStringOfShift(e,t){if(!_lodash.default.isString(e))throw new _exceptioner.default(9999,"445116,type should be string but ==> "+typeof e);const r=e.split(t);return r.shift(),r.join(t)}toObjectWithAttributeKey(e,t){const r={};for(const a of e){const e=a[t];if(this.isUndefinedNullEmpty(e))throw new _exceptioner.default(9999,`48157232 pk can't be empty => '${e}'`);r[e]=a}return r}getObjectOfArraySpecifyAttr(e,t){return this.toObjectWithAttributeKey(e,t)}getStateOfStringContainsSign(e,...t){for(const r of t)if(this.has(e,r))return{exists:!0,sign:r};return{exists:!1}}constraintOfParam(e,t,...r){let a=!1;const n=!!_lodash.default.isEmpty(r)||this.and(...r.map(e=>e.logic));switch(t){case"array":_lodash.default.isArray(e)&&n&&(a=!0);break;case"object":_lodash.default.isObject(e)&&n&&(a=!0);break;case"string":_lodash.default.isString(e)&&n&&(a=!0);break;case"number":_lodash.default.isNumber(e)&&n&&(a=!0);break;case"other":if(n)return!0}const s=_lodash.default.isEmpty(r)?"":`, ${r.map(e=>e.message).join(" | ")}`;if(!1===a)throw new _exceptioner.default(9999,`7474423 type should be ${t} but get '${typeof t}' ${s} `)}getSliceArrayWithMutate(e,t){return _lodash.default.remove(e,(e,r)=>r<t)}getArrayOfInteraction(e,t){return e.filter(e=>!t.includes(e))}getArrayOfMoveToSpecificIndex(e,t,r){if(!Array.isArray(e))throw new Error("First argument must be an array.");const a=e.length;if(t<0||t>=a||r<0||r>=a)return console.warn("Invalid 'from' or 'to' index for getArrayOfMoveToSpecificIndexOptimized."),[...e];if(t===r)return[...e];const n=[...e],[s]=n.splice(t,1);return n.splice(r,0,s),n}getArrayOfMoveItemToSpecificIndex(e,t,r){const a=_lodash.default.indexOf(e,t);return this.getArrayOfMoveToSpecificIndex(e,a,r)}getArrayOfMoveSpecificItemToAside(e,t,r=!0){const a=_lodash.default.indexOf(e,t);return this.getArrayOfMoveSpecificIndexToAside(e,a,r)}getArrayOfMoveSpecificIndexToAside(e,t,r=!0){const a=_lodash.default.size(e)-1;return this.getArrayOfMoveToSpecificIndex(e,t,r?a:0)}getECPayCheckMacValue(e,t="5294y06JbISpM5x9",r="v77hoKGq4kWxNNIS"){const a=_lodash.default.cloneDeep(e);delete a.CheckMacValue;const n=Object.keys(a).sort((e,t)=>e>t?1:-1);let s="";for(const e of n)s+=`${e}=${a[e]}&`;return s=`HashKey=${t}&${s}HashIV=${r}`,s=encodeURIComponent(s).toLowerCase(),s=s.replace(/%20/g,"+").replace(/%2d/g,"-").replace(/%5f/g,"_").replace(/%2e/g,".").replace(/%21/g,"!").replace(/%2a/g,"*").replace(/%28/g,"(").replace(/%29/g,")").replace(/%20/g,"+"),_lodash.default.toUpper(_cryptoJs.default.SHA256(s).toString(_cryptoJs.default.enc.Hex))}getStringOfHandledHtml(e,t=e=>!0){const r=(0,_nodeHtmlParser.parse)(e);return t(r),r.toString()}getSpecifyObjectBy(e,t){for(const r of e)if(t(r))return r}validatePayloadObjectValid(e,t=[],r=this.getRandomHash(10)){if(this.isUndefinedNullEmpty(e))throw new _exceptioner.default(9999,`${r} content(pay-load) is undefined || empty`);for(const a of t)if(_lodash.default.isString(a)){if(this.isUndefinedNullEmpty(e[a]))throw new _exceptioner.default(9999,`${r} ATTRIBUTE:'${a}' is not Exist`)}else if(_lodash.default.isObject(a)){const t=this.getObjectKey(a);if(!this.getObjectValue(a)(e[t]))throw new _exceptioner.default(9999,`${r} ATTRIBUTE:'${t}' is not valid of custom rule`)}return!0}getArrayOfSummarizeBy(e,t,r){const a={};for(const n of e){const e=n[t];void 0!==a[e]?a[e]=a[e]+n[r]:a[e]=n[r]}const n=[];for(const e in a){const s={};s[t]=e,s[r]=a[e],n.push(s)}return n}getHeadStringSplitBy(e,t=this.getSeparatorOfUnique()){return _lodash.default.split(e,t).shift()}getTailStringSplitBy(e,t=this.getSeparatorOfUnique()){return _lodash.default.split(e,t).pop()}getSlicesByIndexes(e=[],t=[]){const r=[];return _lodash.default.each(t,(a,n,s)=>{if(_lodash.default.isEqual(n,t.length-1))return!1;const i=_lodash.default.slice(e,a,t[n+1]);r.push(i)}),r}findIndexes(e,t){const r=[];let a=!0,n=0;for(;a;)n=_lodash.default.findIndex(e,t,n+1),n>-1?r.push(n):a=!1;return r}isOverSpecificAge(e,t=18){return(0,_dayjs.default)().diff((0,_dayjs.default)(e),"years")>=t}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}isValidTaiwaneseID(e){if(!/^[A-Z][1-2]\d{8}$/.test(e))return!1;const t=[1,9,8,7,6,5,4,3,2,1];let r=10*(e.charCodeAt(0)-65)+parseInt(e.slice(1));for(let a=0;a<t.length;a++)r+=parseInt(e.charAt(a+1))*t[a];return r%10==0}validatePersonalInfoInput(e,t,r,a,n,s=12){return e.length<2?{valid:!1,message:"姓名至少要兩個字"}:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?/^[A-Z][1-2]\d{8}$/.test(r)?/^09\d{8}$/.test(a)?n&&""!==n?(0,_dayjs.default)().diff((0,_dayjs.default)(n),"years")<s?{valid:!1,message:`年齡不得小於 ${s} 歲`}:{valid:!0,message:"格式檢查通過"}:{valid:!1,message:"出生日期格式不正確"}:{valid:!1,message:"手機號碼格式不正確"}:{valid:!1,message:"身分證號碼格式不正確"}:{valid:!1,message:"電子郵件格式不正確"}}getStringOfFormatTimestampRange(e,t){const r=(0,_dayjs.default)(e),a=(0,_dayjs.default)(t),n=e=>e.format("YY/MM/DD");return r.year()===a.year()?`${n(r)} - ${a.format("MM/DD")}`:`${n(r)} - ${n(a)}`}getStringOfCalculateClassTime(e,t,r){const a=(0,_dayjs.default)(e),n=(0,_dayjs.default)(t).diff(a,"days")+1,s=Math.ceil(n/7)*r,i=Math.floor(s/60),o=s%60;return 0===o?`${i}小時`:`${i}小時${o}分鐘`}getNumberOfPeriodMinute(e,t){const r=(0,_dayjs.default)(e).format("HH:mm"),a=(0,_dayjs.default)(t).format("HH:mm"),n=(0,_dayjs.default)(r,"HH:mm"),s=(0,_dayjs.default)(a,"HH:mm");return _dayjs.default.duration(s.diff(n)).asMinutes()}getStringOfWeekTime(e,t,r){if(e<1||e>7)throw new Error("day 必須在 1 到 7 之間");const a=(0,_dayjs.default)(t).format("HH:mm"),n=(0,_dayjs.default)(r).format("HH:mm");return`${{1:"週一",2:"週二",3:"週三",4:"週四",5:"週五",6:"週六",7:"週日"}[e]} ${a}-${n}`}extractNumber(e){if(this.isUndefinedNullEmpty(e))return-1;const t=e.match(/\d+/);return t?Number(t[0]):-1}async fetchElementAttribute(e,t="innerText",r=""){return await e.evaluate(e=>e[t])}async fetchElementAttributes(e,t,r="",...a){const n=await e.$(t);if(!this.isUndefinedNullEmpty(n))try{return await n.evaluate((e,t)=>1===t.length?e[t.shift()]:{...t.map(t=>e[t])},a)}catch(e){return this.appendError(`1581532 ${t} fetch ${JSON.stringify(a)} fail, element is not found`),r}return r}async writeElementAttributes(e,t,...r){const a=await e.$(t);this.isUndefinedNullEmpty(a)?this.appendError(`1231232 ${t} fetch ${JSON.stringify(r)} fail, element is not found`):await a.evaluate((e,t)=>{t.map(t=>{const r=Object.entries(t),a=r[0][0],n=r[0][1];e[a]=n})},r)}getSliceArrayOfUnique(e){if(!Array.isArray(e)||0===e.length)return[];const t=e[0];if(_lodash.default.isObject(t)&&key){const t=new Map(e.map(e=>[e[key],e]));return Array.from(t.values())}return _lodash.default.isObject(t)?(console.warn("getSliceArrayOfUniqueOptimized: No key provided for object array, using potentially slow deep comparison."),_lodash.default.uniqWith(e,_lodash.default.isEqual)):Array.from(new Set(e))}getUniqueValuesBy(e,t="valueOfType"){return _lodash.default.uniq(e.map(e=>e[t]))}generateCombinations(...e){const t=e.map(e=>e.key),r=(_lodash.default.keyBy(e,"key"),e.map(e=>e.options.map(t=>({key:e.key,value:t.value,label:t.label})))),a=_lodash.default.reduce(r,(e,t)=>_lodash.default.flatMap(e,e=>t.map(t=>[...e,t])),[[]]).map(e=>{const t={},r=[],a=[];for(const{key:n,value:s,label:i}of e)t[n]=s,r.push(`${n}_${s}`),a.push(`${i}`);return{trait:t,id:r.join("_"),content:a.join("|")}});return _lodash.default.sortBy(a,e=>t.map(t=>e.trait[t]))}extractStaticSegments(e,t=[":"]){return e.trim().replace(/^\.?\/*|\/*$/g,"").split("/").filter(e=>e&&!t.some(t=>e.startsWith(t)))}mutateRemoveKeys(e,t){_lodash.default.forEach(e,(e,r)=>{const a=Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)));Object.keys(e).forEach(t=>delete e[t]),Object.assign(e,a)})}removeKeysFromArrayObjects(e,t){return _lodash.default.map(e,e=>Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))))}formatTextWithEllipsis(e,t){if(_lodash.default.size(e)<=t)return e;if(t<=6)return"";const r=t-6,a=Math.floor(r/2),n=r-a;return`${_lodash.default.truncate(e,{length:a,omission:""})}......${_lodash.default.takeRight(e,n).join("")}`}getObjectBy(e,t=e=>!0!==e.checked){return _lodash.default.fromPairs(_lodash.default.toPairs(e).filter(([e,r])=>t(r)))}mutateBy(e,t=e=>e){const r=_lodash.default.sortBy(e,t);e.splice(0,e.length,...r)}findUniqueStrings(...e){const t=_lodash.default.flatten(e),r=_lodash.default.countBy(t);return _lodash.default.chain(r).pickBy(e=>1===e).keys().compact().value()}getObjectOfSpecifyKey(e,t){const r={};return r[t]=e,r}findUniqueNonReferenceStrings(...e){if(0===e.length)return[];const[t,...r]=e,a=_lodash.default.flatten(r),n=_lodash.default.countBy(a);return _lodash.default.chain(n).pickBy((e,r)=>1===e&&!t.includes(r)).keys().compact().value()}getArrayOfFillMissingValues(e){const t=()=>_lodash.default.times(8,()=>_lodash.default.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")).join(""),r=new Set(e.map(e=>e.value).filter(Boolean));return e.map(e=>{if(_lodash.default.isEmpty(e.value)){let a;do{a=t()}while(r.has(a));return r.add(a),{...e,value:a}}return e})}isFirestoreAutoId(e){return _lodash.default.isString(e)&&20===e.length&&/^[A-Za-z0-9]{20}$/.test(e)}getAutoIdOfFirestore(){return this.getRandomHashV2(20)}getStringOfConvertTimeRange(e){const[t,r]=e.split("|"),a=t.split("(")[0],[n,s]=r.split("-"),i=e=>(0,_dayjs.default)(`${a} ${e}`,"YYYY/MM/DD HH:mm").format("YYYYMMDDHHmm");return`${i(n)}-${i(s)}`}getTSOfSpecificDate(e,{end:t=!1}={}){const r=(0,_dayjs.default)(e.split("(")[0],"YYYY/MM/DD"),a=t?r.endOf("day"):r.startOf("day");return Number(a.format("YYYYMMDDHHmmss"))}isHttpsURL(e){if(!_lodash.default.isString(e))return!1;try{const t=decodeURIComponent(e.trim());return"https:"===new URL(t).protocol}catch(e){return!1}}generateUniqueCodeMap(e,t=3){if(t<2)throw new Error("代碼長度最少必須為 2。");const r=new Set,a=new Set;return _lodash.default.transform(e,(e,n)=>{if(a.has(n))throw new Error(`23125453 Duplicate key detected: "${n}"`);a.add(n),e[n]=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",a=e+"0123456789";let n;do{n=e[Math.floor(52*Math.random())];for(let e=1;e<t;e++)n+=a[Math.floor(62*Math.random())]}while(r.has(n));return r.add(n),n})()},{})}getPriceOfPercentageBehavior(e,t,r=!1){const a=this.toPercentageDecimal(t);return this.getNumberOfMultiplyCeil(e,r?1-a:1+a)}getFeeOfDiscount(e,t){return Math.round(_lodash.default.multiply(e,this.toPercentageDecimal(t)))}mergeArrayByKey(e){if(!Array.isArray(e))return e;const t={};for(const r of e)if(_lodash.default.isPlainObject(r))for(const[e,a]of Object.entries(r))t[e]?_lodash.default.merge(t[e],a):t[e]=_lodash.default.cloneDeep(a);return e.length=0,Object.entries(t).forEach(([t,r])=>{e.push({[t]:r})}),e}getObjectOfStartEndDateTime(e){if(!e||"string"!=typeof e)return{startDate:"",startTime:"",endDate:"",endTime:""};const t=e.replace(/|/g," ").replace(/-/g,"-").replace(/\s+/g," ").trim(),r=/(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})\s*-\s*(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})/,a=/(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})\s*-\s*(\d{2}:\d{2})/;let n,s,i,o;if(r.test(t))[,n,s,i,o]=t.match(r);else{if(!a.test(t))return{startDate:"",startTime:"",endDate:"",endTime:""};[,n,s,o]=t.match(a),i=n}const l=new Date(`${n} ${s}`);if(new Date(`${i} ${o}`)<l)throw new Error(`End time cannot be earlier than start time: ${e}`);return{startDate:n,startTime:s,endDate:i,endTime:o}}getFilteredHeraPeriods(e,t){return _lodash.default.chain(e).filter(e=>e.idOfBooze!==t).uniqBy(e=>`${e.idOfBooze}_${e.idOfVariant}`).value()}checkPeriodConflict(e,t,r=1){const[a,n]=e.content.split("|"),s=a.split(" ")[0],[i,o]=n.split("-"),l=(0,_dayjs.default)(`${s} ${i}`,"YYYY/MM/DD HH:mm"),d=(0,_dayjs.default)(`${s} ${o}`,"YYYY/MM/DD HH:mm"),u=_lodash.default.filter(t,e=>{const[t,r]=e.period.split("-"),a=(0,_dayjs.default)(t,"YYYYMMDDHHmm"),n=(0,_dayjs.default)(r,"YYYYMMDDHHmm");return l.isBefore(n)&&d.isAfter(a)});return{conflict:u.length>=r,items:u}}}var _default=exports.default=Utiller;
|
|
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")),_cryptoJs=_interopRequireDefault(require("crypto-js")),_configerer=require("configerer"),_exceptioner=_interopRequireDefault(require("../exceptioner")),_uuid=require("uuid"),_nodeHtmlParser=require("node-html-parser"),_dayjs=_interopRequireDefault(require("dayjs"));require("dayjs/locale/zh-tw"),require("dayjs/locale/en");var _utc=_interopRequireDefault(require("dayjs/plugin/utc")),_timezone=_interopRequireDefault(require("dayjs/plugin/timezone")),_duration=_interopRequireDefault(require("dayjs/plugin/duration")),_customParseFormat=_interopRequireDefault(require("dayjs/plugin/customParseFormat")),_relativeTime=_interopRequireDefault(require("dayjs/plugin/relativeTime")),_isBetween=_interopRequireDefault(require("dayjs/plugin/isBetween"));_dayjs.default.extend(_utc.default),_dayjs.default.extend(_timezone.default),_dayjs.default.extend(_duration.default),_dayjs.default.extend(_customParseFormat.default),_dayjs.default.extend(_relativeTime.default),_dayjs.default.extend(_isBetween.default),_dayjs.default.locale("zh-tw"),String.format=function(){let e=[];for(let t=0,r=arguments.length;t<r;t++)e.push(arguments[t]);let t=e[0];return e.shift(),t.replace(/\{(\d+)\}/g,function(t,r){return e[r]})};class Utiller{removeAttributeBy(e,t=e=>_lodash.default.isUndefined(e)){for(const r in e)t(e[r])&&delete e[r]}getUrlPath(...e){return e.filter(e=>null!=e&&""!==e).map(e=>String(e)).map(e=>e.replace(/^\/+|\/+$/g,"")).filter(e=>""!==e).join("/").replace(/^(https?):\/(?!\/)/,"$1://")}getStringsOfFlatten(e=[]){return _lodash.default.chain(e).flatten().filter(e=>null!=e&&""!==e).value()}getNumberOfNormalize(e,t=0){if(_lodash.default.isNumber(e))return e;try{const r=_lodash.default.toNumber(e);return _lodash.default.isNumber(r)&&!isNaN(r)?r:t}catch(e){this.appendError(`448561684561 ${e.message}`)}return t}getStringOfNormalize(e,t="",r=!1){if(_lodash.default.isString(e))return r?_lodash.default.trim(e):e;try{const a=_lodash.default.toString(e);return this.isOrEquals(a,"","undefined")?t:r?_lodash.default.trim(a):a}catch(e){thisappendError(`448616845453 ${e.message}`)}return t}isValidVersionOfString(e){if(this.isUndefinedNullEmpty(e))return!1;const t=e.split(".");for(const e of t){const t=_lodash.default.toNumber(e);if(!_lodash.default.isNumber(t)||isNaN(t))return!1}return!0}getSeparatorOfUnique(){return"།།"}getStringOfVersionIncrement(e,t=1){const r=e.split(".").map(e=>_lodash.default.toNumber(e)),a=r.length-1;return r[a]=r[a]+t,r.join(".")}setLocaleOfDate(e="en"){_dayjs.default.locale(e.toLowerCase())}getUuidOfV4(){return(0,_uuid.v4)()}constructor(){(0,_defineProperty2.default)(this,"mapOfIdNTimeoutId",{}),(0,_defineProperty2.default)(this,"compactConsecutive",e=>_lodash.default.isArray(e)?_lodash.default.sortedUniq(e):[]),(0,_defineProperty2.default)(this,"getEnvironment",()=>this.env),(0,_defineProperty2.default)(this,"isProductionEnvironment",()=>_lodash.default.isEqual(this.getEnvironment(),"prod")),(0,_defineProperty2.default)(this,"asyncUnitTaskFunction",(e=2e3,t="預設的param",r)=>async(a=this.getRandomHash(10))=>{const n=this.getRandomValue(e,1.2*e);try{const e=n;if(this.appendInfo(`before executed ===> i'm symbol of ${e}, ready to be executed, inner param = ${t}`),await this.syncDelay(n),_lodash.default.isFunction(r)&&r(a))throw Error("force to made error happen");return this.appendInfo(`after executed ===> i'm symbol of ${e}, the task cost ${n} million-seconds ${a?`i hav params ===> ${a}`:""}`),{randomValue:n,symbol:e,param:a}}catch(e){this.appendError(new Error(`asyncUnitTask() catch error ${e.message}`))}finally{this.appendInfo("wow.... finally got you")}}),(0,_defineProperty2.default)(this,"findLowestValue",(e,t="price")=>{const r=_lodash.default.minBy(e,t)[t];return Math.floor(r)}),(0,_defineProperty2.default)(this,"findHighestValue",(e,t="price")=>{const r=_lodash.default.maxBy(e,t)[t];return Math.floor(r)}),(0,_defineProperty2.default)(this,"getStringOfValueRange",(e,t="price",r="$")=>{const a=_lodash.default.minBy(e,t)[t],n=_lodash.default.maxBy(e,t)[t];return n===a?`$${a}`:`${r}${a} - ${r}${n}`}),(0,_defineProperty2.default)(this,"getCallersName",()=>{let e;try{throw new Error}catch(t){let r,a=/(\w+)@|at (\w+) \(/g,n=t.stack;a.exec(n),r=a.exec(n),_lodash.default.isNull(r)||(e=r[1]||r[2])}return _lodash.default.startsWith("asyncGeneratorStep",e)&&(e=""),e}),(0,_defineProperty2.default)(this,"getRandomValue",(e,t)=>(e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e)),(0,_defineProperty2.default)(this,"insertToArray",(e,t,...r)=>{if(!Array.isArray(e))throw new Error("First argument must be an array.");const a=Math.max(0,Math.min(t+1,e.length));e.splice(a,0,...r)}),(0,_defineProperty2.default)(this,"getStringOfYearADConvertToMinguoYear",(e,t=!1)=>{const r=e-1911;return r>0?`${t?"民國":""}${r}${t?"年":""}`:`${t?"民國":""}前${Math.abs(r)}${t?"年":""}`}),(0,_defineProperty2.default)(this,"merO",(...e)=>_lodash.default.merge(...e)),(0,_defineProperty2.default)(this,"merO4",(...e)=>{if(0===e.length)return{};const t=e[0],r=e.slice(1),a=_lodash.default.cloneDeep(t);return _lodash.default.merge(a,...r)}),(0,_defineProperty2.default)(this,"convertDateToTimestamp",e=>(0,_dayjs.default)(e).valueOf()),(0,_defineProperty2.default)(this,"measureExecutionTime",async(e,...t)=>{const r=Date.now();await e(...t);const a=Date.now()-r,n=_dayjs.default.duration(a),s=Math.floor(n.asHours()),i=n.minutes(),o=n.seconds(),l=n.milliseconds(),d=(a/1e3).toFixed(3);return{second:d,zh_TW:`${s}小時 ${i}分 ${o}.${l.toString().padStart(3,"0")}秒 (合計 ${d} 秒)`}}),(0,_defineProperty2.default)(this,"formatPriceWithCurrency",(e,t)=>{if("number"!=typeof e||"string"!=typeof t)throw new TypeError("Invalid input: number must be a number and locale must be a string.");return new Intl.NumberFormat(t,{style:"currency",currency:new Intl.Locale(t).maximize().currency||"USD",minimumFractionDigits:0}).format(e)}),(0,_defineProperty2.default)(this,"formatPrice",(e,t)=>{if("number"!=typeof e)throw new TypeError("Invalid input: number must be a number.");return t?new Intl.NumberFormat(t,{style:"currency",currency:new Intl.Locale(t).maximize().currency||"USD",minimumFractionDigits:0}).format(e):e.toLocaleString("en-US")}),(0,_defineProperty2.default)(this,"generateUniversalKeywords",(e,t=50,r=4)=>{if(!e||"string"!=typeof e)return[];if(void 0===_lodash.default)return console.error("Lodash is not available. Please ensure it is imported."),[];let a=e.trim(),n=[];r=Math.max(2,r),a.length>t&&(console.warn(`警告:輸入字串長度為 ${a.length},已根據 maxLength: ${t} 截斷。`),a=a.substring(0,t)),(a.match(/[a-zA-Z]+/g)||[]).forEach(e=>{if(e.length>=2){n.push(e.toUpperCase()),n.push(e.toLowerCase());const t=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase();n.push(t)}});const s=(a.match(/\b[0-9]+[a-zA-Z]{1,4}\b|\b[0-9]{1,3}(w|ml|g|oz|k)\b|[\u4e00-\u9fa5a-zA-Z0-9]{1,4}(色|號)[\u4e00-\u9fa5a-zA-Z0-9]{0,2}/gi)||[]).filter(e=>e.length>=2).map(e=>e.toLowerCase());n.push(...s);let i=a.toLowerCase();i=i.replace(/[0-9]+([\u4e00-\u9fa5a-z]{1,4}|[\/\-\~\\])/g," ").replace(/\b[a-z]{1,4}\b/g," ").replace(/\b[0-9]{1,3}\b/g," "),i=i.replace(/[!@#$%^&*()_+={}\[\]:;"'<>,.?\/\\|`~]/g," ").replace(/系列|一組|單色|多款|套組|全套|專用|迷你|頂級|高品質|超閃|奢華|最新|款式|新款|超亮|的|與|和|閃|美甲/g," ").replace(/\s+/g,"").trim();for(let e=2;e<=r;e++)for(let t=0;t<=i.length-e;t++){const r=i.substring(t,t+e);n.push(r)}return _lodash.default.chain(n).filter(e=>e.length>=2).filter(e=>e.length>2||!/^[\u4e00-\u9fa5a-z0-9]$/.test(e)).uniq().sortBy().value()}),(0,_defineProperty2.default)(this,"mutateIndexOfArrayItem",(e,t,r=0)=>{if(!Array.isArray(e)||!_lodash.default.isObject(t))return e;const a=_lodash.default.findIndex(e,e=>_lodash.default.isEqual(e,t));if(-1===a)return e;e.splice(a,1);const n=_lodash.default.clamp(r,0,e.length);return e.splice(n,0,t),e}),(0,_defineProperty2.default)(this,"getArrayOfModifyObject2Index",(e,t,r=0)=>{if(!Array.isArray(e)||!_lodash.default.isObject(t))return e;const a=_lodash.default.cloneDeep(e),n=_lodash.default.findIndex(a,e=>_lodash.default.isEqual(e,t));if(-1===n)return e;a.splice(n,1);const s=_lodash.default.clamp(r,0,a.length);return a.splice(s,0,t),a}),(0,_defineProperty2.default)(this,"generateLabelValuePairsWithOrigin",(e=[{label:"aa",value:1203},{label:"cc",value:1204},{label:"gg",value:2}],t=["aa","bb"])=>{const r=new Set(e.map(e=>e.value));return _lodash.default.chain(t).uniq().map(t=>{const a=_lodash.default.find(e,{label:t});if(a)return{label:t,value:a.value};let n;do{n=_lodash.default.random(2,999999999)}while(r.has(n));return r.add(n),{label:t,value:n}}).value()}),(0,_defineProperty2.default)(this,"getItemsOfMarkMatching",(e=[],t=[],r="value",a="belong")=>{const n=new Set(t);return _lodash.default.map(e,e=>({...e,[a]:n.has(e[r])}))}),(0,_defineProperty2.default)(this,"generateVariants",(e,t="|",r="-")=>{const a=e.filter(e=>e.length>0);return 0===a.length?[]:1===a.length?a[0].map(e=>({label:e.label,value:e.value})):_lodash.default.reduce(a,(e,t)=>_lodash.default.flatMap(e,e=>t.map(t=>[...e,t])),[[]]).map(e=>({label:e.map(e=>e.label).join(t),value:e.map(e=>e.value).join(r)}))}),(0,_defineProperty2.default)(this,"renameKeysInArray",(e,...t)=>{const r=Object.fromEntries(t);return e.map(e=>_lodash.default.mapKeys(e,(e,t)=>r[t]||t))}),(0,_defineProperty2.default)(this,"getArrayOfMergeBySpecificId",(e,t,r="id")=>{if(!Array.isArray(t))return e;const a=_lodash.default.keyBy(t,e=>_lodash.default.get(e,r));return e.map(e=>{const t=_lodash.default.get(e,r),n=a[t];return n?_lodash.default.merge({},e,n):e})}),(0,_defineProperty2.default)(this,"toPercentageDecimal",e=>{if(_lodash.default.isNil(e))return 1;_lodash.default.isString(e)&&(e=e.replace(/%/g,"").trim());const t=_lodash.default.toNumber(e);return _lodash.default.isFinite(t)?_lodash.default.round(t/100,10):1}),(0,_defineProperty2.default)(this,"getNumberOfMultiplyCeil",(e,t,r=0)=>{const a=Math.pow(10,r);return Math.ceil(e*t*a)/a}),(0,_defineProperty2.default)(this,"generateGoogleCalendarLink",({title:e,startDate:t,startTime:r,endDate:a,endTime:n,location:s,details:i})=>{const o="YYYYMMDDTHHmmss",l=(0,_dayjs.default)(`${t} ${r}`,"YYYY/MM/DD HH:mm").format(o),d=(0,_dayjs.default)(`${a} ${n}`,"YYYY/MM/DD HH:mm").format(o),u=new URLSearchParams;return e&&u.append("text",e),l&&d&&u.append("dates",`${l}/${d}`),i&&u.append("details",i),s&&u.append("location",s),u.append("ctz","Asia/Taipei"),u.append("trp","true"),`https://calendar.google.com/calendar/r/eventedit?${u.toString()}`}),(0,_defineProperty2.default)(this,"generateTimeTreeLink",({title:e,startDate:t,startTime:r,endDate:a,endTime:n,location:s,memo:i})=>{const o=new URLSearchParams;return e&&o.append("title",e),t&&o.append("start_date",t.replace(/\//g,"-")),r&&o.append("start_time",r),a&&o.append("end_date",a.replace(/\//g,"-")),n&&o.append("end_time",n),s&&o.append("location",s),i&&o.append("memo",i),`https://timetreeapp.com/plans/new?${o.toString()}`}),(0,_defineProperty2.default)(this,"generateIcsContent",({title:e,startDate:t,startTime:r,endDate:a,endTime:n,location:s,details:i})=>{const o="Asia/Taipei",l="YYYYMMDDTHHmmss",d=_dayjs.default.tz(`${t} ${r}`,"YYYY/MM/DD HH:mm",o).format(l),u=_dayjs.default.tz(`${a} ${n}`,"YYYY/MM/DD HH:mm",o).format(l),f=(0,_dayjs.default)().utc().format(l)+"Z",c=e=>(e||"").replace(/\\/g,"\\\\").replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/\n/g,"\\n"),h=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//Gemini AI//NONSGML v1.0//EN","BEGIN:VEVENT","UID:"+(Date.now().toString(36)+Math.random().toString(36).substring(2,5)+"@gemini-app.com"),`DTSTAMP:${f}`];return d&&h.push(`DTSTART;TZID=${o}:${d}`),u&&h.push(`DTEND;TZID=${o}:${u}`),e&&h.push(`SUMMARY:${c(e)}`),s&&h.push(`LOCATION:${c(s)}`),i&&h.push(`DESCRIPTION:${c(i)}`),h.push("END:VEVENT","END:VCALENDAR"),h.join("\r\n")}),(0,_defineProperty2.default)(this,"generateAllCalendarLinks",e=>{const t=this.generateGoogleCalendarLink(e),r={...e,memo:e.details},a=this.generateTimeTreeLink(r),n=this.generateIcsContent(e);return{google:t,timeTree:a,ics:`data:text/calendar;charset=utf8,${encodeURIComponent(n)}`}}),(0,_defineProperty2.default)(this,"getArrayOfMappingRef",(e,t)=>_lodash.default.map(e,e=>{const r=_lodash.default.find(t,{value:e.value});return r?_lodash.default.merge({},e,r):e})),(0,_defineProperty2.default)(this,"areAllValuesTheSameOnKeys",(e,...t)=>{if(!e||e.length<=1||0===t.length)return!0;for(const r of t){const t=e[0]?.[r];if(!_lodash.default.every(e,e=>e[r]===t))return!1}return!0}),(0,_defineProperty2.default)(this,"getArrayOfUniqBy",(e,t)=>{if(!Array.isArray(e))return console.error("Input must be an array."),[];if("string"!=typeof t||0===t.length)return console.error("Key must be a non-empty string."),[...e];const r=e.reduce((e,r)=>{const a=r[t];return e.has(a)||e.set(a,r),e},new Map);return Array.from(r.values())}),(0,_defineProperty2.default)(this,"execute4Tasks",async(e=[],t)=>{if(!t||"function"!=typeof t)throw new Error("Task function is required and must be a function.");if("AsyncFunction"!==t.constructor.name)throw new Error("Task function must be an asynchronous function (async function) to ensure proper Promise handling.");return 0===e.length?Promise.resolve([]):await Promise.all(e.map(async(r,a)=>t(r,a,e)))}),(0,_defineProperty2.default)(this,"execute4Settled",async(e=[],t)=>{if(!t||"function"!=typeof t)throw new Error("Task function is required and must be a function.");if("AsyncFunction"!==t.constructor.name)throw new Error("Task function must be an asynchronous function (async function) to ensure proper Promise handling.");return 0===e.length?Promise.resolve([]):await Promise.allSettled(e.map((r,a)=>t(r,a,e)))}),(0,_defineProperty2.default)(this,"getReadableOfFileS",(e,t=2)=>{if(0===e)return"0 Bytes";const r=t<0?0:t,a=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,a)).toFixed(r))+" "+["Bytes","KB","MB","GB","TB"][a]}),(0,_defineProperty2.default)(this,"getNumOfFileS",e=>{if(null==e)throw new Error("輸入不能為空");const t=String(e).toUpperCase().trim().match(/^(\d+(\.\d+)?)\s*([A-Z]*)$/);if(!t)throw new Error(`[Invalid Format] 無法解析:'${e}'。請確保格式如 '5MB'`);const r=parseFloat(t[1]),a=t[3],n={"":1,B:1,K:1024,KB:1024,M:1048576,MB:1048576,G:1024**3,GB:1024**3,T:1024**4,TB:1024**4};if(!(a in n))throw new Error(`[Unknown Unit] 未知的容量單位:'${a}'`);return r*n[a]}),(0,_defineProperty2.default)(this,"isCallable",e=>{if("function"==typeof e)return!0;if(e&&"object"==typeof e){const t=Object.prototype.toString.call(e);return!!["[object Function]","[object AsyncFunction]","[object GeneratorFunction]"].includes(t)||"function"==typeof e.call&&"function"==typeof e.apply}return!1}),(0,_defineProperty2.default)(this,"isP",e=>{if(!e)return!1;const t=Object.prototype.toString.call(e);if("[object AsyncFunction]"===t||"function"==typeof e&&"AsyncFunction"===e.constructor?.name)throw new Error("[isPromise Error]: You passed an AsyncFunction instead of a Promise. Did you forget to execute it? (e.g., use 'isPromise(task())' instead of 'isPromise(task)')");return"[object Promise]"===t||e instanceof Promise||("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}),(0,_defineProperty2.default)(this,"exeAsyncT",(e,{thenDo:t,catchDo:r,finallyDo:a,ignore:n=!1}={})=>{if(!this.isP(e))throw console.error("Task validation failed:",e),new Error("[exeAsyncT]: task must be a Promise. Did you forget to call the async function?");return e.then(async e=>{this.isCallable(t)&&await t(e)}).catch(async e=>{if(this.isCallable(r))await r(e);else if(!n)throw console.error("[exeAsyncT Catch]:",e),e}).finally(async()=>{this.isCallable(a)&&await a()})}),this.init(),this.env="dev"}performActionWithoutTimingIssue(e=()=>!0,t=10){this.syncDelay(t).then(()=>e())}executeTimeoutTask(e,t=1e3,r=this.getRandomHash(),...a){const n=this,s=this.mapOfIdNTimeoutId[r];s&&clearTimeout(s);const i=setTimeout(async(...t)=>{await e(),delete n.mapOfIdNTimeoutId[r]},t,...a);n.mapOfIdNTimeoutId[r]=i}printLogMessage(e,t=!1,...r){this.isProductionEnvironment()||(t?this.appendError(e,...r):this.appendInfo(e,...r))}init(){}setEnvironment(e){this.env=e}appendInfo(...e){this.isProductionEnvironment()||console.log(...e)}appendError(...e){this.isProductionEnvironment()||console.error(...e)}async syncDelay(e=2e3){return new Promise(t=>{setTimeout(()=>{t(e)},e)})}startWithRegex(e="",t="."){return new RegExp(`^${t}`,"i").test(e)}accumulate(e,t){let r=e;for(const e of t)void 0!==e&&_lodash.default.isFunction(e)&&(r=e(r));return r}isOrEquals(e,...t){for(const r of t)if(_lodash.default.isEqual(e,r))return!0;return!1}isAndEquals(...e){for(const t of e)if(!t())return!1;return!0}getStringOfHeadMatch(e,t,r="g"){const a=e.match(new RegExp(t,r));return this.isUndefinedNullEmpty(a)?void 0:a[0]}or(...e){for(const t of e)if(_lodash.default.isBoolean(t)&&t)return!0;return!1}and(...e){for(const t of e)if(!t)return!1;return!0}nth(e,t=-1){return _lodash.default.nth(e,t%_lodash.default.size(e))}getExistOne(...e){for(const t of e)if(t)return t}getStringOfDropHeadSign(e,t){return _lodash.default.dropWhile(Array.from(e),e=>_lodash.default.isEqual(e,t)).join("")}isAndWith(e,t,...r){for(const a of r)if(!t(e,a))return!1;return!0}async syncDelayRandom(e=3e3,t=5e3){const r=this.getRandomValue(e,t);return await this.syncDelay(r),r}has(e,t,r=!1){return _lodash.default.isArray(e)?r?_lodash.default.findIndex(e,e=>_lodash.default.isEqual(t,e))>-1:_lodash.default.indexOf(e,t)>-1:_lodash.default.isObject(t)?e[t]:!!_lodash.default.isString(e)&&e.indexOf(t)>-1}containsBy(e,t){return _lodash.default.findIndex(e,e=>_lodash.default.isEqual(e,t))>=0}getStringOfInsideParentheses(e,t="."){return this.getStringOfRule(e,t,"(",")")}getStringOfInsideBrackets(e,t="."){return this.getStringOfRule(e,t,"[","]")}getStringOfInsideBraces(e,t="."){return this.getStringOfRule(e,t,"{","}")}getStringOfRule(e,t=".",r="{",a="}"){return this.getStringOfHeadMatch(e,`(?<=\\${r})${t}+?(?=\\${a})`)}getRandomHash(e=20){const t=_cryptoJs.default.lib.WordArray.random(e);return _cryptoJs.default.enc.Base64.stringify(t).substring(0,e)}getRandomHashV2(e){let t="";for(let r=0;r<e;r++){const e=Math.floor(62*Math.random());t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(e)}return t}getEncryptString(e,t=_configerer.configerer.ENCRYPT_KEY,r=!1){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const a=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue"),n=r?_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`):t;return _cryptoJs.default.AES.encrypt(e,n,{iv:a}).toString()}getEncryptStringV2(e,t=_configerer.configerer.ENCRYPT_KEY,r=!1){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const a=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue"),n=r?_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`):t;return _cryptoJs.default.AES.encrypt(JSON.stringify({content:e}),n,{iv:a}).toString()}getDecryptString(e,t=_configerer.configerer.ENCRYPT_KEY){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const r=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const a=_cryptoJs.default.AES.decrypt(e,t,{iv:r}).toString(_cryptoJs.default.enc.Utf8);if(!_lodash.default.isEmpty(a.trim()))return a}catch(e){}return _cryptoJs.default.AES.decrypt(e,_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`),{iv:r}).toString(_cryptoJs.default.enc.Utf8)}getDecryptStringV2(e,t=_configerer.configerer.ENCRYPT_KEY){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const r=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const a=_cryptoJs.default.AES.decrypt(e,t,{iv:r}).toString(_cryptoJs.default.enc.Utf8);if(!_lodash.default.isEmpty(a.trim()))return JSON.parse(a).content}catch(e){}const a=_cryptoJs.default.AES.decrypt(e,_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`),{iv:r}).toString(_cryptoJs.default.enc.Utf8);return JSON.parse(a).content}getFirebaseFormattedString(e){return _lodash.default.replace(e,/[\.\#\$\[\]]/g,"-").trim()}formalizeNamesToArray(e){let t=e;for(t=t.split(_configerer.configerer.SEPARATE_TONE_SINGER)[0].trim(),t=_lodash.default.replace(t,/[,\/#!$%\^&\*;:{}=_`、~()()]/g,"_").trim(),t=this.getFirebaseFormattedString(t),t=_lodash.default.replace(t,/\_\_+/g,"_").trim();_lodash.default.endsWith(t,"_");)t=t.slice(0,-1).trim();const r=t.split("_");return _lodash.default.map(r,e=>_lodash.default.trim(e))}getShuffledArrayWithLimitCountHighPerformance(e,t){let r=new Array(t),a=e.length,n=new Array(a);for(t>a&&(t=a);t--;){let s=Math.floor(Math.random()*a);r[t]=e[s in n?n[s]:s],n[s]=--a in n?n[a]:a}return r}getFileNameFromPath(e,t=!1){const r=e.split("/").pop();return t?r:r.split(".").shift()}getFileNameExtensionFromPath(e){return e.split("/").pop()}getPathOfReplaceLastDir(e,t){const r=e.split("/");return r.pop(),r.push(t),r.join("/")}getExtensionFromPath(e){const t=e.split("/").pop().split(".");return _lodash.default.size(t)>1?t.pop():""}getFolderPathOfSpecificPath(e){const t=e.split("/");return t.pop(),t.join("/")}getFolderNameOfFilePath(e){if(this.isValidFilePath(e)){const t=e.split("/");return _lodash.default.nth(t,-2)}throw new _exceptioner.default(9999,`64255615 path is not valid '${e}'`)}isUnderTargetPath(e,t){const r=e.split("/");return this.has(r,t)}getFileDirPath(e,t=!0){return _lodash.default.join(_lodash.default.initial(_lodash.default.split(e,"/")),"/")+(t?"/":"")}isPathEqualsFileType(e,t){const r=e.split(".").pop();return _lodash.default.isEqual(r,t)}isValidFilePath(e){const t=this.getExtensionFromPath(e);return _lodash.default.size(t)>0}getArrayOfSize(e,t=1){return _lodash.default.take(e,t)}getShuffledArrayWithLimitCount(e,t){return this.getShuffledArrayWithLimitCountHighPerformance(e,t)}getRandomItemOfArray(e,...t){if(!_lodash.default.isArray(e))throw new _exceptioner.default(9999,`why are you so stupid, typeof array should be array, not ==> ${e} `);const r=_lodash.default.without(e,...t),a=_lodash.default.size(r)>0?r:e,n=this.getShuffledArrayWithLimitCount(a,1);return n.length>0?n[0]:void 0}appendMapOfKeyArray(e,t,...r){this.isUndefinedNullEmpty(e[t])?e[t]=[...r]:e[t].push(...r)}getMergedArrayBy(e=[],t=[],r){if(!r||0===e.length||0===t.length)return[...e];const a=new Map(t.map(e=>[e[r],e]));return e.map(e=>({...a.get(e[r])||{},...e}))}getShuffledItemFromArray(e){return _lodash.default.shuffle(e)[0]}getShuffledArray(e){return _lodash.default.shuffle(e)}isJson(e){e="string"!=typeof e?JSON.stringify(e):e;try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e}getObjectValue(e){return _lodash.default.isObject(e)?Object.values(e)[0]:""}getObject(e,t){const r={};return r[e]=t,r}getStringOfCreditCardFormatted(e=0){return e.replace(/\D/g,"").replace(/(\d{4})(?=\d)/g,"$1-").slice(0,19)}getObjectKey(e){return _lodash.default.isObject(e)?Object.keys(e)[0]:""}printf(){this.appendInfo("i can use in web || react.js")}isKeywordRule(e){if(_lodash.default.isUndefined(e)||_lodash.default.isEmpty(e))throw new Error("PARAMS CAN NOT BE EMPTY");if(!_lodash.default.isString(e))throw new Error("PARAMS SHOULD BE STRING");if(e.length>20)throw new Error("EXCEED 20 WORDS IS NOT ALLOWED")}getItsKeyByValue(e,t){return Object.keys(e).find(r=>e[r]===t)}startWiths(e,t=[]){for(const r of t)if(_lodash.default.startsWith(e,r))return!0;return!1}replaceAll(e,t,r){return _lodash.default.replace(e,new RegExp(`${t}`,"g"),r)}replaceAllWithSets(e="",...t){let r=e;for(const e of t){if(this.isOrEquals(void 0,e.from,e.to))throw(0,_exceptioner.default)(9999,"from or to can't be empty");r=this.replaceAll(r,e.from,e.to)}return r}replaceArrayByContentIndex(e,t,r){e[_lodash.default.indexOf(e,t)]=r}deepFlat(e,t="_"){let r="";const a=[[e,""]];for(;a.length>0;){const[e,n]=a.pop();if(_lodash.default.isArray(e))for(let t=e.length-1;t>=0;t--)a.push([e[t],n]);else if(_lodash.default.isObject(e)){const r=Object.keys(e);for(let s=r.length-1;s>=0;s--){const i=r[s];a.push([e[i],n+i+t])}}else{const a=_lodash.default.trim(String(e));a.length>0?r+=(r.length>0?t:"")+n+a:n.length>0&&r.length>0?r+=t:n.length>0&&0===r.length&&(r+=n.endsWith(t)?n.slice(0,-t.length):n)}}return r.endsWith(t)&&(r=r.slice(0,-t.length)),r}joinEscapeChar(e){return(e+"").replace(/[\\"']/g,"\\$&").replace(/\u0000/g,"\\0")}getValueWithIntegerType(e){try{const t=parseInt(e);return isNaN(t)?0:t}catch(e){return 0}}getValueOfPriority(...e){for(const t of e)if(!this.isUndefinedNullEmpty(t))return t}async asyncPool(e,t,r){const a=[],n=[];for(const s of t){const i=Promise.resolve().then(()=>r(s,t));if(a.push(i),e<=t.length){const t=i.then(()=>n.splice(n.indexOf(t),1));n.push(t),n.length>=e&&await Promise.race(n)}}return Promise.all(a)}getAttrValueInSequence(e,...t){for(const r of t)if(!_lodash.default.isEmpty(e[r]))return e[r];return e}toDBC(e){for(var t="",r=0;r<e.length;r++)32===e.charCodeAt(r)&&(t+=String.fromCharCode(12288)),e.charCodeAt(r)<127&&(t+=String.fromCharCode(e.charCodeAt(r)+65248));return t}toCDB(e){for(var t="",r=0;r<e.length;r++)12288!==e.charCodeAt(r)?e.charCodeAt(r)>65280&&e.charCodeAt(r)<65375?t+=String.fromCharCode(e.charCodeAt(r)-65248):t+=String.fromCharCode(e.charCodeAt(r)):t+=String.fromCharCode(e.charCodeAt(r)-12256);return t}findIndexes(e,t){const r=[];let a=!0,n=0;for(;a;)n=_lodash.default.findIndex(e,t,n+1),n>-1?r.push(n):a=!1;return r}getSliceArrayOfSpecificIndexes(e,...t){const r=[],a=_lodash.default.size(e);for(const n of t){if(!_lodash.default.isNumber(n))throw new _exceptioner.default(9999,`59941278 index should be number => ${n}, ${e}`);if(n>a-1)throw new _exceptioner.default(9999,`5994123 index=>${n} is not valid, exceed than array size=${a}, ${e}`);r.push(_lodash.default.nth(e,n))}return r}indexesOf(e,t){const r=[];let a=-1;for(;-1!==(a=e.indexOf(t,a+1));)r.push(a);return r}getIndexOfContext(e,t){return _lodash.default.findIndex(e,e=>_lodash.default.isEqual(e.trim(),t))}toOneLineString(e){return _lodash.default.join(_lodash.default.split(e,"\n"),"")}toSpaceLessString(e){return _lodash.default.split(e,"").map(e=>_lodash.default.trim(e)).join("")}toNewLineLessString(e){return _lodash.default.split(e,"\n").map(e=>_lodash.default.trim(e)).join("")}exist(e){return!_lodash.default.isNull(e)&&!_lodash.default.isUndefined(e)}isUndefinedNullEmpty(e){const t=null==e,r=!!(_lodash.default.isString(e)||_lodash.default.isArray(e)||_lodash.default.isObject(e))&&_lodash.default.isEmpty(e);return t||r}isAndConditionOfUndefinedNullEmpty(...e){for(const t of e)if(!this.isUndefinedNullEmpty(t))return!1;return!0}isOrConditionOfUndefinedNullEmpty(...e){for(const t of e)if(this.isUndefinedNullEmpty(t))return!0;return!1}getStringHandledByEachLine(e,t=(e,t,r)=>!0,r="\n"){const a=e.split(r);for(const e of a)t(e,_lodash.default.indexOf(a,e),a);return a.join(r)}getSegmentsOfEachLine(e){return e.split("\n")}getNormalizedStringEndWith(e,t){e=this.toCDB(e),t=this.toCDB(t);const r=_lodash.default.join(_lodash.default.dropRightWhile(e,e=>!_lodash.default.isEqual(e,t)),"");return _lodash.default.isEmpty(r)?e:r}getNormalizedStringNotStartWith(e,...t){e=this.toCDB(e);const r=_lodash.default.join(_lodash.default.dropWhile(e,e=>this.has(t,e)),"");return _lodash.default.isEmpty(r)?e:r}getNormalizedStringNotEndWith(e,...t){e=this.toCDB(e);const r=_lodash.default.join(_lodash.default.dropRightWhile(e,e=>this.has(t,e)),"");return _lodash.default.isEmpty(r)?e:r}getTodayTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY-MM-DD")}getCustomFormatOfDatePresent(e,t="YY/MM"){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format(t)}getSimpleDateYYMMDDFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YY/MM/DD")}getSimpleTimeYYMMDDHHmmFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YY/MM/DD HH:mm")}getECPayCurrentTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatV2(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatYMDHM(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm")}getCurrentTimeFormatYMDHMS(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY-MM-DD-HH-mm-ss")}getCurrentMillionSecTimeFormat(e){return(0,_dayjs.default)(e||void 0).format("YYYY-MM-DD-HH-mm-ss-SSS")}isBetweenTimeStamp(e=this.getCurrentTimeStamp(),t,r){return(0,_dayjs.default)(e).isBetween(t,r)}isBeforeTimeStamp(e=this.getCurrentTimeStamp(),t){return(0,_dayjs.default)(e).isBefore(t)}isAfterTimeStamp(e=this.getCurrentTimeStamp(),t){return(0,_dayjs.default)(e).isAfter(t)}formatTimeByLocale(e,t="zh-tw",r="Asia/Taipei",a=!0){const n=t.toLowerCase(),s=a?"YYYY/MM/DD HH:mm":"YYYY/MM/DD hh:mm A";return(0,_dayjs.default)(e).tz(r).locale(n).format(s)}getTimeStampWithConditions(e={days:0,months:0,years:0,minutes:0,seconds:0,hours:0},t=(0,_dayjs.default)().valueOf()){let r=(0,_dayjs.default)(t);return Object.entries(e).forEach(([e,t])=>{0!==t&&(r=r.add(t,e))}),r.valueOf()}getTimeStampWithConditions(e={days:0,months:0,years:0,minutes:0,seconds:0,hours:0},t=(0,_dayjs.default)().valueOf()){let r=(0,_dayjs.default)(t);return Object.entries(e).forEach(([e,t])=>{0!==t&&(r=r.add(t,e))}),r.valueOf()}getTimeStampByStringFormat(e){return this.getTimeStampFromSpecificFormat(e,"YYYY/MM/DD HH:mm:ss")}getTimeStampFromSpecificFormat(e,t="YYYY/MM/DD HH:mm:ss"){return(0,_dayjs.default)(e,t).valueOf()}getTimeStampFromECPayStringFormat(e){return this.getTimeStampFromSpecificFormat(e,"YYYY/MM/DD HH:mm:ss")}getTimeFormatOfDurationToMillionSecond(e){return _dayjs.default.utc(e).format("HH小時mm分鐘ss秒SSS")}getTimeFormatOfDurationToSecond(e){return _dayjs.default.utc(e).format("HH小時mm分鐘ss秒")}getTimeFormatOfDurationToDay(e){return _dayjs.default.utc(e).format("DD天HH小時mm分鐘ss秒")}getChineseTimeFormat(e){return(0,_dayjs.default)(e).format("LLLL")}getMinuteFormatOfDuration(e){return _dayjs.default.duration(e).asMinutes()}getSecondFormatOfDuration(e){return _dayjs.default.duration(e).asSeconds()}getDayFormatOfDuration(e){return _dayjs.default.duration(e).asDays()}getDurationOfMillionSec(e){const t=(0,_dayjs.default)(),r=(0,_dayjs.default)(e);return Math.abs(t.diff(r))}getCurrentTimeStamp(){return(0,_dayjs.default)().valueOf()}isStringContainInLines(e,t){for(let r of _lodash.default.split(e,"\n"))if(this.has(r,t))return!0;return!1}camel(...e){return _lodash.default.camelCase(e.join("_"))}upperCamel(...e){return _lodash.default.upperFirst(this.camel(...e))}array2Obj(e){const t={};for(const r of e)t[`${this.getObjectKey(r)}`]=this.getObjectValue(r);return t}arrayToObjWith(e,t){const r={};for(const a of e){const e=t(a),n=r[e];n&&_lodash.default.isArray(n)?n.push(a):r[e]=[a]}return r}isEmptyString(e){return _lodash.default.isEqual(_lodash.default.trim(e),"")}syncSetTimeout(e,t,r=()=>{}){!function a(n){n?r():setTimeout(function(){e(),a(!0)},t)}()}mergeArrayBy(e="id",...t){return Object.values(t.flat().reduce((t,r)=>(r[e]&&(t[r[e]]={...t[r[e]]||{},...r}),t),{}))}getRelativePath(e,t){return _lodash.default.dropWhile(e,(e,r)=>_lodash.default.isEqual(e,t[r])).join("")}dropItemsByIndex(e,t,r){_lodash.default.remove(e,(e,a,n)=>r>=a&&a>=t)}isEven(e){return e%2==0}isOdd(e){return 1===Math.abs(e%2)}getVisibleOrHidden(e){return{visibility:e?"visible":"hidden"}}getNumberOfPercentageToFloat(e){let t=e.replace("%","");return parseFloat(t)/100}getVisibleOrNone(e,t=!1){return{display:e?t?"flex":"inherit":"none"}}stringToInteger(e){switch(e=_lodash.default.toUpper(e)){case"A":return 0;case"B":return 1;case"C":return 2;case"D":return 3;case"E":return 4;case"F":return 5;case"G":return 6;case"H":return 7;case"I":return 8;case"J":return 9;case"K":return 10;case"L":return 11;case"M":return 12;case"N":return 13;default:return 101}}integerToString(e){switch(e){case 0:return"A";case 1:return"B";case 2:return"C";case 3:return"D";case 4:return"E";case 5:return"F";case 6:return"G";case 7:return"H";case 8:return"I";case 9:return"J";case 10:return"K";case 11:return"L";case 12:return"M";case 13:return"N";default:return"Z"}}toObjectMap(e,...t){const r=[];for(const a of e){const e={};for(const r of t){const t=r.func?r.func:e=>e;e[r.to]=this.isUndefinedNullEmpty(r.from)||!_lodash.default.isObject(a)?t(a):t(a[r.from])}r.push(e)}return r}exeAll(e,...t){if(_lodash.default.isArray(e))for(const r of e)for(const e of t)e(r);else{if(!_lodash.default.isObject(e))throw new _exceptioner.default(9999,"7841212 type can't be array or object");for(const r in e)for(const a of t)e[r]=a(e[r])}return e}getObjectWhile(e,t,r=e=>!0){const a={};for(const n in e)r(e,t,n)&&(a[n]=e[n]);return a}getIntersectionObject(e,t){return this.getObjectWhile(e,t,(e,t,r)=>void 0!==t[r])}getDifferenceObject(e,t){return this.getObjectWhile(e,t,(e,t,r)=>void 0===t[r])}isObjectContainAndEqual(e,t){let r=!0;for(const a in e)if(void 0===t[a]||t[a]!==e[a]){r=!1;break}return r}getStringOfPop(e,t){if(!_lodash.default.isString(e))throw new _exceptioner.default(9999,"445115,type should be string but ==> "+typeof e);const r=e.split(t);return r.pop(),r.join(t)}getStringOfShift(e,t){if(!_lodash.default.isString(e))throw new _exceptioner.default(9999,"445116,type should be string but ==> "+typeof e);const r=e.split(t);return r.shift(),r.join(t)}toObjectWithAttributeKey(e,t){const r={};for(const a of e){const e=a[t];if(this.isUndefinedNullEmpty(e))throw new _exceptioner.default(9999,`48157232 pk can't be empty => '${e}'`);r[e]=a}return r}getObjectOfArraySpecifyAttr(e,t){return this.toObjectWithAttributeKey(e,t)}getStateOfStringContainsSign(e,...t){for(const r of t)if(this.has(e,r))return{exists:!0,sign:r};return{exists:!1}}constraintOfParam(e,t,...r){let a=!1;const n=!!_lodash.default.isEmpty(r)||this.and(...r.map(e=>e.logic));switch(t){case"array":_lodash.default.isArray(e)&&n&&(a=!0);break;case"object":_lodash.default.isObject(e)&&n&&(a=!0);break;case"string":_lodash.default.isString(e)&&n&&(a=!0);break;case"number":_lodash.default.isNumber(e)&&n&&(a=!0);break;case"other":if(n)return!0}const s=_lodash.default.isEmpty(r)?"":`, ${r.map(e=>e.message).join(" | ")}`;if(!1===a)throw new _exceptioner.default(9999,`7474423 type should be ${t} but get '${typeof t}' ${s} `)}getSliceArrayWithMutate(e,t){return _lodash.default.remove(e,(e,r)=>r<t)}getArrayOfInteraction(e,t){return e.filter(e=>!t.includes(e))}getArrayOfMoveToSpecificIndex(e,t,r){if(!Array.isArray(e))throw new Error("First argument must be an array.");const a=e.length;if(t<0||t>=a||r<0||r>=a)return console.warn("Invalid 'from' or 'to' index for getArrayOfMoveToSpecificIndexOptimized."),[...e];if(t===r)return[...e];const n=[...e],[s]=n.splice(t,1);return n.splice(r,0,s),n}getArrayOfMoveItemToSpecificIndex(e,t,r){const a=_lodash.default.indexOf(e,t);return this.getArrayOfMoveToSpecificIndex(e,a,r)}getArrayOfMoveSpecificItemToAside(e,t,r=!0){const a=_lodash.default.indexOf(e,t);return this.getArrayOfMoveSpecificIndexToAside(e,a,r)}getArrayOfMoveSpecificIndexToAside(e,t,r=!0){const a=_lodash.default.size(e)-1;return this.getArrayOfMoveToSpecificIndex(e,t,r?a:0)}getECPayCheckMacValue(e,t="5294y06JbISpM5x9",r="v77hoKGq4kWxNNIS"){const a=_lodash.default.cloneDeep(e);delete a.CheckMacValue;const n=Object.keys(a).sort((e,t)=>e>t?1:-1);let s="";for(const e of n)s+=`${e}=${a[e]}&`;return s=`HashKey=${t}&${s}HashIV=${r}`,s=encodeURIComponent(s).toLowerCase(),s=s.replace(/%20/g,"+").replace(/%2d/g,"-").replace(/%5f/g,"_").replace(/%2e/g,".").replace(/%21/g,"!").replace(/%2a/g,"*").replace(/%28/g,"(").replace(/%29/g,")").replace(/%20/g,"+"),_lodash.default.toUpper(_cryptoJs.default.SHA256(s).toString(_cryptoJs.default.enc.Hex))}getStringOfHandledHtml(e,t=e=>!0){const r=(0,_nodeHtmlParser.parse)(e);return t(r),r.toString()}getSpecifyObjectBy(e,t){for(const r of e)if(t(r))return r}validatePayloadObjectValid(e,t=[],r=this.getRandomHash(10)){if(this.isUndefinedNullEmpty(e))throw new _exceptioner.default(9999,`${r} content(pay-load) is undefined || empty`);for(const a of t)if(_lodash.default.isString(a)){if(this.isUndefinedNullEmpty(e[a]))throw new _exceptioner.default(9999,`${r} ATTRIBUTE:'${a}' is not Exist`)}else if(_lodash.default.isObject(a)){const t=this.getObjectKey(a);if(!this.getObjectValue(a)(e[t]))throw new _exceptioner.default(9999,`${r} ATTRIBUTE:'${t}' is not valid of custom rule`)}return!0}getArrayOfSummarizeBy(e,t,r){const a={};for(const n of e){const e=n[t];void 0!==a[e]?a[e]=a[e]+n[r]:a[e]=n[r]}const n=[];for(const e in a){const s={};s[t]=e,s[r]=a[e],n.push(s)}return n}getHeadStringSplitBy(e,t=this.getSeparatorOfUnique()){return _lodash.default.split(e,t).shift()}getTailStringSplitBy(e,t=this.getSeparatorOfUnique()){return _lodash.default.split(e,t).pop()}getSlicesByIndexes(e=[],t=[]){const r=[];return _lodash.default.each(t,(a,n,s)=>{if(_lodash.default.isEqual(n,t.length-1))return!1;const i=_lodash.default.slice(e,a,t[n+1]);r.push(i)}),r}findIndexes(e,t){const r=[];let a=!0,n=0;for(;a;)n=_lodash.default.findIndex(e,t,n+1),n>-1?r.push(n):a=!1;return r}isOverSpecificAge(e,t=18){return(0,_dayjs.default)().diff((0,_dayjs.default)(e),"years")>=t}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}isValidTaiwaneseID(e){if(!/^[A-Z][1-2]\d{8}$/.test(e))return!1;const t=[1,9,8,7,6,5,4,3,2,1];let r=10*(e.charCodeAt(0)-65)+parseInt(e.slice(1));for(let a=0;a<t.length;a++)r+=parseInt(e.charAt(a+1))*t[a];return r%10==0}validatePersonalInfoInput(e,t,r,a,n,s=12){return e.length<2?{valid:!1,message:"姓名至少要兩個字"}:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?/^[A-Z][1-2]\d{8}$/.test(r)?/^09\d{8}$/.test(a)?n&&""!==n?(0,_dayjs.default)().diff((0,_dayjs.default)(n),"years")<s?{valid:!1,message:`年齡不得小於 ${s} 歲`}:{valid:!0,message:"格式檢查通過"}:{valid:!1,message:"出生日期格式不正確"}:{valid:!1,message:"手機號碼格式不正確"}:{valid:!1,message:"身分證號碼格式不正確"}:{valid:!1,message:"電子郵件格式不正確"}}getStringOfFormatTimestampRange(e,t){const r=(0,_dayjs.default)(e),a=(0,_dayjs.default)(t),n=e=>e.format("YY/MM/DD");return r.year()===a.year()?`${n(r)} - ${a.format("MM/DD")}`:`${n(r)} - ${n(a)}`}getStringOfCalculateClassTime(e,t,r){const a=(0,_dayjs.default)(e),n=(0,_dayjs.default)(t).diff(a,"days")+1,s=Math.ceil(n/7)*r,i=Math.floor(s/60),o=s%60;return 0===o?`${i}小時`:`${i}小時${o}分鐘`}getNumberOfPeriodMinute(e,t){const r=(0,_dayjs.default)(e).format("HH:mm"),a=(0,_dayjs.default)(t).format("HH:mm"),n=(0,_dayjs.default)(r,"HH:mm"),s=(0,_dayjs.default)(a,"HH:mm");return _dayjs.default.duration(s.diff(n)).asMinutes()}getStringOfWeekTime(e,t,r){if(e<1||e>7)throw new Error("day 必須在 1 到 7 之間");const a=(0,_dayjs.default)(t).format("HH:mm"),n=(0,_dayjs.default)(r).format("HH:mm");return`${{1:"週一",2:"週二",3:"週三",4:"週四",5:"週五",6:"週六",7:"週日"}[e]} ${a}-${n}`}extractNumber(e){if(this.isUndefinedNullEmpty(e))return-1;const t=e.match(/\d+/);return t?Number(t[0]):-1}async fetchElementAttribute(e,t="innerText",r=""){return await e.evaluate(e=>e[t])}async fetchElementAttributes(e,t,r="",...a){const n=await e.$(t);if(!this.isUndefinedNullEmpty(n))try{return await n.evaluate((e,t)=>1===t.length?e[t.shift()]:{...t.map(t=>e[t])},a)}catch(e){return this.appendError(`1581532 ${t} fetch ${JSON.stringify(a)} fail, element is not found`),r}return r}async writeElementAttributes(e,t,...r){const a=await e.$(t);this.isUndefinedNullEmpty(a)?this.appendError(`1231232 ${t} fetch ${JSON.stringify(r)} fail, element is not found`):await a.evaluate((e,t)=>{t.map(t=>{const r=Object.entries(t),a=r[0][0],n=r[0][1];e[a]=n})},r)}getSliceArrayOfUnique(e){if(!Array.isArray(e)||0===e.length)return[];const t=e[0];if(_lodash.default.isObject(t)&&key){const t=new Map(e.map(e=>[e[key],e]));return Array.from(t.values())}return _lodash.default.isObject(t)?(console.warn("getSliceArrayOfUniqueOptimized: No key provided for object array, using potentially slow deep comparison."),_lodash.default.uniqWith(e,_lodash.default.isEqual)):Array.from(new Set(e))}getUniqueValuesBy(e,t="valueOfType"){return _lodash.default.uniq(e.map(e=>e[t]))}generateCombinations(...e){const t=e.map(e=>e.key),r=(_lodash.default.keyBy(e,"key"),e.map(e=>e.options.map(t=>({key:e.key,value:t.value,label:t.label})))),a=_lodash.default.reduce(r,(e,t)=>_lodash.default.flatMap(e,e=>t.map(t=>[...e,t])),[[]]).map(e=>{const t={},r=[],a=[];for(const{key:n,value:s,label:i}of e)t[n]=s,r.push(`${n}_${s}`),a.push(`${i}`);return{trait:t,id:r.join("_"),content:a.join("|")}});return _lodash.default.sortBy(a,e=>t.map(t=>e.trait[t]))}extractStaticSegments(e,t=[":"]){return e.trim().replace(/^\.?\/*|\/*$/g,"").split("/").filter(e=>e&&!t.some(t=>e.startsWith(t)))}mutateRemoveKeys(e,t){_lodash.default.forEach(e,(e,r)=>{const a=Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)));Object.keys(e).forEach(t=>delete e[t]),Object.assign(e,a)})}removeKeysFromArrayObjects(e,t){return _lodash.default.map(e,e=>Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))))}formatTextWithEllipsis(e,t){if(_lodash.default.size(e)<=t)return e;if(t<=6)return"";const r=t-6,a=Math.floor(r/2),n=r-a;return`${_lodash.default.truncate(e,{length:a,omission:""})}......${_lodash.default.takeRight(e,n).join("")}`}getObjectBy(e,t=e=>!0!==e.checked){return _lodash.default.fromPairs(_lodash.default.toPairs(e).filter(([e,r])=>t(r)))}mutateBy(e,t=e=>e){const r=_lodash.default.sortBy(e,t);e.splice(0,e.length,...r)}findUniqueStrings(...e){const t=_lodash.default.flatten(e),r=_lodash.default.countBy(t);return _lodash.default.chain(r).pickBy(e=>1===e).keys().compact().value()}getObjectOfSpecifyKey(e,t){const r={};return r[t]=e,r}findUniqueNonReferenceStrings(...e){if(0===e.length)return[];const[t,...r]=e,a=_lodash.default.flatten(r),n=_lodash.default.countBy(a);return _lodash.default.chain(n).pickBy((e,r)=>1===e&&!t.includes(r)).keys().compact().value()}getArrayOfFillMissingValues(e){const t=()=>_lodash.default.times(8,()=>_lodash.default.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")).join(""),r=new Set(e.map(e=>e.value).filter(Boolean));return e.map(e=>{if(_lodash.default.isEmpty(e.value)){let a;do{a=t()}while(r.has(a));return r.add(a),{...e,value:a}}return e})}isFirestoreAutoId(e){return _lodash.default.isString(e)&&20===e.length&&/^[A-Za-z0-9]{20}$/.test(e)}getAutoIdOfFirestore(){return this.getRandomHashV2(20)}getStringOfConvertTimeRange(e){const[t,r]=e.split("|"),a=t.split("(")[0],[n,s]=r.split("-"),i=e=>(0,_dayjs.default)(`${a} ${e}`,"YYYY/MM/DD HH:mm").format("YYYYMMDDHHmm");return`${i(n)}-${i(s)}`}getTSOfSpecificDate(e,{end:t=!1}={}){const r=(0,_dayjs.default)(e.split("(")[0],"YYYY/MM/DD"),a=t?r.endOf("day"):r.startOf("day");return Number(a.format("YYYYMMDDHHmmss"))}isHttpsURL(e){if(!_lodash.default.isString(e))return!1;try{const t=decodeURIComponent(e.trim());return"https:"===new URL(t).protocol}catch(e){return!1}}generateUniqueCodeMap(e,t=3){if(t<2)throw new Error("代碼長度最少必須為 2。");const r=new Set,a=new Set;return _lodash.default.transform(e,(e,n)=>{if(a.has(n))throw new Error(`23125453 Duplicate key detected: "${n}"`);a.add(n),e[n]=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",a=e+"0123456789";let n;do{n=e[Math.floor(52*Math.random())];for(let e=1;e<t;e++)n+=a[Math.floor(62*Math.random())]}while(r.has(n));return r.add(n),n})()},{})}getPriceOfPercentageBehavior(e,t,r=!1){const a=this.toPercentageDecimal(t);return this.getNumberOfMultiplyCeil(e,r?1-a:1+a)}getFeeOfDiscount(e,t){return Math.round(_lodash.default.multiply(e,this.toPercentageDecimal(t)))}mergeArrayByKey(e){if(!Array.isArray(e))return e;const t={};for(const r of e)if(_lodash.default.isPlainObject(r))for(const[e,a]of Object.entries(r))t[e]?_lodash.default.merge(t[e],a):t[e]=_lodash.default.cloneDeep(a);return e.length=0,Object.entries(t).forEach(([t,r])=>{e.push({[t]:r})}),e}getObjectOfStartEndDateTime(e){if(!e||"string"!=typeof e)return{startDate:"",startTime:"",endDate:"",endTime:""};const t=e.replace(/|/g," ").replace(/-/g,"-").replace(/\s+/g," ").trim(),r=/(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})\s*-\s*(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})/,a=/(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})\s*-\s*(\d{2}:\d{2})/;let n,s,i,o;if(r.test(t))[,n,s,i,o]=t.match(r);else{if(!a.test(t))return{startDate:"",startTime:"",endDate:"",endTime:""};[,n,s,o]=t.match(a),i=n}const l=new Date(`${n} ${s}`);if(new Date(`${i} ${o}`)<l)throw new Error(`End time cannot be earlier than start time: ${e}`);return{startDate:n,startTime:s,endDate:i,endTime:o}}getFilteredHeraPeriods(e,t){return _lodash.default.chain(e).filter(e=>e.idOfBooze!==t).uniqBy(e=>`${e.idOfBooze}_${e.idOfVariant}`).value()}checkPeriodConflict(e,t,r=1){const[a,n]=e.content.split("|"),s=a.split(" ")[0],[i,o]=n.split("-"),l=(0,_dayjs.default)(`${s} ${i}`,"YYYY/MM/DD HH:mm"),d=(0,_dayjs.default)(`${s} ${o}`,"YYYY/MM/DD HH:mm"),u=_lodash.default.filter(t,e=>{const[t,r]=e.period.split("-"),a=(0,_dayjs.default)(t,"YYYYMMDDHHmm"),n=(0,_dayjs.default)(r,"YYYYMMDDHHmm");return l.isBefore(n)&&d.isAfter(a)});return{conflict:u.length>=r,items:u}}}var _default=exports.default=Utiller;
|
package/package.json
CHANGED