befly 3.10.18 → 3.11.1
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/README.md +83 -307
- package/dist/befly.config.d.ts +7 -0
- package/{befly.config.ts → dist/befly.config.js} +11 -36
- package/dist/befly.js +15621 -0
- package/dist/befly.min.js +21 -0
- package/dist/checks/checkApi.d.ts +1 -0
- package/{checks/checkApi.ts → dist/checks/checkApi.js} +12 -30
- package/dist/checks/checkHook.d.ts +1 -0
- package/dist/checks/checkHook.js +86 -0
- package/dist/checks/checkMenu.d.ts +7 -0
- package/{checks/checkMenu.ts → dist/checks/checkMenu.js} +18 -53
- package/dist/checks/checkPlugin.d.ts +1 -0
- package/dist/checks/checkPlugin.js +86 -0
- package/dist/checks/checkTable.d.ts +6 -0
- package/{checks/checkTable.ts → dist/checks/checkTable.js} +17 -41
- package/dist/configs/presetFields.d.ts +4 -0
- package/{configs/presetFields.ts → dist/configs/presetFields.js} +1 -1
- package/dist/configs/presetRegexp.d.ts +145 -0
- package/{utils/regex.ts → dist/configs/presetRegexp.js} +8 -31
- package/dist/hooks/auth.d.ts +7 -0
- package/{hooks/auth.ts → dist/hooks/auth.js} +8 -10
- package/dist/hooks/cors.d.ts +11 -0
- package/{hooks/cors.ts → dist/hooks/cors.js} +5 -13
- package/dist/hooks/parser.d.ts +14 -0
- package/{hooks/parser.ts → dist/hooks/parser.js} +31 -45
- package/dist/hooks/permission.d.ts +14 -0
- package/{hooks/permission.ts → dist/hooks/permission.js} +16 -25
- package/dist/hooks/validator.d.ts +11 -0
- package/{hooks/validator.ts → dist/hooks/validator.js} +9 -14
- package/dist/index.d.ts +26 -0
- package/{main.ts → dist/index.js} +61 -100
- package/dist/lib/asyncContext.d.ts +21 -0
- package/dist/lib/asyncContext.js +27 -0
- package/dist/lib/cacheHelper.d.ts +95 -0
- package/{lib/cacheHelper.ts → dist/lib/cacheHelper.js} +45 -105
- package/dist/lib/cacheKeys.d.ts +23 -0
- package/{lib/cacheKeys.ts → dist/lib/cacheKeys.js} +5 -10
- package/dist/lib/cipher.d.ts +153 -0
- package/{lib/cipher.ts → dist/lib/cipher.js} +23 -44
- package/dist/lib/connect.d.ts +91 -0
- package/{lib/connect.ts → dist/lib/connect.js} +47 -88
- package/dist/lib/dbDialect.d.ts +87 -0
- package/{lib/dbDialect.ts → dist/lib/dbDialect.js} +32 -112
- package/dist/lib/dbHelper.d.ts +204 -0
- package/{lib/dbHelper.ts → dist/lib/dbHelper.js} +82 -241
- package/dist/lib/dbUtils.d.ts +68 -0
- package/{lib/dbUtils.ts → dist/lib/dbUtils.js} +51 -126
- package/dist/lib/jwt.d.ts +13 -0
- package/{lib/jwt.ts → dist/lib/jwt.js} +11 -32
- package/dist/lib/logger.d.ts +42 -0
- package/dist/lib/logger.js +1144 -0
- package/dist/lib/redisHelper.d.ts +185 -0
- package/{lib/redisHelper.ts → dist/lib/redisHelper.js} +97 -141
- package/dist/lib/sqlBuilder.d.ts +160 -0
- package/{lib/sqlBuilder.ts → dist/lib/sqlBuilder.js} +132 -278
- package/dist/lib/sqlCheck.d.ts +23 -0
- package/{lib/sqlCheck.ts → dist/lib/sqlCheck.js} +24 -41
- package/dist/lib/validator.d.ts +45 -0
- package/{lib/validator.ts → dist/lib/validator.js} +44 -61
- package/dist/loader/loadApis.d.ts +12 -0
- package/{loader/loadApis.ts → dist/loader/loadApis.js} +10 -20
- package/dist/loader/loadHooks.d.ts +7 -0
- package/dist/loader/loadHooks.js +35 -0
- package/dist/loader/loadPlugins.d.ts +8 -0
- package/{loader/loadPlugins.ts → dist/loader/loadPlugins.js} +14 -26
- package/dist/paths.d.ts +93 -0
- package/{paths.ts → dist/paths.js} +6 -19
- package/dist/plugins/cache.d.ts +16 -0
- package/{plugins/cache.ts → dist/plugins/cache.js} +7 -12
- package/dist/plugins/cipher.d.ts +12 -0
- package/{plugins/cipher.ts → dist/plugins/cipher.js} +4 -6
- package/dist/plugins/config.d.ts +12 -0
- package/dist/plugins/config.js +8 -0
- package/dist/plugins/db.d.ts +16 -0
- package/{plugins/db.ts → dist/plugins/db.js} +11 -17
- package/dist/plugins/jwt.d.ts +12 -0
- package/dist/plugins/jwt.js +12 -0
- package/dist/plugins/logger.d.ts +32 -0
- package/{plugins/logger.ts → dist/plugins/logger.js} +5 -8
- package/dist/plugins/redis.d.ts +16 -0
- package/{plugins/redis.ts → dist/plugins/redis.js} +9 -12
- package/dist/plugins/tool.d.ts +81 -0
- package/{plugins/tool.ts → dist/plugins/tool.js} +9 -30
- package/dist/router/api.d.ts +14 -0
- package/dist/router/api.js +107 -0
- package/dist/router/static.d.ts +9 -0
- package/{router/static.ts → dist/router/static.js} +20 -34
- package/dist/scripts/ensureDist.d.ts +1 -0
- package/dist/scripts/ensureDist.js +296 -0
- package/dist/sync/syncApi.d.ts +3 -0
- package/{sync/syncApi.ts → dist/sync/syncApi.js} +35 -55
- package/dist/sync/syncCache.d.ts +2 -0
- package/{sync/syncCache.ts → dist/sync/syncCache.js} +1 -6
- package/dist/sync/syncDev.d.ts +6 -0
- package/{sync/syncDev.ts → dist/sync/syncDev.js} +29 -62
- package/dist/sync/syncMenu.d.ts +14 -0
- package/{sync/syncMenu.ts → dist/sync/syncMenu.js} +65 -125
- package/dist/sync/syncTable.d.ts +151 -0
- package/{sync/syncTable.ts → dist/sync/syncTable.js} +172 -379
- package/{types → dist/types}/api.d.ts +12 -51
- package/dist/types/api.js +4 -0
- package/{types → dist/types}/befly.d.ts +32 -227
- package/dist/types/befly.js +4 -0
- package/{types → dist/types}/cache.d.ts +7 -15
- package/dist/types/cache.js +4 -0
- package/dist/types/cipher.d.ts +27 -0
- package/dist/types/cipher.js +7 -0
- package/{types → dist/types}/common.d.ts +8 -33
- package/dist/types/common.js +5 -0
- package/{types → dist/types}/context.d.ts +3 -5
- package/dist/types/context.js +4 -0
- package/{types → dist/types}/crypto.d.ts +0 -3
- package/dist/types/crypto.js +4 -0
- package/dist/types/database.d.ts +138 -0
- package/dist/types/database.js +4 -0
- package/dist/types/hook.d.ts +17 -0
- package/dist/types/hook.js +6 -0
- package/dist/types/jwt.d.ts +75 -0
- package/dist/types/jwt.js +4 -0
- package/dist/types/logger.d.ts +59 -0
- package/dist/types/logger.js +6 -0
- package/dist/types/plugin.d.ts +16 -0
- package/dist/types/plugin.js +6 -0
- package/dist/types/redis.d.ts +71 -0
- package/dist/types/redis.js +4 -0
- package/{types/roleApisCache.ts → dist/types/roleApisCache.d.ts} +0 -2
- package/dist/types/roleApisCache.js +8 -0
- package/dist/types/sync.d.ts +92 -0
- package/dist/types/sync.js +4 -0
- package/dist/types/table.d.ts +34 -0
- package/dist/types/table.js +4 -0
- package/dist/types/validate.d.ts +67 -0
- package/dist/types/validate.js +4 -0
- package/dist/utils/calcPerfTime.d.ts +4 -0
- package/{utils/calcPerfTime.ts → dist/utils/calcPerfTime.js} +3 -3
- package/dist/utils/convertBigIntFields.d.ts +11 -0
- package/{utils/convertBigIntFields.ts → dist/utils/convertBigIntFields.js} +5 -9
- package/dist/utils/cors.d.ts +8 -0
- package/{utils/cors.ts → dist/utils/cors.js} +1 -3
- package/dist/utils/disableMenusGlob.d.ts +13 -0
- package/{utils/disableMenusGlob.ts → dist/utils/disableMenusGlob.js} +9 -29
- package/dist/utils/fieldClear.d.ts +11 -0
- package/{utils/fieldClear.ts → dist/utils/fieldClear.js} +15 -33
- package/dist/utils/getClientIp.d.ts +6 -0
- package/{utils/getClientIp.ts → dist/utils/getClientIp.js} +1 -7
- package/dist/utils/importDefault.d.ts +1 -0
- package/dist/utils/importDefault.js +29 -0
- package/dist/utils/isDirentDirectory.d.ts +2 -0
- package/{utils/isDirentDirectory.ts → dist/utils/isDirentDirectory.js} +3 -8
- package/dist/utils/loadMenuConfigs.d.ts +29 -0
- package/{utils/loadMenuConfigs.ts → dist/utils/loadMenuConfigs.js} +66 -52
- package/dist/utils/mergeAndConcat.d.ts +7 -0
- package/dist/utils/mergeAndConcat.js +72 -0
- package/dist/utils/processAtSymbol.d.ts +4 -0
- package/{utils/processFields.ts → dist/utils/processAtSymbol.js} +5 -9
- package/dist/utils/processInfo.d.ts +24 -0
- package/{utils/process.ts → dist/utils/processInfo.js} +2 -18
- package/dist/utils/response.d.ts +20 -0
- package/{utils/response.ts → dist/utils/response.js} +28 -49
- package/dist/utils/scanAddons.d.ts +17 -0
- package/{utils/scanAddons.ts → dist/utils/scanAddons.js} +7 -41
- package/dist/utils/scanConfig.d.ts +26 -0
- package/{utils/scanConfig.ts → dist/utils/scanConfig.js} +28 -66
- package/dist/utils/scanCoreBuiltins.d.ts +3 -0
- package/dist/utils/scanCoreBuiltins.js +65 -0
- package/dist/utils/scanFiles.d.ts +30 -0
- package/{utils/scanFiles.ts → dist/utils/scanFiles.js} +44 -71
- package/dist/utils/scanSources.d.ts +10 -0
- package/dist/utils/scanSources.js +46 -0
- package/dist/utils/sortModules.d.ts +28 -0
- package/{utils/sortModules.ts → dist/utils/sortModules.js} +26 -66
- package/dist/utils/util.d.ts +84 -0
- package/dist/utils/util.js +262 -0
- package/package.json +26 -34
- package/.gitignore +0 -0
- package/bunfig.toml +0 -3
- package/checks/checkHook.ts +0 -48
- package/checks/checkPlugin.ts +0 -48
- package/configs/presetRegexp.ts +0 -225
- package/docs/README.md +0 -98
- package/docs/api/api.md +0 -1921
- package/docs/guide/examples.md +0 -926
- package/docs/guide/quickstart.md +0 -354
- package/docs/hooks/auth.md +0 -38
- package/docs/hooks/cors.md +0 -28
- package/docs/hooks/hook.md +0 -838
- package/docs/hooks/parser.md +0 -19
- package/docs/hooks/rateLimit.md +0 -47
- package/docs/infra/redis.md +0 -628
- package/docs/plugins/cipher.md +0 -61
- package/docs/plugins/database.md +0 -189
- package/docs/plugins/plugin.md +0 -986
- package/docs/reference/addon.md +0 -510
- package/docs/reference/config.md +0 -573
- package/docs/reference/logger.md +0 -495
- package/docs/reference/sync.md +0 -478
- package/docs/reference/table.md +0 -763
- package/docs/reference/validator.md +0 -620
- package/lib/asyncContext.ts +0 -43
- package/lib/logger.ts +0 -811
- package/loader/loadHooks.ts +0 -51
- package/plugins/config.ts +0 -13
- package/plugins/jwt.ts +0 -15
- package/router/api.ts +0 -130
- package/tsconfig.json +0 -8
- package/types/database.d.ts +0 -541
- package/types/hook.d.ts +0 -25
- package/types/jwt.d.ts +0 -118
- package/types/logger.d.ts +0 -65
- package/types/plugin.d.ts +0 -19
- package/types/redis.d.ts +0 -83
- package/types/sync.d.ts +0 -398
- package/types/table.d.ts +0 -216
- package/types/validate.d.ts +0 -69
- package/utils/arrayKeysToCamel.ts +0 -18
- package/utils/configTypes.ts +0 -3
- package/utils/genShortId.ts +0 -12
- package/utils/importDefault.ts +0 -21
- package/utils/keysToCamel.ts +0 -22
- package/utils/keysToSnake.ts +0 -22
- package/utils/pickFields.ts +0 -19
- package/utils/scanSources.ts +0 -64
- package/utils/sqlLog.ts +0 -37
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var aW=Object.create;var{getPrototypeOf:eW,defineProperty:Y1,getOwnPropertyNames:$G}=Object;var JG=Object.prototype.hasOwnProperty;var ZG=($,J,Z)=>{Z=$!=null?aW(eW($)):{};let X=J||!$||!$.__esModule?Y1(Z,"default",{value:$,enumerable:!0}):Z;for(let Y of $G($))if(!JG.call(X,Y))Y1(X,Y,{get:()=>$[Y],enumerable:!0});return X};var o=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var E$=($,J)=>()=>($&&(J=$($=0)),J);var K$=import.meta.require;function s($){if(typeof $!=="object"||$===null)return!1;let J=Object.getPrototypeOf($);return J===Object.prototype||J===null}function FJ($){if($===null||$===void 0)return!0;if(typeof $==="string")return $.trim().length===0;if(typeof $==="number")return $===0||Number.isNaN($);if(typeof $==="boolean")return $===!1;if(Array.isArray($))return $.length===0;if($ instanceof Map||$ instanceof Set)return $.size===0;if(s($))return Object.keys($).length===0;return!1}function W1($,J){if(typeof J!=="function")return;if(!s($))return;for(let Z of Object.keys($))J($[Z],Z)}function GG($){let J=String($).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").trim();if(J.length===0)return[];return J.split(/\s+/).filter((Z)=>Z.length>0)}function QG($){if($.length===0)return $;return $[0].toUpperCase()+$.slice(1)}function O$($){let J=GG($);if(J.length===0)return"";let Z=J[0].toLowerCase(),X=J.slice(1).map((Y)=>QG(Y.toLowerCase()));return[Z,...X].join("")}function zG($){return String($).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").trim()}function p($){let J=zG($);if(J.length===0)return"";return J.split(/\s+/).filter((Z)=>Z.length>0).map((Z)=>Z.toLowerCase()).join("_")}function wZ($,J){if(!J)return $;let Z=J.split("."),X=$;for(let Y of Z){if(X===null||X===void 0)return;if(typeof X!=="object")return;X=X[Y]}return X}function LZ($,J,Z){let X=J.split(".");for(let H of X)if(!H)return;let Y=$;for(let H=0;H<X.length;H++){let G=X[H];if(H===X.length-1){Y[G]=Z;return}let V=Y[G];if(!s(V))Y[G]={};Y=Y[G]}}function u($,J){if(!s($))return{};let Z=new Set(Array.isArray(J)?J:[]),X={};for(let[Y,H]of Object.entries($)){if(Z.has(Y))continue;X[Y]=H}return X}function Q1($,J){let Z={};if(!Array.isArray($)||typeof J!=="function")return Z;for(let X of $){let Y=J(X);if(typeof Y!=="string"||Y==="")continue;Z[Y]=X}return Z}function z1(){return Date.now().toString(36)+Math.random().toString(36).slice(2,7)}var CZ=($)=>{if(!$||!s($))return $;let J={};for(let[Z,X]of Object.entries($)){let Y=O$(Z);J[Y]=X}return J},G1=($)=>{if(!$||!s($))return $;let J={};for(let[Z,X]of Object.entries($)){let Y=p(Z);J[Y]=X}return J},SZ=($)=>{if(!$||!Array.isArray($))return $;return $.map((J)=>CZ(J))},AJ=($,J)=>{if(!$||!s($)&&!Array.isArray($))return{};let Z={};for(let X of J)if(X in $)Z[X]=$[X];return Z};import{AsyncLocalStorage as _G}from"async_hooks";function _1($,J){return NZ.run($,J)}function F1(){let $=NZ.getStore();if(!$)return null;return $}function A1($,J,Z,X){let Y=NZ.getStore();if(!Y)return;Y.userId=$,Y.roleCode=J,Y.nickname=Z,Y.roleType=X}var NZ;var RJ=E$(()=>{NZ=new _G});import{createWriteStream as R1,existsSync as FG,mkdirSync as AG}from"fs";import{readdir as RG,stat as I1,unlink as MG}from"fs/promises";import{hostname as IG}from"os";import{isAbsolute as qG,join as q1,resolve as PG}from"path";function jG($){return String($).replace(BG,"\\$&")}function D1(){if(M1)return;M1=!0;let $=(J,Z)=>{try{if(typeof process.listenerCount==="function"&&process.listenerCount(J)>0)return}catch{}try{process.once(J,()=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0;try{process.exit(Z)}catch{}},2000);cZ().catch(()=>{return}).finally(()=>{if(X)return;X=!0,clearTimeout(Y);try{process.exit(Z)}catch{}})})}catch{}};$("SIGINT",130),$("SIGTERM",143)}function EG($){let J=$.getFullYear(),Z=$.getMonth()+1,X=$.getDate(),Y=Z<10?`0${Z}`:String(Z),H=X<10?`0${X}`:String(X);return`${J}-${Y}-${H}`}function TG(){return m0.debug===1?"debug":"info"}function gZ($,J){return q$[J]>=q$[$]}function v$($){if(xZ)return;xZ=!0;try{process.stderr.write(`${$}
|
|
3
|
+
`)}catch{}}function k1($,J){let Z=[],X=0;while($.length>0){let Y=$[0],H=Buffer.byteLength(Y);if(Z.length>0&&X+H>J)break;Z.push(Y),X+=H,$.shift()}return{chunk:Z.join(""),bytes:X}}class x1{kind;minLevel;pending;pendingBytes;scheduled;flushing;maxBufferBytes;flushDelayMs;maxBatchBytes;constructor($){this.kind=$.kind,this.minLevel=$.minLevel,this.pending=[],this.pendingBytes=0,this.scheduled=!1,this.flushing=!1,this.maxBufferBytes=T1,this.flushDelayMs=N1,this.maxBatchBytes=v1}enqueue($,J){if(!gZ(this.minLevel,$))return;let Z=Buffer.byteLength(J);if(this.pendingBytes+Z>this.maxBufferBytes){if(q$[$]<q$.warn)return}this.pending.push(J),this.pendingBytes+=Z,this.scheduleFlush()}async flushNow(){await this.flush()}async shutdown(){await this.flush()}scheduleFlush(){if(this.scheduled)return;this.scheduled=!0,setTimeout(()=>{this.flush()},this.flushDelayMs)}getStream(){return this.kind==="stderr"?process.stderr:process.stdout}async flush(){if(this.flushing)return;this.scheduled=!1,this.flushing=!0;try{let $=this.getStream();while(this.pending.length>0){let Z=k1(this.pending,this.maxBatchBytes).chunk,X=Buffer.byteLength(Z);if(this.pendingBytes=this.pendingBytes-X,!$.write(Z))await new Promise((H)=>{$.once("drain",()=>H())})}}catch($){v$(`[Logger] stream sink error: ${$?.message||$}`)}finally{if(this.flushing=!1,this.pending.length>0)this.scheduleFlush()}}}class bZ{prefix;minLevel;maxFileBytes;pending;pendingBytes;scheduled;flushing;maxBufferBytes;flushDelayMs;maxBatchBytes;stream;streamDate;streamIndex;streamSizeBytes;disabled;constructor($){this.prefix=$.prefix,this.minLevel=$.minLevel,this.maxFileBytes=$.maxFileBytes,this.pending=[],this.pendingBytes=0,this.scheduled=!1,this.flushing=!1,this.maxBufferBytes=T1,this.flushDelayMs=N1,this.maxBatchBytes=v1,this.stream=null,this.streamDate="",this.streamIndex=0,this.streamSizeBytes=0,this.disabled=!1}enqueue($,J){if(this.disabled)return;if(!gZ(this.minLevel,$))return;let Z=Buffer.byteLength(J);if(this.pendingBytes+Z>this.maxBufferBytes){if(q$[$]<q$.warn)return}this.pending.push(J),this.pendingBytes+=Z,this.scheduleFlush()}async flushNow(){await this.flush()}async shutdown(){await this.flush(),await this.closeStream()}scheduleFlush(){if(this.scheduled)return;this.scheduled=!0,setTimeout(()=>{this.flush()},this.flushDelayMs)}async closeStream(){if(!this.stream)return;let $=this.stream;this.stream=null,await new Promise((J)=>{try{$.end(()=>J())}catch{J()}})}getFilePath($,J){let Z=J>0?`.${J}`:"",X=`${this.prefix}.${$}${Z}.log`;return q1(pZ(),X)}async ensureStreamReady($){let J=EG(new Date);if(this.stream&&this.streamDate&&J!==this.streamDate)await this.closeStream(),this.streamDate="",this.streamIndex=0,this.streamSizeBytes=0;if(!this.stream){let Z=this.getFilePath(J,0),X=0;try{let Y=await I1(Z);X=typeof Y.size==="number"?Y.size:0}catch{X=0}this.streamDate=J,this.streamIndex=0,this.streamSizeBytes=X;try{this.stream=R1(Z,{flags:"a"}),this.stream.on("error",(Y)=>{v$(`[Logger] file sink error (${this.prefix}): ${Y?.message||Y}`),this.disabled=!0,this.closeStream()})}catch(Y){v$(`[Logger] createWriteStream failed (${this.prefix}): ${Y?.message||Y}`),this.disabled=!0;return}}if(this.stream&&this.maxFileBytes>0&&this.streamSizeBytes+$>this.maxFileBytes){await this.closeStream(),this.streamIndex=this.streamIndex+1;let Z=this.getFilePath(J,this.streamIndex);this.streamDate=J,this.streamSizeBytes=0;try{this.stream=R1(Z,{flags:"a"}),this.stream.on("error",(X)=>{v$(`[Logger] file sink error (${this.prefix}): ${X?.message||X}`),this.disabled=!0,this.closeStream()})}catch(X){v$(`[Logger] createWriteStream failed (${this.prefix}): ${X?.message||X}`),this.disabled=!0;return}}}async flush(){if(this.disabled){this.pending=[],this.pendingBytes=0;return}if(this.flushing)return;this.scheduled=!1,this.flushing=!0;try{while(this.pending.length>0&&!this.disabled){let J=k1(this.pending,this.maxBatchBytes).chunk,Z=Buffer.byteLength(J);if(this.pendingBytes=this.pendingBytes-Z,await this.ensureStreamReady(Z),!this.stream)break;if(!this.stream.write(J))await new Promise((Y)=>{this.stream.once("drain",()=>Y())});this.streamSizeBytes=this.streamSizeBytes+Z}}catch($){v$(`[Logger] file sink flush error (${this.prefix}): ${$?.message||$}`)}finally{if(this.flushing=!1,this.pending.length>0&&!this.disabled)this.scheduleFlush()}}}async function NG(){if(F$)return;let $=[];if(J$)$.push({flush:()=>J$?J$.flushNow():Promise.resolve()});if(Z$)$.push({flush:()=>Z$?Z$.flushNow():Promise.resolve()});if(X$)$.push({flush:()=>X$?X$.flushNow():Promise.resolve()});for(let J of $)try{await J.flush()}catch{}}async function cZ(){if(F$)return;let $=[];if(J$)$.push({shutdown:()=>J$?J$.shutdown():Promise.resolve()});if(Z$)$.push({shutdown:()=>Z$?Z$.shutdown():Promise.resolve()});if(X$)$.push({shutdown:()=>X$?X$.shutdown():Promise.resolve()});for(let J of $)try{await J.shutdown()}catch{}J$=null,Z$=null,X$=null,D$=null,k$=null}function a$($,J,Z,X){if(typeof $!=="number")return J;if(!Number.isFinite($))return J;let Y=Math.floor($);if(Y<Z)return J;if(Y>X)return X;return Y}function pZ(){let $=m0.dir||"./logs";if(qG($))return $;return PG(CG,$)}function y1(){if(fZ)return;fZ=!0;let $=pZ();try{if(!FG($))AG($,{recursive:!0})}catch(J){throw Error(`\u521B\u5EFA logs \u76EE\u5F55\u5931\u8D25: ${$}. ${J?.message||J}`)}}async function f1(){if(yZ)return;yZ=!0;let $=pZ(),Z=Date.now()-SG;try{let X=await RG($,{withFileTypes:!0});for(let Y of X){if(!Y.isFile())continue;let H=Y.name;if(!(H.startsWith("app.")||H.startsWith("error.")))continue;let U=q1($,H),V;try{V=await I1(U)}catch{continue}let K=typeof V.mtimeMs==="number"?V.mtimeMs:0;if(K>0&&K<Z)try{await MG(U)}catch{}}}catch{}}function vG($){cZ(),m0=Object.assign({},m0,$),D$=null,k$=null,yZ=!1,fZ=!1,xZ=!1,J$=null,Z$=null,X$=null,w1=a$(m0.sanitizeDepth,j1,1,10),kZ=a$(m0.sanitizeNodes,S1,50,20000),CJ=a$(m0.sanitizeObjectKeys,C1,10,5000),DZ=a$(m0.maxStringLen,P1,20,200000),jJ=a$(m0.maxArrayItems,B1,10,5000);let J=Array.isArray(m0.excludeFields)?m0.excludeFields:[],Z=[];for(let H of wG){let G=String(H).trim();if(G.length>0)Z.push(G.toLowerCase())}for(let H of J){let G=String(H).trim();if(G.length>0)Z.push(G.toLowerCase())}let X=new Set,Y=[];for(let H of Z){if(!H.includes("*")){X.add(H);continue}let G=H.replace(/\*+/g,"").trim();if(!G)continue;Y.push(G)}if(L1=X,E1=Y,Y.length>0){let H=Y.map((G)=>jG(G)).filter((G)=>G.length>0);if(H.length>0)e$=new RegExp(H.join("|"));else e$=null}else e$=null}function DG($){F$=$}function MJ(){if(F$)return F$;if(D$)return D$;y1(),D1(),f1();let $=TG(),J=(typeof m0.maxSize==="number"&&m0.maxSize>0?m0.maxSize:10)*1024*1024;if(!J$)J$=new bZ({prefix:"app",minLevel:$,maxFileBytes:J});if(m0.console===1&&!X$)X$=new x1({kind:"stdout",minLevel:$});return D$=h1({kind:"app",minLevel:$,fileSink:J$,consoleSink:m0.console===1?X$:null}),D$}function kG(){if(F$)return F$;if(k$)return k$;y1(),D1(),f1();let $=(typeof m0.maxSize==="number"&&m0.maxSize>0?m0.maxSize:10)*1024*1024;if(!Z$)Z$=new bZ({prefix:"error",minLevel:"error",maxFileBytes:$});return k$=h1({kind:"error",minLevel:"error",fileSink:Z$,consoleSink:null}),k$}function N$($){if(!$||$.length===0)return"";let J=[];for(let Z of $){if(Z===null){J.push("null");continue}if(Z===void 0){J.push("undefined");continue}if(typeof Z==="string"){J.push(Z);continue}if(typeof Z==="number"||typeof Z==="boolean"||typeof Z==="bigint"){J.push(String(Z));continue}if(Z instanceof Error){J.push(Z.stack||Z.message||Z.name);continue}if(s(Z)||Array.isArray(Z)){try{J.push(JSON.stringify(Z))}catch{J.push("[Unserializable]")}continue}try{J.push(String(Z))}catch{J.push("[Unknown]")}}return J.join(" ")}function xG($,J){let Z=Date.now(),X={level:q$[$],time:Z,pid:process.pid,hostname:LG};if(!J||J.length===0)return X.msg="",`${JSON.stringify(X)}
|
|
4
|
+
`;let Y=J[0],H=J.length>1?J[1]:void 0;if(s(Y)){for(let[G,U]of Object.entries(Y))X[G]=U;if(typeof H==="string"){let G=N$(J.slice(2));X.msg=G?`${H} ${G}`:H}else{let G=N$(J.slice(1));X.msg=G}return`${IJ(X)}
|
|
5
|
+
`}if(Y instanceof Error){if(X.err=hZ(Y,{}),typeof H==="string"){let G=N$(J.slice(2));X.msg=G?`${H} ${G}`:H}else X.msg=N$(J.slice(1));return`${IJ(X)}
|
|
6
|
+
`}if(typeof Y==="string"){let G=N$(J.slice(1));return X.msg=G?`${Y} ${G}`:Y,`${IJ(X)}
|
|
7
|
+
`}return X.msg=N$(J),`${IJ(X)}
|
|
8
|
+
`}function IJ($){try{return JSON.stringify($)}catch{try{return JSON.stringify({level:$.level,time:$.time,pid:$.pid,hostname:$.hostname,msg:"[Unserializable log record]"})}catch{return'{"msg":"[Unserializable log record]"}'}}}function h1($){let J=$.minLevel,Z=(X,Y)=>{if(!gZ(J,X))return;let H=xG(X,Y);if($.fileSink.enqueue(X,H),$.consoleSink)$.consoleSink.enqueue(X,H)};return{info(...X){Z("info",X)},warn(...X){Z("warn",X)},error(...X){Z("error",X)},debug(...X){Z("debug",X)}}}function $J($,J){if($.length<=DZ)return $;return $.slice(0,DZ)}function uZ($){let J=String($).toLowerCase();if(L1.has(J))return!0;if(e$)return e$.test(J);for(let Z of E1)if(J.includes(Z))return!0;return!1}function yG($,J,Z){if(typeof $==="string")return $;if($ instanceof Error){let X=$.name||"Error",Y=$.message||"",H=typeof $.stack==="string"?$.stack:"",G={name:X,message:Y,stack:H};try{return JSON.stringify(G)}catch{return`${X}: ${Y}`}}if($&&typeof $==="object"){if(J.has($))return"[Circular]"}try{let X=J;return JSON.stringify($,(H,G)=>{if(H&&uZ(H))return"[MASKED]";if(G&&typeof G==="object"){if(X.has(G))return"[Circular]";X.add(G)}return G})}catch{try{return String($)}catch{return"[Unserializable]"}}}function hZ($,J){let Z={name:$.name||"Error",message:$J($.message||"",J)};if(typeof $.stack==="string")Z.stack=$J($.stack,J);return Z}function qJ($,J,Z){let X=yG($,J,Z);return $J(X,Z)}function fG($,J,Z){if($===null||$===void 0)return $;if(typeof $==="string")return $J($,Z);if(typeof $==="number")return $;if(typeof $==="boolean")return $;if(typeof $==="bigint")return $;if($ instanceof Error)return hZ($,Z);let X=Array.isArray($),Y=s($);if(!X&&!Y)return qJ($,J,Z);if(J.has($))return"[Circular]";J.add($);let H=X?[]:{},G=[{src:$,dst:H,depth:1}],U=0,V=(K,F,A,j)=>{if(A===null||A===void 0){K[F]=A;return}if(typeof A==="string"){K[F]=$J(A,Z);return}if(typeof A==="number"||typeof A==="boolean"||typeof A==="bigint"){K[F]=A;return}if(A instanceof Error){K[F]=hZ(A,Z);return}let C=Array.isArray(A),w=s(A);if(!C&&!w){K[F]=qJ(A,J,Z);return}if(j>=w1){K[F]=qJ(A,J,Z);return}if(U>=kZ){K[F]=qJ(A,J,Z);return}if(J.has(A)){K[F]="[Circular]";return}J.add(A);let E=C?[]:{};K[F]=E,G.push({src:A,dst:E,depth:j+1})};while(G.length>0){let K=G.pop();if(U=U+1,U>kZ)break;if(Array.isArray(K.src)){let F=K.src,A=F.length,j=A>jJ?jJ:A;for(let C=0;C<j;C++)V(K.dst,C,F[C],K.depth);if(A>jJ);continue}if(s(K.src)){let F=Object.entries(K.src),A=F.length,j=A>CJ?CJ:A;for(let C=0;C<j;C++){let w=F[C][0],E=F[C][1];if(uZ(w)){K.dst[w]="[MASKED]";continue}V(K.dst,w,E,K.depth)}if(A>CJ);continue}}return H}function hG($,J){return fG($,J,{})}function PJ($){let J=new WeakSet,Z={};for(let[X,Y]of Object.entries($)){if(uZ(X)){Z[X]="[MASKED]";continue}Z[X]=hG(Y,J)}return Z}function gG(){let $=F1();if(!$)return null;let J=Date.now()-$.now,Z={requestId:$.requestId,method:$.method,route:$.route,ip:$.ip,now:$.now,durationSinceNowMs:J};return Z.userId=$.userId,Z.roleCode=$.roleCode,Z.nickname=$.nickname,Z.roleType=$.roleType,Z}function vZ($,J){let Z={};for(let[Y,H]of Object.entries($))Z[Y]=H;let X=["requestId","method","route","ip","now","durationSinceNowMs","userId","roleCode","nickname","roleType"];for(let Y of X)if(Z[Y]===void 0)Z[Y]=J[Y];return Z}function bG($){let J=gG();if(!J)return $;if($.length===0)return $;let Z=$[0],X=$.length>1?$[1]:void 0;if(typeof Z==="string"&&X instanceof Error)return[vZ({err:X},J),Z,...$.slice(2)];if(Z instanceof Error){let Y=typeof X==="string"?X:void 0,G=vZ({err:Z},J);if(Y)return[G,Y,...$.slice(2)];return[G,...$.slice(1)]}if(typeof Z==="string")return[J,...$];if(s(Z))return[vZ(Z,J),...$.slice(1)];return $}function BJ($){return bG($)}var BG,CG,P1=100,B1=100,DZ,jJ,j1=3,C1=100,S1=500,w1,CJ,kZ,SG=31536000000,wG,L1,E1,e$=null,LG,q$,T1=10485760,N1=10,v1=65536,D$=null,k$=null,F$=null,J$=null,Z$=null,X$=null,xZ=!1,yZ=!1,fZ=!1,M1=!1,m0,P;var a=E$(()=>{RJ();BG=/[\\^$.*+?()[\]{}|]/g;CG=process.cwd(),DZ=P1,jJ=B1,w1=j1,CJ=C1,kZ=S1,wG=["*password*","pass","pwd","*token*","access_token","refresh_token","accessToken","refreshToken","authorization","cookie","set-cookie","*secret*","apiKey","api_key","privateKey","private_key"],L1=new Set,E1=[],LG=(()=>{try{return IG()}catch{return"unknown"}})(),q$={debug:20,info:30,warn:40,error:50},m0={debug:0,dir:"./logs",console:1,maxSize:10};P={info(...$){if($.length===0)return;let J=MJ(),Z=BJ($);if(Z.length===0)return;if(Z.length>0&&s(Z[0]))Z[0]=PJ(Z[0]);return J.info.apply(J,Z)},warn(...$){if($.length===0)return;let J=MJ(),Z=BJ($);if(Z.length===0)return;if(Z.length>0&&s(Z[0]))Z[0]=PJ(Z[0]);return J.warn.apply(J,Z)},error(...$){if($.length===0)return;let J=MJ(),Z=BJ($);if(Z.length===0)return;if(Z.length>0&&s(Z[0]))Z[0]=PJ(Z[0]);let X=J.error.apply(J,Z);if(F$)return X;let Y=kG();return Y.error.apply(Y,Z),X},debug(...$){if($.length===0)return;let J=MJ(),Z=BJ($);if(Z.length===0)return;if(Z.length>0&&s(Z[0]))Z[0]=PJ(Z[0]);return J.debug.apply(J,Z)},async flush(){await NG()},configure:vG,setMock:DG,shutdown:cZ}});function ZJ($=""){if(!$)return $;return $.replace(/\\/g,"/").replace(cG,(J)=>J.toUpperCase())}function nG(){if(typeof process<"u"&&typeof process.cwd==="function")return process.cwd().replace(/\\/g,"/");return"/"}function mZ($,J){let Z="",X=0,Y=-1,H=0,G=null;for(let U=0;U<=$.length;++U){if(U<$.length)G=$[U];else if(G==="/")break;else G="/";if(G==="/"){if(Y===U-1||H===1);else if(H===2){if(Z.length<2||X!==2||Z[Z.length-1]!=="."||Z[Z.length-2]!=="."){if(Z.length>2){let V=Z.lastIndexOf("/");if(V===-1)Z="",X=0;else Z=Z.slice(0,V),X=Z.length-1-Z.lastIndexOf("/");Y=U,H=0;continue}else if(Z.length>0){Z="",X=0,Y=U,H=0;continue}}if(J)Z+=Z.length>0?"/..":"..",X=2}else{if(Z.length>0)Z+=`/${$.slice(Y+1,U)}`;else Z=$.slice(Y+1,U);X=U-Y-1}Y=U,H=0}else if(G==="."&&H!==-1)++H;else H=-1}return Z}var cG,pG,uG,p1,c1,mG,dG,P$=function($){if($.length===0)return".";$=ZJ($);let J=$.match(pG),Z=x$($),X=$[$.length-1]==="/";if($=mZ($,!Z),$.length===0){if(Z)return"/";return X?"./":"."}if(X)$+="/";if(p1.test($))$+="/";if(J){if(!Z)return`//./${$}`;return`//${$}`}return Z&&!x$($)?`/${$}`:$},n=function(...$){let J="";for(let Z of $){if(!Z)continue;if(J.length>0){let X=J[J.length-1]==="/",Y=Z[0]==="/";if(X&&Y)J+=Z.slice(1);else J+=X||Y?Z:`/${Z}`}else J+=Z}return P$(J)},JJ=function(...$){$=$.map((X)=>ZJ(X));let J="",Z=!1;for(let X=$.length-1;X>=-1&&!Z;X--){let Y=X>=0?$[X]:nG();if(!Y||Y.length===0)continue;J=`${Y}/${J}`,Z=x$(Y)}if(J=mZ(J,!Z),Z&&!x$(J))return`/${J}`;return J.length>0?J:"."},x$=function($){return uG.test($)},u1=function($){if($==="..")return"";let J=mG.exec(ZJ($));return J&&J[1]||""},dZ=function($,J){let Z=JJ($).replace(c1,"$1").split("/"),X=JJ(J).replace(c1,"$1").split("/");if(X[0][1]===":"&&Z[0][1]===":"&&Z[0]!==X[0])return X.join("/");let Y=[...Z];for(let H of Y){if(X[0]!==H)break;Z.shift(),X.shift()}return[...Z.map(()=>".."),...X].join("/")},SJ=function($){let J=ZJ($).replace(/\/$/,"").split("/").slice(0,-1);if(J.length===1&&p1.test(J[0]))J[0]+="/";return J.join("/")||(x$($)?"/":".")},m1=function($,J){let Z=ZJ($).split("/"),X="";for(let Y=Z.length-1;Y>=0;Y--){let H=Z[Y];if(H){X=H;break}}return J&&X.endsWith(J)?X.slice(0,-J.length):X},XJ=function($){let J=dG.exec($)?.[0]?.replace(/\\/g,"/")||"",Z=m1($),X=u1(Z);return{root:J,dir:SJ($),base:Z,ext:X,name:Z.slice(0,Z.length-X.length)}};var d1=E$(()=>{cG=/^[A-Za-z]:\//;pG=/^[/\\]{2}/,uG=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,p1=/^[A-Za-z]:$/,c1=/^\/([A-Za-z]:)?$/,mG=/.(\.[^./]+|\.)$/,dG=/^[/\\]|^[a-zA-Z]:[/\\]/});var A$=E$(()=>{d1()});import{statSync as oG}from"fs";var wJ=($,J)=>{if(J.isDirectory())return!0;if(!J.isSymbolicLink())return!1;try{return oG(n($,J.name)).isDirectory()}catch{return!1}};var nZ=E$(()=>{A$()});import{existsSync as YJ}from"fs";import{readdir as sG,readFile as n1}from"fs/promises";function lG($){return String($).replace(/_\d+$/,"")}function rG($){let J=/<script\b[^>]*\bsetup\b[^>]*>/i.exec($);if(!J)return null;let Z=J.index+J[0].length,X=$.indexOf("</script>",Z);if(X<0)return null;return $.slice(Z,X)}function iG($){let J=$.match(/definePage\s*\([\s\S]*?meta\s*:\s*\{[\s\S]*?title\s*:\s*(["'`])([^"'`]+)\1/);if(!J)return null;let Z=$.match(/definePage\s*\([\s\S]*?meta\s*:\s*\{[\s\S]*?order\s*:\s*(\d+)/);return{title:J[2],order:Z?Number(Z[1]):void 0}}async function o1($,J,Z=""){if(!YJ($))return[];let X=[],Y=await sG($,{withFileTypes:!0});for(let H of Y){if(!wJ($,H)||H.name==="components")continue;let G=n($,H.name),U=n(G,"index.vue");if(!YJ(U))continue;let V=null;try{let w=await n1(U,"utf-8"),E=rG(w);if(!E){P.warn({path:U},"index.vue \u7F3A\u5C11 <script setup>\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65");continue}if(V=iG(E),!V?.title){P.warn({path:U},"index.vue \u672A\u58F0\u660E definePage({ meta: { title, order? } })\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65");continue}}catch(w){P.warn({err:w,path:U},"\u8BFB\u53D6 index.vue \u5931\u8D25");continue}if(!V?.title)continue;let K=lG(H.name),F;if(K==="index")F=Z;else F=Z?`${Z}/${K}`:`/${K}`;let A=J?F?`${J}${F}`:J:F||"/",j={name:V.title,path:A,sort:V.order??999999},C=await o1(G,J,F);if(C.length>0)j.children=C;X.push(j)}return X.sort((H,G)=>(H.sort??999999)-(G.sort??999999)),X}function s1($){let J=$.split("/").filter((Z)=>!!Z);if(J.length<=1)return"";return`/${J.slice(0,-1).join("/")}`}async function l1($){let J=[];for(let X of $){let Y=n(X.fullPath,"adminViews"),H=n(X.fullPath,"views","admin"),G=YJ(Y)?Y:YJ(H)?H:null;if(!G)continue;try{let U=`/${X.source}/${X.name}`,V=await o1(G,U);if(V.length>0)for(let K of V)J.push(K)}catch(U){P.warn({err:U,addon:X.name,addonSource:X.source,dir:G},"\u626B\u63CF addon views \u76EE\u5F55\u5931\u8D25")}}let Z=n(process.cwd(),"menus.json");if(YJ(Z))try{let X=await n1(Z,"utf-8"),Y=JSON.parse(X);if(Array.isArray(Y)&&Y.length>0)for(let H of Y)J.push(H)}catch(X){P.warn({err:X},"\u8BFB\u53D6\u9879\u76EE menus.json \u5931\u8D25")}return J}var oZ=E$(()=>{A$();a();nZ()});var p$=o((U7,JH)=>{var $H={invalidType:"FAST_JWT_INVALID_TYPE",invalidOption:"FAST_JWT_INVALID_OPTION",invalidAlgorithm:"FAST_JWT_INVALID_ALGORITHM",invalidClaimType:"FAST_JWT_INVALID_CLAIM_TYPE",invalidClaimValue:"FAST_JWT_INVALID_CLAIM_VALUE",invalidKey:"FAST_JWT_INVALID_KEY",invalidSignature:"FAST_JWT_INVALID_SIGNATURE",invalidPayload:"FAST_JWT_INVALID_PAYLOAD",malformed:"FAST_JWT_MALFORMED",inactive:"FAST_JWT_INACTIVE",expired:"FAST_JWT_EXPIRED",missingKey:"FAST_JWT_MISSING_KEY",keyFetchingError:"FAST_JWT_KEY_FETCHING_ERROR",signError:"FAST_JWT_SIGN_ERROR",verifyError:"FAST_JWT_VERIFY_ERROR",missingRequiredClaim:"FAST_JWT_MISSING_REQUIRED_CLAIM",missingSignature:"FAST_JWT_MISSING_SIGNATURE"};class c$ extends Error{constructor($,J,Z){super(J);if(Error.captureStackTrace(this,this.constructor),this.code=$,Z)for(let X in Z)this[X]=Z[X]}}c$.codes=$H;c$.wrap=function($,J,Z){if($ instanceof c$)return $;return new c$(J,Z,{originalError:$})};JH.exports={TokenError:c$,TOKEN_ERROR_CODES:$H}});var zX=o((V7,ZH)=>{var{TokenError:W$}=p$();function iQ({complete:$,checkTyp:J},Z){if(Z instanceof Buffer)Z=Z.toString("utf-8");else if(typeof Z!=="string")throw new W$(W$.codes.invalidType,"The token must be a string or a buffer.");let X=Z.indexOf("."),Y=Z.lastIndexOf(".");if(X===-1||X>=Y)throw new W$(W$.codes.malformed,"The token is malformed.");let H=!1;try{let G=JSON.parse(Buffer.from(Z.slice(0,X),"base64").toString("utf-8"));if(J&&G.typ!==J)throw new W$(W$.codes.invalidType,`The type must be "${J}".`,{header:G});H=!0;let U=Buffer.from(Z.slice(X+1,Y),"base64").toString("utf-8");if(U=JSON.parse(U),!U||typeof U!=="object")throw new W$(W$.codes.invalidPayload,"The payload must be an object",{payload:U});return $?{header:G,payload:U,signature:Z.slice(Y+1),input:Z.slice(0,Y)}:U}catch(G){throw W$.wrap(G,W$.codes.malformed,`The token ${H?"payload":"header"} is not a valid base64url serialized JSON.`)}}ZH.exports=function(J={}){let Z=J.complete||!1,X=J.checkTyp;return iQ.bind(null,{complete:Z,checkTyp:X})}});var YH=o((K7,XH)=>{function G$($){if(typeof $!=="function")throw Error("obliterator/iterator: expecting a function!");this.next=$}if(typeof Symbol<"u")G$.prototype[Symbol.iterator]=function(){return this};G$.of=function(){var $=arguments,J=$.length,Z=0;return new G$(function(){if(Z>=J)return{done:!0};return{done:!1,value:$[Z++]}})};G$.empty=function(){var $=new G$(function(){return{done:!0}});return $};G$.fromSequence=function($){var J=0,Z=$.length;return new G$(function(){if(J>=Z)return{done:!0};return{done:!1,value:$[J++]}})};G$.is=function($){if($ instanceof G$)return!0;return typeof $==="object"&&$!==null&&typeof $.next==="function"};XH.exports=G$});var HH=o((tQ)=>{tQ.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<"u";tQ.SYMBOL_SUPPORT=typeof Symbol<"u"});var UX=o((_7,GH)=>{var WH=HH(),$6=WH.ARRAY_BUFFER_SUPPORT,J6=WH.SYMBOL_SUPPORT;GH.exports=function(J,Z){var X,Y,H,G,U;if(!J)throw Error("obliterator/forEach: invalid iterable.");if(typeof Z!=="function")throw Error("obliterator/forEach: expecting a callback.");if(Array.isArray(J)||$6&&ArrayBuffer.isView(J)||typeof J==="string"||J.toString()==="[object Arguments]"){for(H=0,G=J.length;H<G;H++)Z(J[H],H);return}if(typeof J.forEach==="function"){J.forEach(Z);return}if(J6&&Symbol.iterator in J&&typeof J.next!=="function")J=J[Symbol.iterator]();if(typeof J.next==="function"){X=J,H=0;while(U=X.next(),U.done!==!0)Z(U.value,H),H++;return}for(Y in J)if(J.hasOwnProperty(Y))Z(J[Y],Y);return}});var VX=o((z6)=>{var Z6=Math.pow(2,8)-1,X6=Math.pow(2,16)-1,Y6=Math.pow(2,32)-1,H6=Math.pow(2,7)-1,W6=Math.pow(2,15)-1,G6=Math.pow(2,31)-1;z6.getPointerArray=function($){var J=$-1;if(J<=Z6)return Uint8Array;if(J<=X6)return Uint16Array;if(J<=Y6)return Uint32Array;throw Error("mnemonist: Pointer Array of size > 4294967295 is not supported.")};z6.getSignedPointerArray=function($){var J=$-1;if(J<=H6)return Int8Array;if(J<=W6)return Int16Array;if(J<=G6)return Int32Array;return Float64Array};z6.getNumberType=function($){if($===($|0))if(Math.sign($)===-1){if($<=127&&$>=-128)return Int8Array;if($<=32767&&$>=-32768)return Int16Array;return Int32Array}else{if($<=255)return Uint8Array;if($<=65535)return Uint16Array;return Uint32Array}return Float64Array};var Q6={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};z6.getMinimalRepresentation=function($,J){var Z=null,X=0,Y,H,G,U,V;for(U=0,V=$.length;U<V;U++)if(G=J?J($[U]):$[U],H=z6.getNumberType(G),Y=Q6[H.name],Y>X)X=Y,Z=H;return Z};z6.isTypedArray=function($){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView($)};z6.concat=function(){var $=0,J,Z,X;for(J=0,X=arguments.length;J<X;J++)$+=arguments[J].length;var Y=new arguments[0].constructor($);for(J=0,Z=0;J<X;J++)Y.set(arguments[J],Z),Z+=arguments[J].length;return Y};z6.indices=function($){var J=z6.getPointerArray($),Z=new J($);for(var X=0;X<$;X++)Z[X]=X;return Z}});var KH=o((M6)=>{var UH=UX(),VH=VX();function F6($){return Array.isArray($)||VH.isTypedArray($)}function KX($){if(typeof $.length==="number")return $.length;if(typeof $.size==="number")return $.size;return}function A6($){var J=KX($),Z=typeof J==="number"?Array(J):[],X=0;return UH($,function(Y){Z[X++]=Y}),Z}function R6($){var J=KX($),Z=typeof J==="number"?VH.getPointerArray(J):Array,X=typeof J==="number"?Array(J):[],Y=typeof J==="number"?new Z(J):[],H=0;return UH($,function(G){X[H]=G,Y[H]=H++}),[X,Y]}M6.isArrayLike=F6;M6.guessLength=KX;M6.toArray=A6;M6.toArrayWithIndices=R6});var _X=o((R7,OH)=>{var OX=YH(),j6=UX(),C6=VX(),S6=KH();function p0($,J,Z){if(arguments.length<2)Z=$,$=null,J=null;if(this.capacity=Z,typeof this.capacity!=="number"||this.capacity<=0)throw Error("mnemonist/lru-cache: capacity should be positive number.");else if(!isFinite(this.capacity)||Math.floor(this.capacity)!==this.capacity)throw Error("mnemonist/lru-cache: capacity should be a finite positive integer.");var X=C6.getPointerArray(Z);this.forward=new X(Z),this.backward=new X(Z),this.K=typeof $==="function"?new $(Z):Array(Z),this.V=typeof J==="function"?new J(Z):Array(Z),this.size=0,this.head=0,this.tail=0,this.items={}}p0.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}};p0.prototype.splayOnTop=function($){var J=this.head;if(this.head===$)return this;var Z=this.backward[$],X=this.forward[$];if(this.tail===$)this.tail=Z;else this.backward[X]=Z;return this.forward[Z]=X,this.backward[J]=$,this.head=$,this.forward[$]=J,this};p0.prototype.set=function($,J){var Z=this.items[$];if(typeof Z<"u"){this.splayOnTop(Z),this.V[Z]=J;return}if(this.size<this.capacity)Z=this.size++;else Z=this.tail,this.tail=this.backward[Z],delete this.items[this.K[Z]];this.items[$]=Z,this.K[Z]=$,this.V[Z]=J,this.forward[Z]=this.head,this.backward[this.head]=Z,this.head=Z};p0.prototype.setpop=function($,J){var Z=null,X=null,Y=this.items[$];if(typeof Y<"u")return this.splayOnTop(Y),Z=this.V[Y],this.V[Y]=J,{evicted:!1,key:$,value:Z};if(this.size<this.capacity)Y=this.size++;else Y=this.tail,this.tail=this.backward[Y],Z=this.V[Y],X=this.K[Y],delete this.items[X];if(this.items[$]=Y,this.K[Y]=$,this.V[Y]=J,this.forward[Y]=this.head,this.backward[this.head]=Y,this.head=Y,X)return{evicted:!0,key:X,value:Z};else return null};p0.prototype.has=function($){return $ in this.items};p0.prototype.get=function($){var J=this.items[$];if(typeof J>"u")return;return this.splayOnTop(J),this.V[J]};p0.prototype.peek=function($){var J=this.items[$];if(typeof J>"u")return;return this.V[J]};p0.prototype.forEach=function($,J){J=arguments.length>1?J:this;var Z=0,X=this.size,Y=this.head,H=this.K,G=this.V,U=this.forward;while(Z<X)$.call(J,G[Y],H[Y],this),Y=U[Y],Z++};p0.prototype.keys=function(){var $=0,J=this.size,Z=this.head,X=this.K,Y=this.forward;return new OX(function(){if($>=J)return{done:!0};var H=X[Z];if($++,$<J)Z=Y[Z];return{done:!1,value:H}})};p0.prototype.values=function(){var $=0,J=this.size,Z=this.head,X=this.V,Y=this.forward;return new OX(function(){if($>=J)return{done:!0};var H=X[Z];if($++,$<J)Z=Y[Z];return{done:!1,value:H}})};p0.prototype.entries=function(){var $=0,J=this.size,Z=this.head,X=this.K,Y=this.V,H=this.forward;return new OX(function(){if($>=J)return{done:!0};var G=X[Z],U=Y[Z];if($++,$<J)Z=H[Z];return{done:!1,value:[G,U]}})};if(typeof Symbol<"u")p0.prototype[Symbol.iterator]=p0.prototype.entries;p0.prototype.inspect=function(){var $=new Map,J=this.entries(),Z;while(Z=J.next(),!Z.done)$.set(Z.value[0],Z.value[1]);return Object.defineProperty($,"constructor",{value:p0,enumerable:!1}),$};if(typeof Symbol<"u")p0.prototype[Symbol.for("nodejs.util.inspect.custom")]=p0.prototype.inspect;p0.from=function($,J,Z,X){if(arguments.length<2){if(X=S6.guessLength($),typeof X!=="number")throw Error("mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.")}else if(arguments.length===2)X=J,J=null,Z=null;var Y=new p0(J,Z,X);return j6($,function(H,G){Y.set(G,H)}),Y};OH.exports=p0});var AX=o((_H,FX)=>{(function($,J){function Z(q,W){if(!q)throw Error(W||"Assertion failed")}function X(q,W){q.super_=W;var z=function(){};z.prototype=W.prototype,q.prototype=new z,q.prototype.constructor=q}function Y(q,W,z){if(Y.isBN(q))return q;if(this.negative=0,this.words=null,this.length=0,this.red=null,q!==null){if(W==="le"||W==="be")z=W,W=10;this._init(q||0,W||10,z||"be")}}if(typeof $==="object")$.exports=Y;else J.BN=Y;Y.BN=Y,Y.wordSize=26;var H;try{if(typeof window<"u"&&typeof window.Buffer<"u")H=window.Buffer;else H=K$("buffer").Buffer}catch(q){}Y.isBN=function(W){if(W instanceof Y)return!0;return W!==null&&typeof W==="object"&&W.constructor.wordSize===Y.wordSize&&Array.isArray(W.words)},Y.max=function(W,z){if(W.cmp(z)>0)return W;return z},Y.min=function(W,z){if(W.cmp(z)<0)return W;return z},Y.prototype._init=function(W,z,O){if(typeof W==="number")return this._initNumber(W,z,O);if(typeof W==="object")return this._initArray(W,z,O);if(z==="hex")z=16;Z(z===(z|0)&&z>=2&&z<=36),W=W.toString().replace(/\s+/g,"");var _=0;if(W[0]==="-")_++,this.negative=1;if(_<W.length){if(z===16)this._parseHex(W,_,O);else if(this._parseBase(W,z,_),O==="le")this._initArray(this.toArray(),z,O)}},Y.prototype._initNumber=function(W,z,O){if(W<0)this.negative=1,W=-W;if(W<67108864)this.words=[W&67108863],this.length=1;else if(W<4503599627370496)this.words=[W&67108863,W/67108864&67108863],this.length=2;else Z(W<9007199254740992),this.words=[W&67108863,W/67108864&67108863,1],this.length=3;if(O!=="le")return;this._initArray(this.toArray(),z,O)},Y.prototype._initArray=function(W,z,O){if(Z(typeof W.length==="number"),W.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(W.length/3),this.words=Array(this.length);for(var _=0;_<this.length;_++)this.words[_]=0;var I,B,S=0;if(O==="be"){for(_=W.length-1,I=0;_>=0;_-=3)if(B=W[_]|W[_-1]<<8|W[_-2]<<16,this.words[I]|=B<<S&67108863,this.words[I+1]=B>>>26-S&67108863,S+=24,S>=26)S-=26,I++}else if(O==="le"){for(_=0,I=0;_<W.length;_+=3)if(B=W[_]|W[_+1]<<8|W[_+2]<<16,this.words[I]|=B<<S&67108863,this.words[I+1]=B>>>26-S&67108863,S+=24,S>=26)S-=26,I++}return this.strip()};function G(q,W){var z=q.charCodeAt(W);if(z>=65&&z<=70)return z-55;else if(z>=97&&z<=102)return z-87;else return z-48&15}function U(q,W,z){var O=G(q,z);if(z-1>=W)O|=G(q,z-1)<<4;return O}Y.prototype._parseHex=function(W,z,O){this.length=Math.ceil((W.length-z)/6),this.words=Array(this.length);for(var _=0;_<this.length;_++)this.words[_]=0;var I=0,B=0,S;if(O==="be")for(_=W.length-1;_>=z;_-=2)if(S=U(W,z,_)<<I,this.words[B]|=S&67108863,I>=18)I-=18,B+=1,this.words[B]|=S>>>26;else I+=8;else{var R=W.length-z;for(_=R%2===0?z+1:z;_<W.length;_+=2)if(S=U(W,z,_)<<I,this.words[B]|=S&67108863,I>=18)I-=18,B+=1,this.words[B]|=S>>>26;else I+=8}this.strip()};function V(q,W,z,O){var _=0,I=Math.min(q.length,z);for(var B=W;B<I;B++){var S=q.charCodeAt(B)-48;if(_*=O,S>=49)_+=S-49+10;else if(S>=17)_+=S-17+10;else _+=S}return _}Y.prototype._parseBase=function(W,z,O){this.words=[0],this.length=1;for(var _=0,I=1;I<=67108863;I*=z)_++;_--,I=I/z|0;var B=W.length-O,S=B%_,R=Math.min(B,B-S)+O,Q=0;for(var M=O;M<R;M+=_)if(Q=V(W,M,M+_,z),this.imuln(I),this.words[0]+Q<67108864)this.words[0]+=Q;else this._iaddn(Q);if(S!==0){var k=1;Q=V(W,M,W.length,z);for(M=0;M<S;M++)k*=z;if(this.imuln(k),this.words[0]+Q<67108864)this.words[0]+=Q;else this._iaddn(Q)}this.strip()},Y.prototype.copy=function(W){W.words=Array(this.length);for(var z=0;z<this.length;z++)W.words[z]=this.words[z];W.length=this.length,W.negative=this.negative,W.red=this.red},Y.prototype.clone=function(){var W=new Y(null);return this.copy(W),W},Y.prototype._expand=function(W){while(this.length<W)this.words[this.length++]=0;return this},Y.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},Y.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},Y.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var K=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],F=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],A=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];if(Y.prototype.toString=function(W,z){W=W||10,z=z|0||1;var O;if(W===16||W==="hex"){O="";var _=0,I=0;for(var B=0;B<this.length;B++){var S=this.words[B],R=((S<<_|I)&16777215).toString(16);if(I=S>>>24-_&16777215,_+=2,_>=26)_-=26,B--;if(I!==0||B!==this.length-1)O=K[6-R.length]+R+O;else O=R+O}if(I!==0)O=I.toString(16)+O;while(O.length%z!==0)O="0"+O;if(this.negative!==0)O="-"+O;return O}if(W===(W|0)&&W>=2&&W<=36){var Q=F[W],M=A[W];O="";var k=this.clone();k.negative=0;while(!k.isZero()){var x=k.modn(M).toString(W);if(k=k.idivn(M),!k.isZero())O=K[Q-x.length]+x+O;else O=x+O}if(this.isZero())O="0"+O;while(O.length%z!==0)O="0"+O;if(this.negative!==0)O="-"+O;return O}Z(!1,"Base should be between 2 and 36")},Y.prototype.toNumber=function(){var W=this.words[0];if(this.length===2)W+=this.words[1]*67108864;else if(this.length===3&&this.words[2]===1)W+=4503599627370496+this.words[1]*67108864;else if(this.length>2)Z(!1,"Number can only safely store up to 53 bits");return this.negative!==0?-W:W},Y.prototype.toJSON=function(){return this.toString(16)},Y.prototype.toBuffer=function(W,z){return Z(typeof H<"u"),this.toArrayLike(H,W,z)},Y.prototype.toArray=function(W,z){return this.toArrayLike(Array,W,z)},Y.prototype.toArrayLike=function(W,z,O){var _=this.byteLength(),I=O||Math.max(1,_);Z(_<=I,"byte array longer than desired length"),Z(I>0,"Requested array length <= 0"),this.strip();var B=z==="le",S=new W(I),R,Q,M=this.clone();if(!B){for(Q=0;Q<I-_;Q++)S[Q]=0;for(Q=0;!M.isZero();Q++)R=M.andln(255),M.iushrn(8),S[I-Q-1]=R}else{for(Q=0;!M.isZero();Q++)R=M.andln(255),M.iushrn(8),S[Q]=R;for(;Q<I;Q++)S[Q]=0}return S},Math.clz32)Y.prototype._countBits=function(W){return 32-Math.clz32(W)};else Y.prototype._countBits=function(W){var z=W,O=0;if(z>=4096)O+=13,z>>>=13;if(z>=64)O+=7,z>>>=7;if(z>=8)O+=4,z>>>=4;if(z>=2)O+=2,z>>>=2;return O+z};Y.prototype._zeroBits=function(W){if(W===0)return 26;var z=W,O=0;if((z&8191)===0)O+=13,z>>>=13;if((z&127)===0)O+=7,z>>>=7;if((z&15)===0)O+=4,z>>>=4;if((z&3)===0)O+=2,z>>>=2;if((z&1)===0)O++;return O},Y.prototype.bitLength=function(){var W=this.words[this.length-1],z=this._countBits(W);return(this.length-1)*26+z};function j(q){var W=Array(q.bitLength());for(var z=0;z<W.length;z++){var O=z/26|0,_=z%26;W[z]=(q.words[O]&1<<_)>>>_}return W}Y.prototype.zeroBits=function(){if(this.isZero())return 0;var W=0;for(var z=0;z<this.length;z++){var O=this._zeroBits(this.words[z]);if(W+=O,O!==26)break}return W},Y.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},Y.prototype.toTwos=function(W){if(this.negative!==0)return this.abs().inotn(W).iaddn(1);return this.clone()},Y.prototype.fromTwos=function(W){if(this.testn(W-1))return this.notn(W).iaddn(1).ineg();return this.clone()},Y.prototype.isNeg=function(){return this.negative!==0},Y.prototype.neg=function(){return this.clone().ineg()},Y.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},Y.prototype.iuor=function(W){while(this.length<W.length)this.words[this.length++]=0;for(var z=0;z<W.length;z++)this.words[z]=this.words[z]|W.words[z];return this.strip()},Y.prototype.ior=function(W){return Z((this.negative|W.negative)===0),this.iuor(W)},Y.prototype.or=function(W){if(this.length>W.length)return this.clone().ior(W);return W.clone().ior(this)},Y.prototype.uor=function(W){if(this.length>W.length)return this.clone().iuor(W);return W.clone().iuor(this)},Y.prototype.iuand=function(W){var z;if(this.length>W.length)z=W;else z=this;for(var O=0;O<z.length;O++)this.words[O]=this.words[O]&W.words[O];return this.length=z.length,this.strip()},Y.prototype.iand=function(W){return Z((this.negative|W.negative)===0),this.iuand(W)},Y.prototype.and=function(W){if(this.length>W.length)return this.clone().iand(W);return W.clone().iand(this)},Y.prototype.uand=function(W){if(this.length>W.length)return this.clone().iuand(W);return W.clone().iuand(this)},Y.prototype.iuxor=function(W){var z,O;if(this.length>W.length)z=this,O=W;else z=W,O=this;for(var _=0;_<O.length;_++)this.words[_]=z.words[_]^O.words[_];if(this!==z)for(;_<z.length;_++)this.words[_]=z.words[_];return this.length=z.length,this.strip()},Y.prototype.ixor=function(W){return Z((this.negative|W.negative)===0),this.iuxor(W)},Y.prototype.xor=function(W){if(this.length>W.length)return this.clone().ixor(W);return W.clone().ixor(this)},Y.prototype.uxor=function(W){if(this.length>W.length)return this.clone().iuxor(W);return W.clone().iuxor(this)},Y.prototype.inotn=function(W){Z(typeof W==="number"&&W>=0);var z=Math.ceil(W/26)|0,O=W%26;if(this._expand(z),O>0)z--;for(var _=0;_<z;_++)this.words[_]=~this.words[_]&67108863;if(O>0)this.words[_]=~this.words[_]&67108863>>26-O;return this.strip()},Y.prototype.notn=function(W){return this.clone().inotn(W)},Y.prototype.setn=function(W,z){Z(typeof W==="number"&&W>=0);var O=W/26|0,_=W%26;if(this._expand(O+1),z)this.words[O]=this.words[O]|1<<_;else this.words[O]=this.words[O]&~(1<<_);return this.strip()},Y.prototype.iadd=function(W){var z;if(this.negative!==0&&W.negative===0)return this.negative=0,z=this.isub(W),this.negative^=1,this._normSign();else if(this.negative===0&&W.negative!==0)return W.negative=0,z=this.isub(W),W.negative=1,z._normSign();var O,_;if(this.length>W.length)O=this,_=W;else O=W,_=this;var I=0;for(var B=0;B<_.length;B++)z=(O.words[B]|0)+(_.words[B]|0)+I,this.words[B]=z&67108863,I=z>>>26;for(;I!==0&&B<O.length;B++)z=(O.words[B]|0)+I,this.words[B]=z&67108863,I=z>>>26;if(this.length=O.length,I!==0)this.words[this.length]=I,this.length++;else if(O!==this)for(;B<O.length;B++)this.words[B]=O.words[B];return this},Y.prototype.add=function(W){var z;if(W.negative!==0&&this.negative===0)return W.negative=0,z=this.sub(W),W.negative^=1,z;else if(W.negative===0&&this.negative!==0)return this.negative=0,z=W.sub(this),this.negative=1,z;if(this.length>W.length)return this.clone().iadd(W);return W.clone().iadd(this)},Y.prototype.isub=function(W){if(W.negative!==0){W.negative=0;var z=this.iadd(W);return W.negative=1,z._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(W),this.negative=1,this._normSign();var O=this.cmp(W);if(O===0)return this.negative=0,this.length=1,this.words[0]=0,this;var _,I;if(O>0)_=this,I=W;else _=W,I=this;var B=0;for(var S=0;S<I.length;S++)z=(_.words[S]|0)-(I.words[S]|0)+B,B=z>>26,this.words[S]=z&67108863;for(;B!==0&&S<_.length;S++)z=(_.words[S]|0)+B,B=z>>26,this.words[S]=z&67108863;if(B===0&&S<_.length&&_!==this)for(;S<_.length;S++)this.words[S]=_.words[S];if(this.length=Math.max(this.length,S),_!==this)this.negative=1;return this.strip()},Y.prototype.sub=function(W){return this.clone().isub(W)};function C(q,W,z){z.negative=W.negative^q.negative;var O=q.length+W.length|0;z.length=O,O=O-1|0;var _=q.words[0]|0,I=W.words[0]|0,B=_*I,S=B&67108863,R=B/67108864|0;z.words[0]=S;for(var Q=1;Q<O;Q++){var M=R>>>26,k=R&67108863,x=Math.min(Q,W.length-1);for(var y=Math.max(0,Q-q.length+1);y<=x;y++){var c=Q-y|0;_=q.words[c]|0,I=W.words[y]|0,B=_*I+k,M+=B/67108864|0,k=B&67108863}z.words[Q]=k|0,R=M|0}if(R!==0)z.words[Q]=R|0;else z.length--;return z.strip()}var w=function(W,z,O){var _=W.words,I=z.words,B=O.words,S=0,R,Q,M,k=_[0]|0,x=k&8191,y=k>>>13,c=_[1]|0,i=c&8191,e=c>>>13,V$=_[2]|0,$0=V$&8191,Z0=V$>>>13,pX=_[3]|0,W0=pX&8191,G0=pX>>>13,uX=_[4]|0,Q0=uX&8191,z0=uX>>>13,mX=_[5]|0,U0=mX&8191,V0=mX>>>13,dX=_[6]|0,K0=dX&8191,O0=dX>>>13,nX=_[7]|0,_0=nX&8191,F0=nX>>>13,oX=_[8]|0,A0=oX&8191,R0=oX>>>13,sX=_[9]|0,M0=sX&8191,I0=sX>>>13,lX=I[0]|0,q0=lX&8191,P0=lX>>>13,rX=I[1]|0,B0=rX&8191,j0=rX>>>13,iX=I[2]|0,C0=iX&8191,S0=iX>>>13,tX=I[3]|0,w0=tX&8191,L0=tX>>>13,aX=I[4]|0,E0=aX&8191,T0=aX>>>13,eX=I[5]|0,N0=eX&8191,v0=eX>>>13,$1=I[6]|0,D0=$1&8191,k0=$1>>>13,J1=I[7]|0,x0=J1&8191,y0=J1>>>13,Z1=I[8]|0,f0=Z1&8191,h0=Z1>>>13,X1=I[9]|0,g0=X1&8191,b0=X1>>>13;O.negative=W.negative^z.negative,O.length=19,R=Math.imul(x,q0),Q=Math.imul(x,P0),Q=Q+Math.imul(y,q0)|0,M=Math.imul(y,P0);var HZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(HZ>>>26)|0,HZ&=67108863,R=Math.imul(i,q0),Q=Math.imul(i,P0),Q=Q+Math.imul(e,q0)|0,M=Math.imul(e,P0),R=R+Math.imul(x,B0)|0,Q=Q+Math.imul(x,j0)|0,Q=Q+Math.imul(y,B0)|0,M=M+Math.imul(y,j0)|0;var WZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(WZ>>>26)|0,WZ&=67108863,R=Math.imul($0,q0),Q=Math.imul($0,P0),Q=Q+Math.imul(Z0,q0)|0,M=Math.imul(Z0,P0),R=R+Math.imul(i,B0)|0,Q=Q+Math.imul(i,j0)|0,Q=Q+Math.imul(e,B0)|0,M=M+Math.imul(e,j0)|0,R=R+Math.imul(x,C0)|0,Q=Q+Math.imul(x,S0)|0,Q=Q+Math.imul(y,C0)|0,M=M+Math.imul(y,S0)|0;var GZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(GZ>>>26)|0,GZ&=67108863,R=Math.imul(W0,q0),Q=Math.imul(W0,P0),Q=Q+Math.imul(G0,q0)|0,M=Math.imul(G0,P0),R=R+Math.imul($0,B0)|0,Q=Q+Math.imul($0,j0)|0,Q=Q+Math.imul(Z0,B0)|0,M=M+Math.imul(Z0,j0)|0,R=R+Math.imul(i,C0)|0,Q=Q+Math.imul(i,S0)|0,Q=Q+Math.imul(e,C0)|0,M=M+Math.imul(e,S0)|0,R=R+Math.imul(x,w0)|0,Q=Q+Math.imul(x,L0)|0,Q=Q+Math.imul(y,w0)|0,M=M+Math.imul(y,L0)|0;var QZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(QZ>>>26)|0,QZ&=67108863,R=Math.imul(Q0,q0),Q=Math.imul(Q0,P0),Q=Q+Math.imul(z0,q0)|0,M=Math.imul(z0,P0),R=R+Math.imul(W0,B0)|0,Q=Q+Math.imul(W0,j0)|0,Q=Q+Math.imul(G0,B0)|0,M=M+Math.imul(G0,j0)|0,R=R+Math.imul($0,C0)|0,Q=Q+Math.imul($0,S0)|0,Q=Q+Math.imul(Z0,C0)|0,M=M+Math.imul(Z0,S0)|0,R=R+Math.imul(i,w0)|0,Q=Q+Math.imul(i,L0)|0,Q=Q+Math.imul(e,w0)|0,M=M+Math.imul(e,L0)|0,R=R+Math.imul(x,E0)|0,Q=Q+Math.imul(x,T0)|0,Q=Q+Math.imul(y,E0)|0,M=M+Math.imul(y,T0)|0;var zZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,R=Math.imul(U0,q0),Q=Math.imul(U0,P0),Q=Q+Math.imul(V0,q0)|0,M=Math.imul(V0,P0),R=R+Math.imul(Q0,B0)|0,Q=Q+Math.imul(Q0,j0)|0,Q=Q+Math.imul(z0,B0)|0,M=M+Math.imul(z0,j0)|0,R=R+Math.imul(W0,C0)|0,Q=Q+Math.imul(W0,S0)|0,Q=Q+Math.imul(G0,C0)|0,M=M+Math.imul(G0,S0)|0,R=R+Math.imul($0,w0)|0,Q=Q+Math.imul($0,L0)|0,Q=Q+Math.imul(Z0,w0)|0,M=M+Math.imul(Z0,L0)|0,R=R+Math.imul(i,E0)|0,Q=Q+Math.imul(i,T0)|0,Q=Q+Math.imul(e,E0)|0,M=M+Math.imul(e,T0)|0,R=R+Math.imul(x,N0)|0,Q=Q+Math.imul(x,v0)|0,Q=Q+Math.imul(y,N0)|0,M=M+Math.imul(y,v0)|0;var UZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(UZ>>>26)|0,UZ&=67108863,R=Math.imul(K0,q0),Q=Math.imul(K0,P0),Q=Q+Math.imul(O0,q0)|0,M=Math.imul(O0,P0),R=R+Math.imul(U0,B0)|0,Q=Q+Math.imul(U0,j0)|0,Q=Q+Math.imul(V0,B0)|0,M=M+Math.imul(V0,j0)|0,R=R+Math.imul(Q0,C0)|0,Q=Q+Math.imul(Q0,S0)|0,Q=Q+Math.imul(z0,C0)|0,M=M+Math.imul(z0,S0)|0,R=R+Math.imul(W0,w0)|0,Q=Q+Math.imul(W0,L0)|0,Q=Q+Math.imul(G0,w0)|0,M=M+Math.imul(G0,L0)|0,R=R+Math.imul($0,E0)|0,Q=Q+Math.imul($0,T0)|0,Q=Q+Math.imul(Z0,E0)|0,M=M+Math.imul(Z0,T0)|0,R=R+Math.imul(i,N0)|0,Q=Q+Math.imul(i,v0)|0,Q=Q+Math.imul(e,N0)|0,M=M+Math.imul(e,v0)|0,R=R+Math.imul(x,D0)|0,Q=Q+Math.imul(x,k0)|0,Q=Q+Math.imul(y,D0)|0,M=M+Math.imul(y,k0)|0;var VZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(VZ>>>26)|0,VZ&=67108863,R=Math.imul(_0,q0),Q=Math.imul(_0,P0),Q=Q+Math.imul(F0,q0)|0,M=Math.imul(F0,P0),R=R+Math.imul(K0,B0)|0,Q=Q+Math.imul(K0,j0)|0,Q=Q+Math.imul(O0,B0)|0,M=M+Math.imul(O0,j0)|0,R=R+Math.imul(U0,C0)|0,Q=Q+Math.imul(U0,S0)|0,Q=Q+Math.imul(V0,C0)|0,M=M+Math.imul(V0,S0)|0,R=R+Math.imul(Q0,w0)|0,Q=Q+Math.imul(Q0,L0)|0,Q=Q+Math.imul(z0,w0)|0,M=M+Math.imul(z0,L0)|0,R=R+Math.imul(W0,E0)|0,Q=Q+Math.imul(W0,T0)|0,Q=Q+Math.imul(G0,E0)|0,M=M+Math.imul(G0,T0)|0,R=R+Math.imul($0,N0)|0,Q=Q+Math.imul($0,v0)|0,Q=Q+Math.imul(Z0,N0)|0,M=M+Math.imul(Z0,v0)|0,R=R+Math.imul(i,D0)|0,Q=Q+Math.imul(i,k0)|0,Q=Q+Math.imul(e,D0)|0,M=M+Math.imul(e,k0)|0,R=R+Math.imul(x,x0)|0,Q=Q+Math.imul(x,y0)|0,Q=Q+Math.imul(y,x0)|0,M=M+Math.imul(y,y0)|0;var KZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(KZ>>>26)|0,KZ&=67108863,R=Math.imul(A0,q0),Q=Math.imul(A0,P0),Q=Q+Math.imul(R0,q0)|0,M=Math.imul(R0,P0),R=R+Math.imul(_0,B0)|0,Q=Q+Math.imul(_0,j0)|0,Q=Q+Math.imul(F0,B0)|0,M=M+Math.imul(F0,j0)|0,R=R+Math.imul(K0,C0)|0,Q=Q+Math.imul(K0,S0)|0,Q=Q+Math.imul(O0,C0)|0,M=M+Math.imul(O0,S0)|0,R=R+Math.imul(U0,w0)|0,Q=Q+Math.imul(U0,L0)|0,Q=Q+Math.imul(V0,w0)|0,M=M+Math.imul(V0,L0)|0,R=R+Math.imul(Q0,E0)|0,Q=Q+Math.imul(Q0,T0)|0,Q=Q+Math.imul(z0,E0)|0,M=M+Math.imul(z0,T0)|0,R=R+Math.imul(W0,N0)|0,Q=Q+Math.imul(W0,v0)|0,Q=Q+Math.imul(G0,N0)|0,M=M+Math.imul(G0,v0)|0,R=R+Math.imul($0,D0)|0,Q=Q+Math.imul($0,k0)|0,Q=Q+Math.imul(Z0,D0)|0,M=M+Math.imul(Z0,k0)|0,R=R+Math.imul(i,x0)|0,Q=Q+Math.imul(i,y0)|0,Q=Q+Math.imul(e,x0)|0,M=M+Math.imul(e,y0)|0,R=R+Math.imul(x,f0)|0,Q=Q+Math.imul(x,h0)|0,Q=Q+Math.imul(y,f0)|0,M=M+Math.imul(y,h0)|0;var OZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(OZ>>>26)|0,OZ&=67108863,R=Math.imul(M0,q0),Q=Math.imul(M0,P0),Q=Q+Math.imul(I0,q0)|0,M=Math.imul(I0,P0),R=R+Math.imul(A0,B0)|0,Q=Q+Math.imul(A0,j0)|0,Q=Q+Math.imul(R0,B0)|0,M=M+Math.imul(R0,j0)|0,R=R+Math.imul(_0,C0)|0,Q=Q+Math.imul(_0,S0)|0,Q=Q+Math.imul(F0,C0)|0,M=M+Math.imul(F0,S0)|0,R=R+Math.imul(K0,w0)|0,Q=Q+Math.imul(K0,L0)|0,Q=Q+Math.imul(O0,w0)|0,M=M+Math.imul(O0,L0)|0,R=R+Math.imul(U0,E0)|0,Q=Q+Math.imul(U0,T0)|0,Q=Q+Math.imul(V0,E0)|0,M=M+Math.imul(V0,T0)|0,R=R+Math.imul(Q0,N0)|0,Q=Q+Math.imul(Q0,v0)|0,Q=Q+Math.imul(z0,N0)|0,M=M+Math.imul(z0,v0)|0,R=R+Math.imul(W0,D0)|0,Q=Q+Math.imul(W0,k0)|0,Q=Q+Math.imul(G0,D0)|0,M=M+Math.imul(G0,k0)|0,R=R+Math.imul($0,x0)|0,Q=Q+Math.imul($0,y0)|0,Q=Q+Math.imul(Z0,x0)|0,M=M+Math.imul(Z0,y0)|0,R=R+Math.imul(i,f0)|0,Q=Q+Math.imul(i,h0)|0,Q=Q+Math.imul(e,f0)|0,M=M+Math.imul(e,h0)|0,R=R+Math.imul(x,g0)|0,Q=Q+Math.imul(x,b0)|0,Q=Q+Math.imul(y,g0)|0,M=M+Math.imul(y,b0)|0;var _Z=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(_Z>>>26)|0,_Z&=67108863,R=Math.imul(M0,B0),Q=Math.imul(M0,j0),Q=Q+Math.imul(I0,B0)|0,M=Math.imul(I0,j0),R=R+Math.imul(A0,C0)|0,Q=Q+Math.imul(A0,S0)|0,Q=Q+Math.imul(R0,C0)|0,M=M+Math.imul(R0,S0)|0,R=R+Math.imul(_0,w0)|0,Q=Q+Math.imul(_0,L0)|0,Q=Q+Math.imul(F0,w0)|0,M=M+Math.imul(F0,L0)|0,R=R+Math.imul(K0,E0)|0,Q=Q+Math.imul(K0,T0)|0,Q=Q+Math.imul(O0,E0)|0,M=M+Math.imul(O0,T0)|0,R=R+Math.imul(U0,N0)|0,Q=Q+Math.imul(U0,v0)|0,Q=Q+Math.imul(V0,N0)|0,M=M+Math.imul(V0,v0)|0,R=R+Math.imul(Q0,D0)|0,Q=Q+Math.imul(Q0,k0)|0,Q=Q+Math.imul(z0,D0)|0,M=M+Math.imul(z0,k0)|0,R=R+Math.imul(W0,x0)|0,Q=Q+Math.imul(W0,y0)|0,Q=Q+Math.imul(G0,x0)|0,M=M+Math.imul(G0,y0)|0,R=R+Math.imul($0,f0)|0,Q=Q+Math.imul($0,h0)|0,Q=Q+Math.imul(Z0,f0)|0,M=M+Math.imul(Z0,h0)|0,R=R+Math.imul(i,g0)|0,Q=Q+Math.imul(i,b0)|0,Q=Q+Math.imul(e,g0)|0,M=M+Math.imul(e,b0)|0;var FZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(FZ>>>26)|0,FZ&=67108863,R=Math.imul(M0,C0),Q=Math.imul(M0,S0),Q=Q+Math.imul(I0,C0)|0,M=Math.imul(I0,S0),R=R+Math.imul(A0,w0)|0,Q=Q+Math.imul(A0,L0)|0,Q=Q+Math.imul(R0,w0)|0,M=M+Math.imul(R0,L0)|0,R=R+Math.imul(_0,E0)|0,Q=Q+Math.imul(_0,T0)|0,Q=Q+Math.imul(F0,E0)|0,M=M+Math.imul(F0,T0)|0,R=R+Math.imul(K0,N0)|0,Q=Q+Math.imul(K0,v0)|0,Q=Q+Math.imul(O0,N0)|0,M=M+Math.imul(O0,v0)|0,R=R+Math.imul(U0,D0)|0,Q=Q+Math.imul(U0,k0)|0,Q=Q+Math.imul(V0,D0)|0,M=M+Math.imul(V0,k0)|0,R=R+Math.imul(Q0,x0)|0,Q=Q+Math.imul(Q0,y0)|0,Q=Q+Math.imul(z0,x0)|0,M=M+Math.imul(z0,y0)|0,R=R+Math.imul(W0,f0)|0,Q=Q+Math.imul(W0,h0)|0,Q=Q+Math.imul(G0,f0)|0,M=M+Math.imul(G0,h0)|0,R=R+Math.imul($0,g0)|0,Q=Q+Math.imul($0,b0)|0,Q=Q+Math.imul(Z0,g0)|0,M=M+Math.imul(Z0,b0)|0;var AZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(AZ>>>26)|0,AZ&=67108863,R=Math.imul(M0,w0),Q=Math.imul(M0,L0),Q=Q+Math.imul(I0,w0)|0,M=Math.imul(I0,L0),R=R+Math.imul(A0,E0)|0,Q=Q+Math.imul(A0,T0)|0,Q=Q+Math.imul(R0,E0)|0,M=M+Math.imul(R0,T0)|0,R=R+Math.imul(_0,N0)|0,Q=Q+Math.imul(_0,v0)|0,Q=Q+Math.imul(F0,N0)|0,M=M+Math.imul(F0,v0)|0,R=R+Math.imul(K0,D0)|0,Q=Q+Math.imul(K0,k0)|0,Q=Q+Math.imul(O0,D0)|0,M=M+Math.imul(O0,k0)|0,R=R+Math.imul(U0,x0)|0,Q=Q+Math.imul(U0,y0)|0,Q=Q+Math.imul(V0,x0)|0,M=M+Math.imul(V0,y0)|0,R=R+Math.imul(Q0,f0)|0,Q=Q+Math.imul(Q0,h0)|0,Q=Q+Math.imul(z0,f0)|0,M=M+Math.imul(z0,h0)|0,R=R+Math.imul(W0,g0)|0,Q=Q+Math.imul(W0,b0)|0,Q=Q+Math.imul(G0,g0)|0,M=M+Math.imul(G0,b0)|0;var RZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(RZ>>>26)|0,RZ&=67108863,R=Math.imul(M0,E0),Q=Math.imul(M0,T0),Q=Q+Math.imul(I0,E0)|0,M=Math.imul(I0,T0),R=R+Math.imul(A0,N0)|0,Q=Q+Math.imul(A0,v0)|0,Q=Q+Math.imul(R0,N0)|0,M=M+Math.imul(R0,v0)|0,R=R+Math.imul(_0,D0)|0,Q=Q+Math.imul(_0,k0)|0,Q=Q+Math.imul(F0,D0)|0,M=M+Math.imul(F0,k0)|0,R=R+Math.imul(K0,x0)|0,Q=Q+Math.imul(K0,y0)|0,Q=Q+Math.imul(O0,x0)|0,M=M+Math.imul(O0,y0)|0,R=R+Math.imul(U0,f0)|0,Q=Q+Math.imul(U0,h0)|0,Q=Q+Math.imul(V0,f0)|0,M=M+Math.imul(V0,h0)|0,R=R+Math.imul(Q0,g0)|0,Q=Q+Math.imul(Q0,b0)|0,Q=Q+Math.imul(z0,g0)|0,M=M+Math.imul(z0,b0)|0;var MZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(MZ>>>26)|0,MZ&=67108863,R=Math.imul(M0,N0),Q=Math.imul(M0,v0),Q=Q+Math.imul(I0,N0)|0,M=Math.imul(I0,v0),R=R+Math.imul(A0,D0)|0,Q=Q+Math.imul(A0,k0)|0,Q=Q+Math.imul(R0,D0)|0,M=M+Math.imul(R0,k0)|0,R=R+Math.imul(_0,x0)|0,Q=Q+Math.imul(_0,y0)|0,Q=Q+Math.imul(F0,x0)|0,M=M+Math.imul(F0,y0)|0,R=R+Math.imul(K0,f0)|0,Q=Q+Math.imul(K0,h0)|0,Q=Q+Math.imul(O0,f0)|0,M=M+Math.imul(O0,h0)|0,R=R+Math.imul(U0,g0)|0,Q=Q+Math.imul(U0,b0)|0,Q=Q+Math.imul(V0,g0)|0,M=M+Math.imul(V0,b0)|0;var IZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(IZ>>>26)|0,IZ&=67108863,R=Math.imul(M0,D0),Q=Math.imul(M0,k0),Q=Q+Math.imul(I0,D0)|0,M=Math.imul(I0,k0),R=R+Math.imul(A0,x0)|0,Q=Q+Math.imul(A0,y0)|0,Q=Q+Math.imul(R0,x0)|0,M=M+Math.imul(R0,y0)|0,R=R+Math.imul(_0,f0)|0,Q=Q+Math.imul(_0,h0)|0,Q=Q+Math.imul(F0,f0)|0,M=M+Math.imul(F0,h0)|0,R=R+Math.imul(K0,g0)|0,Q=Q+Math.imul(K0,b0)|0,Q=Q+Math.imul(O0,g0)|0,M=M+Math.imul(O0,b0)|0;var qZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(qZ>>>26)|0,qZ&=67108863,R=Math.imul(M0,x0),Q=Math.imul(M0,y0),Q=Q+Math.imul(I0,x0)|0,M=Math.imul(I0,y0),R=R+Math.imul(A0,f0)|0,Q=Q+Math.imul(A0,h0)|0,Q=Q+Math.imul(R0,f0)|0,M=M+Math.imul(R0,h0)|0,R=R+Math.imul(_0,g0)|0,Q=Q+Math.imul(_0,b0)|0,Q=Q+Math.imul(F0,g0)|0,M=M+Math.imul(F0,b0)|0;var PZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(PZ>>>26)|0,PZ&=67108863,R=Math.imul(M0,f0),Q=Math.imul(M0,h0),Q=Q+Math.imul(I0,f0)|0,M=Math.imul(I0,h0),R=R+Math.imul(A0,g0)|0,Q=Q+Math.imul(A0,b0)|0,Q=Q+Math.imul(R0,g0)|0,M=M+Math.imul(R0,b0)|0;var BZ=(S+R|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(BZ>>>26)|0,BZ&=67108863,R=Math.imul(M0,g0),Q=Math.imul(M0,b0),Q=Q+Math.imul(I0,g0)|0,M=Math.imul(I0,b0);var jZ=(S+R|0)+((Q&8191)<<13)|0;if(S=(M+(Q>>>13)|0)+(jZ>>>26)|0,jZ&=67108863,B[0]=HZ,B[1]=WZ,B[2]=GZ,B[3]=QZ,B[4]=zZ,B[5]=UZ,B[6]=VZ,B[7]=KZ,B[8]=OZ,B[9]=_Z,B[10]=FZ,B[11]=AZ,B[12]=RZ,B[13]=MZ,B[14]=IZ,B[15]=qZ,B[16]=PZ,B[17]=BZ,B[18]=jZ,S!==0)B[19]=S,O.length++;return O};if(!Math.imul)w=C;function E(q,W,z){z.negative=W.negative^q.negative,z.length=q.length+W.length;var O=0,_=0;for(var I=0;I<z.length-1;I++){var B=_;_=0;var S=O&67108863,R=Math.min(I,W.length-1);for(var Q=Math.max(0,I-q.length+1);Q<=R;Q++){var M=I-Q,k=q.words[M]|0,x=W.words[Q]|0,y=k*x,c=y&67108863;B=B+(y/67108864|0)|0,c=c+S|0,S=c&67108863,B=B+(c>>>26)|0,_+=B>>>26,B&=67108863}z.words[I]=S,O=B,B=_}if(O!==0)z.words[I]=O;else z.length--;return z.strip()}function T(q,W,z){var O=new v;return O.mulp(q,W,z)}Y.prototype.mulTo=function(W,z){var O,_=this.length+W.length;if(this.length===10&&W.length===10)O=w(this,W,z);else if(_<63)O=C(this,W,z);else if(_<1024)O=E(this,W,z);else O=T(this,W,z);return O};function v(q,W){this.x=q,this.y=W}v.prototype.makeRBT=function(W){var z=Array(W),O=Y.prototype._countBits(W)-1;for(var _=0;_<W;_++)z[_]=this.revBin(_,O,W);return z},v.prototype.revBin=function(W,z,O){if(W===0||W===O-1)return W;var _=0;for(var I=0;I<z;I++)_|=(W&1)<<z-I-1,W>>=1;return _},v.prototype.permute=function(W,z,O,_,I,B){for(var S=0;S<B;S++)_[S]=z[W[S]],I[S]=O[W[S]]},v.prototype.transform=function(W,z,O,_,I,B){this.permute(B,W,z,O,_,I);for(var S=1;S<I;S<<=1){var R=S<<1,Q=Math.cos(2*Math.PI/R),M=Math.sin(2*Math.PI/R);for(var k=0;k<I;k+=R){var x=Q,y=M;for(var c=0;c<S;c++){var i=O[k+c],e=_[k+c],V$=O[k+c+S],$0=_[k+c+S],Z0=x*V$-y*$0;if($0=x*$0+y*V$,V$=Z0,O[k+c]=i+V$,_[k+c]=e+$0,O[k+c+S]=i-V$,_[k+c+S]=e-$0,c!==R)Z0=Q*x-M*y,y=Q*y+M*x,x=Z0}}}},v.prototype.guessLen13b=function(W,z){var O=Math.max(z,W)|1,_=O&1,I=0;for(O=O/2|0;O;O=O>>>1)I++;return 1<<I+1+_},v.prototype.conjugate=function(W,z,O){if(O<=1)return;for(var _=0;_<O/2;_++){var I=W[_];W[_]=W[O-_-1],W[O-_-1]=I,I=z[_],z[_]=-z[O-_-1],z[O-_-1]=-I}},v.prototype.normalize13b=function(W,z){var O=0;for(var _=0;_<z/2;_++){var I=Math.round(W[2*_+1]/z)*8192+Math.round(W[2*_]/z)+O;if(W[_]=I&67108863,I<67108864)O=0;else O=I/67108864|0}return W},v.prototype.convert13b=function(W,z,O,_){var I=0;for(var B=0;B<z;B++)I=I+(W[B]|0),O[2*B]=I&8191,I=I>>>13,O[2*B+1]=I&8191,I=I>>>13;for(B=2*z;B<_;++B)O[B]=0;Z(I===0),Z((I&-8192)===0)},v.prototype.stub=function(W){var z=Array(W);for(var O=0;O<W;O++)z[O]=0;return z},v.prototype.mulp=function(W,z,O){var _=2*this.guessLen13b(W.length,z.length),I=this.makeRBT(_),B=this.stub(_),S=Array(_),R=Array(_),Q=Array(_),M=Array(_),k=Array(_),x=Array(_),y=O.words;y.length=_,this.convert13b(W.words,W.length,S,_),this.convert13b(z.words,z.length,M,_),this.transform(S,B,R,Q,_,I),this.transform(M,B,k,x,_,I);for(var c=0;c<_;c++){var i=R[c]*k[c]-Q[c]*x[c];Q[c]=R[c]*x[c]+Q[c]*k[c],R[c]=i}return this.conjugate(R,Q,_),this.transform(R,Q,y,B,_,I),this.conjugate(y,B,_),this.normalize13b(y,_),O.negative=W.negative^z.negative,O.length=W.length+z.length,O.strip()},Y.prototype.mul=function(W){var z=new Y(null);return z.words=Array(this.length+W.length),this.mulTo(W,z)},Y.prototype.mulf=function(W){var z=new Y(null);return z.words=Array(this.length+W.length),T(this,W,z)},Y.prototype.imul=function(W){return this.clone().mulTo(W,this)},Y.prototype.imuln=function(W){Z(typeof W==="number"),Z(W<67108864);var z=0;for(var O=0;O<this.length;O++){var _=(this.words[O]|0)*W,I=(_&67108863)+(z&67108863);z>>=26,z+=_/67108864|0,z+=I>>>26,this.words[O]=I&67108863}if(z!==0)this.words[O]=z,this.length++;return this.length=W===0?1:this.length,this},Y.prototype.muln=function(W){return this.clone().imuln(W)},Y.prototype.sqr=function(){return this.mul(this)},Y.prototype.isqr=function(){return this.imul(this.clone())},Y.prototype.pow=function(W){var z=j(W);if(z.length===0)return new Y(1);var O=this;for(var _=0;_<z.length;_++,O=O.sqr())if(z[_]!==0)break;if(++_<z.length)for(var I=O.sqr();_<z.length;_++,I=I.sqr()){if(z[_]===0)continue;O=O.mul(I)}return O},Y.prototype.iushln=function(W){Z(typeof W==="number"&&W>=0);var z=W%26,O=(W-z)/26,_=67108863>>>26-z<<26-z,I;if(z!==0){var B=0;for(I=0;I<this.length;I++){var S=this.words[I]&_,R=(this.words[I]|0)-S<<z;this.words[I]=R|B,B=S>>>26-z}if(B)this.words[I]=B,this.length++}if(O!==0){for(I=this.length-1;I>=0;I--)this.words[I+O]=this.words[I];for(I=0;I<O;I++)this.words[I]=0;this.length+=O}return this.strip()},Y.prototype.ishln=function(W){return Z(this.negative===0),this.iushln(W)},Y.prototype.iushrn=function(W,z,O){Z(typeof W==="number"&&W>=0);var _;if(z)_=(z-z%26)/26;else _=0;var I=W%26,B=Math.min((W-I)/26,this.length),S=67108863^67108863>>>I<<I,R=O;if(_-=B,_=Math.max(0,_),R){for(var Q=0;Q<B;Q++)R.words[Q]=this.words[Q];R.length=B}if(B===0);else if(this.length>B){this.length-=B;for(Q=0;Q<this.length;Q++)this.words[Q]=this.words[Q+B]}else this.words[0]=0,this.length=1;var M=0;for(Q=this.length-1;Q>=0&&(M!==0||Q>=_);Q--){var k=this.words[Q]|0;this.words[Q]=M<<26-I|k>>>I,M=k&S}if(R&&M!==0)R.words[R.length++]=M;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},Y.prototype.ishrn=function(W,z,O){return Z(this.negative===0),this.iushrn(W,z,O)},Y.prototype.shln=function(W){return this.clone().ishln(W)},Y.prototype.ushln=function(W){return this.clone().iushln(W)},Y.prototype.shrn=function(W){return this.clone().ishrn(W)},Y.prototype.ushrn=function(W){return this.clone().iushrn(W)},Y.prototype.testn=function(W){Z(typeof W==="number"&&W>=0);var z=W%26,O=(W-z)/26,_=1<<z;if(this.length<=O)return!1;var I=this.words[O];return!!(I&_)},Y.prototype.imaskn=function(W){Z(typeof W==="number"&&W>=0);var z=W%26,O=(W-z)/26;if(Z(this.negative===0,"imaskn works only with positive numbers"),this.length<=O)return this;if(z!==0)O++;if(this.length=Math.min(O,this.length),z!==0){var _=67108863^67108863>>>z<<z;this.words[this.length-1]&=_}return this.strip()},Y.prototype.maskn=function(W){return this.clone().imaskn(W)},Y.prototype.iaddn=function(W){if(Z(typeof W==="number"),Z(W<67108864),W<0)return this.isubn(-W);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<W)return this.words[0]=W-(this.words[0]|0),this.negative=0,this;return this.negative=0,this.isubn(W),this.negative=1,this}return this._iaddn(W)},Y.prototype._iaddn=function(W){this.words[0]+=W;for(var z=0;z<this.length&&this.words[z]>=67108864;z++)if(this.words[z]-=67108864,z===this.length-1)this.words[z+1]=1;else this.words[z+1]++;return this.length=Math.max(this.length,z+1),this},Y.prototype.isubn=function(W){if(Z(typeof W==="number"),Z(W<67108864),W<0)return this.iaddn(-W);if(this.negative!==0)return this.negative=0,this.iaddn(W),this.negative=1,this;if(this.words[0]-=W,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var z=0;z<this.length&&this.words[z]<0;z++)this.words[z]+=67108864,this.words[z+1]-=1;return this.strip()},Y.prototype.addn=function(W){return this.clone().iaddn(W)},Y.prototype.subn=function(W){return this.clone().isubn(W)},Y.prototype.iabs=function(){return this.negative=0,this},Y.prototype.abs=function(){return this.clone().iabs()},Y.prototype._ishlnsubmul=function(W,z,O){var _=W.length+O,I;this._expand(_);var B,S=0;for(I=0;I<W.length;I++){B=(this.words[I+O]|0)+S;var R=(W.words[I]|0)*z;B-=R&67108863,S=(B>>26)-(R/67108864|0),this.words[I+O]=B&67108863}for(;I<this.length-O;I++)B=(this.words[I+O]|0)+S,S=B>>26,this.words[I+O]=B&67108863;if(S===0)return this.strip();Z(S===-1),S=0;for(I=0;I<this.length;I++)B=-(this.words[I]|0)+S,S=B>>26,this.words[I]=B&67108863;return this.negative=1,this.strip()},Y.prototype._wordDiv=function(W,z){var O=this.length-W.length,_=this.clone(),I=W,B=I.words[I.length-1]|0,S=this._countBits(B);if(O=26-S,O!==0)I=I.ushln(O),_.iushln(O),B=I.words[I.length-1]|0;var R=_.length-I.length,Q;if(z!=="mod"){Q=new Y(null),Q.length=R+1,Q.words=Array(Q.length);for(var M=0;M<Q.length;M++)Q.words[M]=0}var k=_.clone()._ishlnsubmul(I,1,R);if(k.negative===0){if(_=k,Q)Q.words[R]=1}for(var x=R-1;x>=0;x--){var y=(_.words[I.length+x]|0)*67108864+(_.words[I.length+x-1]|0);y=Math.min(y/B|0,67108863),_._ishlnsubmul(I,y,x);while(_.negative!==0)if(y--,_.negative=0,_._ishlnsubmul(I,1,x),!_.isZero())_.negative^=1;if(Q)Q.words[x]=y}if(Q)Q.strip();if(_.strip(),z!=="div"&&O!==0)_.iushrn(O);return{div:Q||null,mod:_}},Y.prototype.divmod=function(W,z,O){if(Z(!W.isZero()),this.isZero())return{div:new Y(0),mod:new Y(0)};var _,I,B;if(this.negative!==0&&W.negative===0){if(B=this.neg().divmod(W,z),z!=="mod")_=B.div.neg();if(z!=="div"){if(I=B.mod.neg(),O&&I.negative!==0)I.iadd(W)}return{div:_,mod:I}}if(this.negative===0&&W.negative!==0){if(B=this.divmod(W.neg(),z),z!=="mod")_=B.div.neg();return{div:_,mod:B.mod}}if((this.negative&W.negative)!==0){if(B=this.neg().divmod(W.neg(),z),z!=="div"){if(I=B.mod.neg(),O&&I.negative!==0)I.isub(W)}return{div:B.div,mod:I}}if(W.length>this.length||this.cmp(W)<0)return{div:new Y(0),mod:this};if(W.length===1){if(z==="div")return{div:this.divn(W.words[0]),mod:null};if(z==="mod")return{div:null,mod:new Y(this.modn(W.words[0]))};return{div:this.divn(W.words[0]),mod:new Y(this.modn(W.words[0]))}}return this._wordDiv(W,z)},Y.prototype.div=function(W){return this.divmod(W,"div",!1).div},Y.prototype.mod=function(W){return this.divmod(W,"mod",!1).mod},Y.prototype.umod=function(W){return this.divmod(W,"mod",!0).mod},Y.prototype.divRound=function(W){var z=this.divmod(W);if(z.mod.isZero())return z.div;var O=z.div.negative!==0?z.mod.isub(W):z.mod,_=W.ushrn(1),I=W.andln(1),B=O.cmp(_);if(B<0||I===1&&B===0)return z.div;return z.div.negative!==0?z.div.isubn(1):z.div.iaddn(1)},Y.prototype.modn=function(W){Z(W<=67108863);var z=67108864%W,O=0;for(var _=this.length-1;_>=0;_--)O=(z*O+(this.words[_]|0))%W;return O},Y.prototype.idivn=function(W){Z(W<=67108863);var z=0;for(var O=this.length-1;O>=0;O--){var _=(this.words[O]|0)+z*67108864;this.words[O]=_/W|0,z=_%W}return this.strip()},Y.prototype.divn=function(W){return this.clone().idivn(W)},Y.prototype.egcd=function(W){Z(W.negative===0),Z(!W.isZero());var z=this,O=W.clone();if(z.negative!==0)z=z.umod(W);else z=z.clone();var _=new Y(1),I=new Y(0),B=new Y(0),S=new Y(1),R=0;while(z.isEven()&&O.isEven())z.iushrn(1),O.iushrn(1),++R;var Q=O.clone(),M=z.clone();while(!z.isZero()){for(var k=0,x=1;(z.words[0]&x)===0&&k<26;++k,x<<=1);if(k>0){z.iushrn(k);while(k-- >0){if(_.isOdd()||I.isOdd())_.iadd(Q),I.isub(M);_.iushrn(1),I.iushrn(1)}}for(var y=0,c=1;(O.words[0]&c)===0&&y<26;++y,c<<=1);if(y>0){O.iushrn(y);while(y-- >0){if(B.isOdd()||S.isOdd())B.iadd(Q),S.isub(M);B.iushrn(1),S.iushrn(1)}}if(z.cmp(O)>=0)z.isub(O),_.isub(B),I.isub(S);else O.isub(z),B.isub(_),S.isub(I)}return{a:B,b:S,gcd:O.iushln(R)}},Y.prototype._invmp=function(W){Z(W.negative===0),Z(!W.isZero());var z=this,O=W.clone();if(z.negative!==0)z=z.umod(W);else z=z.clone();var _=new Y(1),I=new Y(0),B=O.clone();while(z.cmpn(1)>0&&O.cmpn(1)>0){for(var S=0,R=1;(z.words[0]&R)===0&&S<26;++S,R<<=1);if(S>0){z.iushrn(S);while(S-- >0){if(_.isOdd())_.iadd(B);_.iushrn(1)}}for(var Q=0,M=1;(O.words[0]&M)===0&&Q<26;++Q,M<<=1);if(Q>0){O.iushrn(Q);while(Q-- >0){if(I.isOdd())I.iadd(B);I.iushrn(1)}}if(z.cmp(O)>=0)z.isub(O),_.isub(I);else O.isub(z),I.isub(_)}var k;if(z.cmpn(1)===0)k=_;else k=I;if(k.cmpn(0)<0)k.iadd(W);return k},Y.prototype.gcd=function(W){if(this.isZero())return W.abs();if(W.isZero())return this.abs();var z=this.clone(),O=W.clone();z.negative=0,O.negative=0;for(var _=0;z.isEven()&&O.isEven();_++)z.iushrn(1),O.iushrn(1);do{while(z.isEven())z.iushrn(1);while(O.isEven())O.iushrn(1);var I=z.cmp(O);if(I<0){var B=z;z=O,O=B}else if(I===0||O.cmpn(1)===0)break;z.isub(O)}while(!0);return O.iushln(_)},Y.prototype.invm=function(W){return this.egcd(W).a.umod(W)},Y.prototype.isEven=function(){return(this.words[0]&1)===0},Y.prototype.isOdd=function(){return(this.words[0]&1)===1},Y.prototype.andln=function(W){return this.words[0]&W},Y.prototype.bincn=function(W){Z(typeof W==="number");var z=W%26,O=(W-z)/26,_=1<<z;if(this.length<=O)return this._expand(O+1),this.words[O]|=_,this;var I=_;for(var B=O;I!==0&&B<this.length;B++){var S=this.words[B]|0;S+=I,I=S>>>26,S&=67108863,this.words[B]=S}if(I!==0)this.words[B]=I,this.length++;return this},Y.prototype.isZero=function(){return this.length===1&&this.words[0]===0},Y.prototype.cmpn=function(W){var z=W<0;if(this.negative!==0&&!z)return-1;if(this.negative===0&&z)return 1;this.strip();var O;if(this.length>1)O=1;else{if(z)W=-W;Z(W<=67108863,"Number is too big");var _=this.words[0]|0;O=_===W?0:_<W?-1:1}if(this.negative!==0)return-O|0;return O},Y.prototype.cmp=function(W){if(this.negative!==0&&W.negative===0)return-1;if(this.negative===0&&W.negative!==0)return 1;var z=this.ucmp(W);if(this.negative!==0)return-z|0;return z},Y.prototype.ucmp=function(W){if(this.length>W.length)return 1;if(this.length<W.length)return-1;var z=0;for(var O=this.length-1;O>=0;O--){var _=this.words[O]|0,I=W.words[O]|0;if(_===I)continue;if(_<I)z=-1;else if(_>I)z=1;break}return z},Y.prototype.gtn=function(W){return this.cmpn(W)===1},Y.prototype.gt=function(W){return this.cmp(W)===1},Y.prototype.gten=function(W){return this.cmpn(W)>=0},Y.prototype.gte=function(W){return this.cmp(W)>=0},Y.prototype.ltn=function(W){return this.cmpn(W)===-1},Y.prototype.lt=function(W){return this.cmp(W)===-1},Y.prototype.lten=function(W){return this.cmpn(W)<=0},Y.prototype.lte=function(W){return this.cmp(W)<=0},Y.prototype.eqn=function(W){return this.cmpn(W)===0},Y.prototype.eq=function(W){return this.cmp(W)===0},Y.red=function(W){return new r(W)},Y.prototype.toRed=function(W){return Z(!this.red,"Already a number in reduction context"),Z(this.negative===0,"red works only with positives"),W.convertTo(this)._forceRed(W)},Y.prototype.fromRed=function(){return Z(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},Y.prototype._forceRed=function(W){return this.red=W,this},Y.prototype.forceRed=function(W){return Z(!this.red,"Already a number in reduction context"),this._forceRed(W)},Y.prototype.redAdd=function(W){return Z(this.red,"redAdd works only with red numbers"),this.red.add(this,W)},Y.prototype.redIAdd=function(W){return Z(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,W)},Y.prototype.redSub=function(W){return Z(this.red,"redSub works only with red numbers"),this.red.sub(this,W)},Y.prototype.redISub=function(W){return Z(this.red,"redISub works only with red numbers"),this.red.isub(this,W)},Y.prototype.redShl=function(W){return Z(this.red,"redShl works only with red numbers"),this.red.shl(this,W)},Y.prototype.redMul=function(W){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,W),this.red.mul(this,W)},Y.prototype.redIMul=function(W){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,W),this.red.imul(this,W)},Y.prototype.redSqr=function(){return Z(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},Y.prototype.redISqr=function(){return Z(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},Y.prototype.redSqrt=function(){return Z(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},Y.prototype.redInvm=function(){return Z(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},Y.prototype.redNeg=function(){return Z(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},Y.prototype.redPow=function(W){return Z(this.red&&!W.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,W)};var L={k256:null,p224:null,p192:null,p25519:null};function D(q,W){this.name=q,this.p=new Y(W,16),this.n=this.p.bitLength(),this.k=new Y(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}D.prototype._tmp=function(){var W=new Y(null);return W.words=Array(Math.ceil(this.n/13)),W},D.prototype.ireduce=function(W){var z=W,O;do this.split(z,this.tmp),z=this.imulK(z),z=z.iadd(this.tmp),O=z.bitLength();while(O>this.n);var _=O<this.n?-1:z.ucmp(this.p);if(_===0)z.words[0]=0,z.length=1;else if(_>0)z.isub(this.p);else if(z.strip!==void 0)z.strip();else z._strip();return z},D.prototype.split=function(W,z){W.iushrn(this.n,0,z)},D.prototype.imulK=function(W){return W.imul(this.k)};function g(){D.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}X(g,D),g.prototype.split=function(W,z){var O=4194303,_=Math.min(W.length,9);for(var I=0;I<_;I++)z.words[I]=W.words[I];if(z.length=_,W.length<=9){W.words[0]=0,W.length=1;return}var B=W.words[9];z.words[z.length++]=B&O;for(I=10;I<W.length;I++){var S=W.words[I]|0;W.words[I-10]=(S&O)<<4|B>>>22,B=S}if(B>>>=22,W.words[I-10]=B,B===0&&W.length>10)W.length-=10;else W.length-=9},g.prototype.imulK=function(W){W.words[W.length]=0,W.words[W.length+1]=0,W.length+=2;var z=0;for(var O=0;O<W.length;O++){var _=W.words[O]|0;z+=_*977,W.words[O]=z&67108863,z=_*64+(z/67108864|0)}if(W.words[W.length-1]===0){if(W.length--,W.words[W.length-1]===0)W.length--}return W};function N(){D.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}X(N,D);function f(){D.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}X(f,D);function l(){D.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}X(l,D),l.prototype.imulK=function(W){var z=0;for(var O=0;O<W.length;O++){var _=(W.words[O]|0)*19+z,I=_&67108863;_>>>=26,W.words[O]=I,z=_}if(z!==0)W.words[W.length++]=z;return W},Y._prime=function(W){if(L[W])return L[W];var z;if(W==="k256")z=new g;else if(W==="p224")z=new N;else if(W==="p192")z=new f;else if(W==="p25519")z=new l;else throw Error("Unknown prime "+W);return L[W]=z,z};function r(q){if(typeof q==="string"){var W=Y._prime(q);this.m=W.p,this.prime=W}else Z(q.gtn(1),"modulus must be greater than 1"),this.m=q,this.prime=null}r.prototype._verify1=function(W){Z(W.negative===0,"red works only with positives"),Z(W.red,"red works only with red numbers")},r.prototype._verify2=function(W,z){Z((W.negative|z.negative)===0,"red works only with positives"),Z(W.red&&W.red===z.red,"red works only with red numbers")},r.prototype.imod=function(W){if(this.prime)return this.prime.ireduce(W)._forceRed(this);return W.umod(this.m)._forceRed(this)},r.prototype.neg=function(W){if(W.isZero())return W.clone();return this.m.sub(W)._forceRed(this)},r.prototype.add=function(W,z){this._verify2(W,z);var O=W.add(z);if(O.cmp(this.m)>=0)O.isub(this.m);return O._forceRed(this)},r.prototype.iadd=function(W,z){this._verify2(W,z);var O=W.iadd(z);if(O.cmp(this.m)>=0)O.isub(this.m);return O},r.prototype.sub=function(W,z){this._verify2(W,z);var O=W.sub(z);if(O.cmpn(0)<0)O.iadd(this.m);return O._forceRed(this)},r.prototype.isub=function(W,z){this._verify2(W,z);var O=W.isub(z);if(O.cmpn(0)<0)O.iadd(this.m);return O},r.prototype.shl=function(W,z){return this._verify1(W),this.imod(W.ushln(z))},r.prototype.imul=function(W,z){return this._verify2(W,z),this.imod(W.imul(z))},r.prototype.mul=function(W,z){return this._verify2(W,z),this.imod(W.mul(z))},r.prototype.isqr=function(W){return this.imul(W,W.clone())},r.prototype.sqr=function(W){return this.mul(W,W)},r.prototype.sqrt=function(W){if(W.isZero())return W.clone();var z=this.m.andln(3);if(Z(z%2===1),z===3){var O=this.m.add(new Y(1)).iushrn(2);return this.pow(W,O)}var _=this.m.subn(1),I=0;while(!_.isZero()&&_.andln(1)===0)I++,_.iushrn(1);Z(!_.isZero());var B=new Y(1).toRed(this),S=B.redNeg(),R=this.m.subn(1).iushrn(1),Q=this.m.bitLength();Q=new Y(2*Q*Q).toRed(this);while(this.pow(Q,R).cmp(S)!==0)Q.redIAdd(S);var M=this.pow(Q,_),k=this.pow(W,_.addn(1).iushrn(1)),x=this.pow(W,_),y=I;while(x.cmp(B)!==0){var c=x;for(var i=0;c.cmp(B)!==0;i++)c=c.redSqr();Z(i<y);var e=this.pow(M,new Y(1).iushln(y-i-1));k=k.redMul(e),M=e.redSqr(),x=x.redMul(M),y=i}return k},r.prototype.invm=function(W){var z=W._invmp(this.m);if(z.negative!==0)return z.negative=0,this.imod(z).redNeg();else return this.imod(z)},r.prototype.pow=function(W,z){if(z.isZero())return new Y(1).toRed(this);if(z.cmpn(1)===0)return W.clone();var O=4,_=Array(1<<O);_[0]=new Y(1).toRed(this),_[1]=W;for(var I=2;I<_.length;I++)_[I]=this.mul(_[I-1],W);var B=_[0],S=0,R=0,Q=z.bitLength()%26;if(Q===0)Q=26;for(I=z.length-1;I>=0;I--){var M=z.words[I];for(var k=Q-1;k>=0;k--){var x=M>>k&1;if(B!==_[0])B=this.sqr(B);if(x===0&&S===0){R=0;continue}if(S<<=1,S|=x,R++,R!==O&&(I!==0||k!==0))continue;B=this.mul(B,_[S]),R=0,S=0}Q=26}return B},r.prototype.convertTo=function(W){var z=W.umod(this.m);return z===W?z.clone():z},r.prototype.convertFrom=function(W){var z=W.clone();return z.red=null,z},Y.mont=function(W){return new u0(W)};function u0(q){if(r.call(this,q),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new Y(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}X(u0,r),u0.prototype.convertTo=function(W){return this.imod(W.ushln(this.shift))},u0.prototype.convertFrom=function(W){var z=this.imod(W.mul(this.rinv));return z.red=null,z},u0.prototype.imul=function(W,z){if(W.isZero()||z.isZero())return W.words[0]=0,W.length=1,W;var O=W.imul(z),_=O.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=O.isub(_).iushrn(this.shift),B=I;if(I.cmp(this.m)>=0)B=I.isub(this.m);else if(I.cmpn(0)<0)B=I.iadd(this.m);return B._forceRed(this)},u0.prototype.mul=function(W,z){if(W.isZero()||z.isZero())return new Y(0)._forceRed(this);var O=W.mul(z),_=O.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=O.isub(_).iushrn(this.shift),B=I;if(I.cmp(this.m)>=0)B=I.isub(this.m);else if(I.cmpn(0)<0)B=I.iadd(this.m);return B._forceRed(this)},u0.prototype.invm=function(W){var z=this.imod(W._invmp(this.m).mul(this.r2));return z._forceRed(this)}})(typeof FX>"u"||FX,_H)});var FH=o((M7,RX)=>{if(typeof Object.create==="function")RX.exports=function(J,Z){if(Z)J.super_=Z,J.prototype=Object.create(Z.prototype,{constructor:{value:J,enumerable:!1,writable:!0,configurable:!0}})};else RX.exports=function(J,Z){if(Z){J.super_=Z;var X=function(){};X.prototype=Z.prototype,J.prototype=new X,J.prototype.constructor=J}}});var I$=o((I7,MX)=>{try{if(mJ=K$("util"),typeof mJ.inherits!=="function")throw"";MX.exports=mJ.inherits}catch($){MX.exports=FH()}var mJ});var nJ=o((q7,AH)=>{var dJ=K$("buffer"),u$=dJ.Buffer,i0={},t0;for(t0 in dJ){if(!dJ.hasOwnProperty(t0))continue;if(t0==="SlowBuffer"||t0==="Buffer")continue;i0[t0]=dJ[t0]}var m$=i0.Buffer={};for(t0 in u$){if(!u$.hasOwnProperty(t0))continue;if(t0==="allocUnsafe"||t0==="allocUnsafeSlow")continue;m$[t0]=u$[t0]}i0.Buffer.prototype=u$.prototype;if(!m$.from||m$.from===Uint8Array.from)m$.from=function($,J,Z){if(typeof $==="number")throw TypeError('The "value" argument must not be of type number. Received type '+typeof $);if($&&typeof $.length>"u")throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof $);return u$($,J,Z)};if(!m$.alloc)m$.alloc=function($,J,Z){if(typeof $!=="number")throw TypeError('The "size" argument must be of type number. Received type '+typeof $);if($<0||$>=2147483648)throw RangeError('The value "'+$+'" is invalid for option "size"');var X=u$($);if(!J||J.length===0)X.fill(0);else if(typeof Z==="string")X.fill(J,Z);else X.fill(J);return X};if(!i0.kStringMaxLength)try{i0.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch($){}if(!i0.constants){if(i0.constants={MAX_LENGTH:i0.kMaxLength},i0.kStringMaxLength)i0.constants.MAX_STRING_LENGTH=i0.kStringMaxLength}AH.exports=i0});var oJ=o((L6)=>{var w6=I$();function a0($){this._reporterState={obj:null,path:[],options:$||{},errors:[]}}L6.Reporter=a0;a0.prototype.isError=function(J){return J instanceof d$};a0.prototype.save=function(){let J=this._reporterState;return{obj:J.obj,pathLen:J.path.length}};a0.prototype.restore=function(J){let Z=this._reporterState;Z.obj=J.obj,Z.path=Z.path.slice(0,J.pathLen)};a0.prototype.enterKey=function(J){return this._reporterState.path.push(J)};a0.prototype.exitKey=function(J){let Z=this._reporterState;Z.path=Z.path.slice(0,J-1)};a0.prototype.leaveKey=function(J,Z,X){let Y=this._reporterState;if(this.exitKey(J),Y.obj!==null)Y.obj[Z]=X};a0.prototype.path=function(){return this._reporterState.path.join("/")};a0.prototype.enterObject=function(){let J=this._reporterState,Z=J.obj;return J.obj={},Z};a0.prototype.leaveObject=function(J){let Z=this._reporterState,X=Z.obj;return Z.obj=J,X};a0.prototype.error=function(J){let Z,X=this._reporterState,Y=J instanceof d$;if(Y)Z=J;else Z=new d$(X.path.map(function(H){return"["+JSON.stringify(H)+"]"}).join(""),J.message||J,J.stack);if(!X.options.partial)throw Z;if(!Y)X.errors.push(Z);return Z};a0.prototype.wrapResult=function(J){let Z=this._reporterState;if(!Z.options.partial)return J;return{result:this.isError(J)?null:J,errors:Z.errors}};function d$($,J){this.path=$,this.rethrow(J)}w6(d$,Error);d$.prototype.rethrow=function(J){if(this.message=J+" at: "+(this.path||"(shallow)"),Error.captureStackTrace)Error.captureStackTrace(this,d$);if(!this.stack)try{throw Error(this.message)}catch(Z){this.stack=Z.stack}return this}});var s$=o((N6)=>{var T6=I$(),sJ=oJ().Reporter,n$=nJ().Buffer;function e0($,J){if(sJ.call(this,J),!n$.isBuffer($)){this.error("Input not Buffer");return}this.base=$,this.offset=0,this.length=$.length}T6(e0,sJ);N6.DecoderBuffer=e0;e0.isDecoderBuffer=function(J){if(J instanceof e0)return!0;return typeof J==="object"&&n$.isBuffer(J.base)&&J.constructor.name==="DecoderBuffer"&&typeof J.offset==="number"&&typeof J.length==="number"&&typeof J.save==="function"&&typeof J.restore==="function"&&typeof J.isEmpty==="function"&&typeof J.readUInt8==="function"&&typeof J.skip==="function"&&typeof J.raw==="function"};e0.prototype.save=function(){return{offset:this.offset,reporter:sJ.prototype.save.call(this)}};e0.prototype.restore=function(J){let Z=new e0(this.base);return Z.offset=J.offset,Z.length=this.offset,this.offset=J.offset,sJ.prototype.restore.call(this,J.reporter),Z};e0.prototype.isEmpty=function(){return this.offset===this.length};e0.prototype.readUInt8=function(J){if(this.offset+1<=this.length)return this.base.readUInt8(this.offset++,!0);else return this.error(J||"DecoderBuffer overrun")};e0.prototype.skip=function(J,Z){if(!(this.offset+J<=this.length))return this.error(Z||"DecoderBuffer overrun");let X=new e0(this.base);return X._reporterState=this._reporterState,X.offset=this.offset,X.length=this.offset+J,this.offset+=J,X};e0.prototype.raw=function(J){return this.base.slice(J?J.offset:this.offset,this.length)};function o$($,J){if(Array.isArray($))this.length=0,this.value=$.map(function(Z){if(!o$.isEncoderBuffer(Z))Z=new o$(Z,J);return this.length+=Z.length,Z},this);else if(typeof $==="number"){if(!(0<=$&&$<=255))return J.error("non-byte EncoderBuffer value");this.value=$,this.length=1}else if(typeof $==="string")this.value=$,this.length=n$.byteLength($);else if(n$.isBuffer($))this.value=$,this.length=$.length;else return J.error("Unsupported type: "+typeof $)}N6.EncoderBuffer=o$;o$.isEncoderBuffer=function(J){if(J instanceof o$)return!0;return typeof J==="object"&&J.constructor.name==="EncoderBuffer"&&typeof J.length==="number"&&typeof J.join==="function"};o$.prototype.join=function(J,Z){if(!J)J=n$.alloc(this.length);if(!Z)Z=0;if(this.length===0)return J;if(Array.isArray(this.value))this.value.forEach(function(X){X.join(J,Z),Z+=X.length});else{if(typeof this.value==="number")J[Z]=this.value;else if(typeof this.value==="string")J.write(this.value,Z);else if(n$.isBuffer(this.value))this.value.copy(J,Z);Z+=this.length}return J}});var IH=o((j7,MH)=>{MH.exports=RH;function RH($,J){if(!$)throw Error(J||"Assertion failed")}RH.equal=function(J,Z,X){if(J!=Z)throw Error(X||"Assertion failed: "+J+" != "+Z)}});var lJ=o((C7,PH)=>{var k6=oJ().Reporter,x6=s$().EncoderBuffer,y6=s$().DecoderBuffer,o0=IH(),qH=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],f6=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(qH),h6=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function t($,J,Z){let X={};if(this._baseState=X,X.name=Z,X.enc=$,X.parent=J||null,X.children=null,X.tag=null,X.args=null,X.reverseArgs=null,X.choice=null,X.optional=!1,X.any=!1,X.obj=!1,X.use=null,X.useDecoder=null,X.key=null,X.default=null,X.explicit=null,X.implicit=null,X.contains=null,!X.parent)X.children=[],this._wrap()}PH.exports=t;var g6=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];t.prototype.clone=function(){let J=this._baseState,Z={};g6.forEach(function(Y){Z[Y]=J[Y]});let X=new this.constructor(Z.parent);return X._baseState=Z,X};t.prototype._wrap=function(){let J=this._baseState;f6.forEach(function(Z){this[Z]=function(){let Y=new this.constructor(this);return J.children.push(Y),Y[Z].apply(Y,arguments)}},this)};t.prototype._init=function(J){let Z=this._baseState;o0(Z.parent===null),J.call(this),Z.children=Z.children.filter(function(X){return X._baseState.parent===this},this),o0.equal(Z.children.length,1,"Root node can have only one child")};t.prototype._useArgs=function(J){let Z=this._baseState,X=J.filter(function(Y){return Y instanceof this.constructor},this);if(J=J.filter(function(Y){return!(Y instanceof this.constructor)},this),X.length!==0)o0(Z.children===null),Z.children=X,X.forEach(function(Y){Y._baseState.parent=this},this);if(J.length!==0)o0(Z.args===null),Z.args=J,Z.reverseArgs=J.map(function(Y){if(typeof Y!=="object"||Y.constructor!==Object)return Y;let H={};return Object.keys(Y).forEach(function(G){if(G==(G|0))G|=0;let U=Y[G];H[U]=G}),H})};h6.forEach(function($){t.prototype[$]=function(){let Z=this._baseState;throw Error($+" not implemented for encoding: "+Z.enc)}});qH.forEach(function($){t.prototype[$]=function(){let Z=this._baseState,X=Array.prototype.slice.call(arguments);return o0(Z.tag===null),Z.tag=$,this._useArgs(X),this}});t.prototype.use=function(J){o0(J);let Z=this._baseState;return o0(Z.use===null),Z.use=J,this};t.prototype.optional=function(){let J=this._baseState;return J.optional=!0,this};t.prototype.def=function(J){let Z=this._baseState;return o0(Z.default===null),Z.default=J,Z.optional=!0,this};t.prototype.explicit=function(J){let Z=this._baseState;return o0(Z.explicit===null&&Z.implicit===null),Z.explicit=J,this};t.prototype.implicit=function(J){let Z=this._baseState;return o0(Z.explicit===null&&Z.implicit===null),Z.implicit=J,this};t.prototype.obj=function(){let J=this._baseState,Z=Array.prototype.slice.call(arguments);if(J.obj=!0,Z.length!==0)this._useArgs(Z);return this};t.prototype.key=function(J){let Z=this._baseState;return o0(Z.key===null),Z.key=J,this};t.prototype.any=function(){let J=this._baseState;return J.any=!0,this};t.prototype.choice=function(J){let Z=this._baseState;return o0(Z.choice===null),Z.choice=J,this._useArgs(Object.keys(J).map(function(X){return J[X]})),this};t.prototype.contains=function(J){let Z=this._baseState;return o0(Z.use===null),Z.contains=J,this};t.prototype._decode=function(J,Z){let X=this._baseState;if(X.parent===null)return J.wrapResult(X.children[0]._decode(J,Z));let Y=X.default,H=!0,G=null;if(X.key!==null)G=J.enterKey(X.key);if(X.optional){let V=null;if(X.explicit!==null)V=X.explicit;else if(X.implicit!==null)V=X.implicit;else if(X.tag!==null)V=X.tag;if(V===null&&!X.any){let K=J.save();try{if(X.choice===null)this._decodeGeneric(X.tag,J,Z);else this._decodeChoice(J,Z);H=!0}catch(F){H=!1}J.restore(K)}else if(H=this._peekTag(J,V,X.any),J.isError(H))return H}let U;if(X.obj&&H)U=J.enterObject();if(H){if(X.explicit!==null){let K=this._decodeTag(J,X.explicit);if(J.isError(K))return K;J=K}let V=J.offset;if(X.use===null&&X.choice===null){let K;if(X.any)K=J.save();let F=this._decodeTag(J,X.implicit!==null?X.implicit:X.tag,X.any);if(J.isError(F))return F;if(X.any)Y=J.raw(K);else J=F}if(Z&&Z.track&&X.tag!==null)Z.track(J.path(),V,J.length,"tagged");if(Z&&Z.track&&X.tag!==null)Z.track(J.path(),J.offset,J.length,"content");if(X.any);else if(X.choice===null)Y=this._decodeGeneric(X.tag,J,Z);else Y=this._decodeChoice(J,Z);if(J.isError(Y))return Y;if(!X.any&&X.choice===null&&X.children!==null)X.children.forEach(function(F){F._decode(J,Z)});if(X.contains&&(X.tag==="octstr"||X.tag==="bitstr")){let K=new y6(Y);Y=this._getUse(X.contains,J._reporterState.obj)._decode(K,Z)}}if(X.obj&&H)Y=J.leaveObject(U);if(X.key!==null&&(Y!==null||H===!0))J.leaveKey(G,X.key,Y);else if(G!==null)J.exitKey(G);return Y};t.prototype._decodeGeneric=function(J,Z,X){let Y=this._baseState;if(J==="seq"||J==="set")return null;if(J==="seqof"||J==="setof")return this._decodeList(Z,J,Y.args[0],X);else if(/str$/.test(J))return this._decodeStr(Z,J,X);else if(J==="objid"&&Y.args)return this._decodeObjid(Z,Y.args[0],Y.args[1],X);else if(J==="objid")return this._decodeObjid(Z,null,null,X);else if(J==="gentime"||J==="utctime")return this._decodeTime(Z,J,X);else if(J==="null_")return this._decodeNull(Z,X);else if(J==="bool")return this._decodeBool(Z,X);else if(J==="objDesc")return this._decodeStr(Z,J,X);else if(J==="int"||J==="enum")return this._decodeInt(Z,Y.args&&Y.args[0],X);if(Y.use!==null)return this._getUse(Y.use,Z._reporterState.obj)._decode(Z,X);else return Z.error("unknown tag: "+J)};t.prototype._getUse=function(J,Z){let X=this._baseState;if(X.useDecoder=this._use(J,Z),o0(X.useDecoder._baseState.parent===null),X.useDecoder=X.useDecoder._baseState.children[0],X.implicit!==X.useDecoder._baseState.implicit)X.useDecoder=X.useDecoder.clone(),X.useDecoder._baseState.implicit=X.implicit;return X.useDecoder};t.prototype._decodeChoice=function(J,Z){let X=this._baseState,Y=null,H=!1;if(Object.keys(X.choice).some(function(G){let U=J.save(),V=X.choice[G];try{let K=V._decode(J,Z);if(J.isError(K))return!1;Y={type:G,value:K},H=!0}catch(K){return J.restore(U),!1}return!0},this),!H)return J.error("Choice not matched");return Y};t.prototype._createEncoderBuffer=function(J){return new x6(J,this.reporter)};t.prototype._encode=function(J,Z,X){let Y=this._baseState;if(Y.default!==null&&Y.default===J)return;let H=this._encodeValue(J,Z,X);if(H===void 0)return;if(this._skipDefault(H,Z,X))return;return H};t.prototype._encodeValue=function(J,Z,X){let Y=this._baseState;if(Y.parent===null)return Y.children[0]._encode(J,Z||new k6);let H=null;if(this.reporter=Z,Y.optional&&J===void 0)if(Y.default!==null)J=Y.default;else return;let G=null,U=!1;if(Y.any)H=this._createEncoderBuffer(J);else if(Y.choice)H=this._encodeChoice(J,Z);else if(Y.contains)G=this._getUse(Y.contains,X)._encode(J,Z),U=!0;else if(Y.children)G=Y.children.map(function(V){if(V._baseState.tag==="null_")return V._encode(null,Z,J);if(V._baseState.key===null)return Z.error("Child should have a key");let K=Z.enterKey(V._baseState.key);if(typeof J!=="object")return Z.error("Child expected, but input is not object");let F=V._encode(J[V._baseState.key],Z,J);return Z.leaveKey(K),F},this).filter(function(V){return V}),G=this._createEncoderBuffer(G);else if(Y.tag==="seqof"||Y.tag==="setof"){if(!(Y.args&&Y.args.length===1))return Z.error("Too many args for : "+Y.tag);if(!Array.isArray(J))return Z.error("seqof/setof, but data is not Array");let V=this.clone();V._baseState.implicit=null,G=this._createEncoderBuffer(J.map(function(K){let F=this._baseState;return this._getUse(F.args[0],J)._encode(K,Z)},V))}else if(Y.use!==null)H=this._getUse(Y.use,X)._encode(J,Z);else G=this._encodePrimitive(Y.tag,J),U=!0;if(!Y.any&&Y.choice===null){let V=Y.implicit!==null?Y.implicit:Y.tag,K=Y.implicit===null?"universal":"context";if(V===null){if(Y.use===null)Z.error("Tag could be omitted only for .use()")}else if(Y.use===null)H=this._encodeComposite(V,U,K,G)}if(Y.explicit!==null)H=this._encodeComposite(Y.explicit,!1,"context",H);return H};t.prototype._encodeChoice=function(J,Z){let X=this._baseState,Y=X.choice[J.type];if(!Y)o0(!1,J.type+" not found in "+JSON.stringify(Object.keys(X.choice)));return Y._encode(J.value,Z)};t.prototype._encodePrimitive=function(J,Z){let X=this._baseState;if(/str$/.test(J))return this._encodeStr(Z,J);else if(J==="objid"&&X.args)return this._encodeObjid(Z,X.reverseArgs[0],X.args[1]);else if(J==="objid")return this._encodeObjid(Z,null,null);else if(J==="gentime"||J==="utctime")return this._encodeTime(Z,J);else if(J==="null_")return this._encodeNull();else if(J==="int"||J==="enum")return this._encodeInt(Z,X.args&&X.reverseArgs[0]);else if(J==="bool")return this._encodeBool(Z);else if(J==="objDesc")return this._encodeStr(Z,J);else throw Error("Unsupported tag: "+J)};t.prototype._isNumstr=function(J){return/^[0-9 ]*$/.test(J)};t.prototype._isPrintstr=function(J){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(J)}});var rJ=o((b6)=>{function BH($){let J={};return Object.keys($).forEach(function(Z){if((Z|0)==Z)Z=Z|0;let X=$[Z];J[X]=Z}),J}b6.tagClass={0:"universal",1:"application",2:"context",3:"private"};b6.tagClassByName=BH(b6.tagClass);b6.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"};b6.tagByName=BH(b6.tag)});var qX=o((w7,LH)=>{var u6=I$(),z$=nJ().Buffer,SH=lJ(),IX=rJ();function wH($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new Y$,this.tree._init($.body)}LH.exports=wH;wH.prototype.encode=function(J,Z){return this.tree._encode(J,Z).join()};function Y$($){SH.call(this,"der",$)}u6(Y$,SH);Y$.prototype._encodeComposite=function(J,Z,X,Y){let H=m6(J,Z,X,this.reporter);if(Y.length<128){let V=z$.alloc(2);return V[0]=H,V[1]=Y.length,this._createEncoderBuffer([V,Y])}let G=1;for(let V=Y.length;V>=256;V>>=8)G++;let U=z$.alloc(2+G);U[0]=H,U[1]=128|G;for(let V=1+G,K=Y.length;K>0;V--,K>>=8)U[V]=K&255;return this._createEncoderBuffer([U,Y])};Y$.prototype._encodeStr=function(J,Z){if(Z==="bitstr")return this._createEncoderBuffer([J.unused|0,J.data]);else if(Z==="bmpstr"){let X=z$.alloc(J.length*2);for(let Y=0;Y<J.length;Y++)X.writeUInt16BE(J.charCodeAt(Y),Y*2);return this._createEncoderBuffer(X)}else if(Z==="numstr"){if(!this._isNumstr(J))return this.reporter.error("Encoding of string type: numstr supports only digits and space");return this._createEncoderBuffer(J)}else if(Z==="printstr"){if(!this._isPrintstr(J))return this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");return this._createEncoderBuffer(J)}else if(/str$/.test(Z))return this._createEncoderBuffer(J);else if(Z==="objDesc")return this._createEncoderBuffer(J);else return this.reporter.error("Encoding of string type: "+Z+" unsupported")};Y$.prototype._encodeObjid=function(J,Z,X){if(typeof J==="string"){if(!Z)return this.reporter.error("string objid given, but no values map found");if(!Z.hasOwnProperty(J))return this.reporter.error("objid not found in values map");J=Z[J].split(/[\s.]+/g);for(let U=0;U<J.length;U++)J[U]|=0}else if(Array.isArray(J)){J=J.slice();for(let U=0;U<J.length;U++)J[U]|=0}if(!Array.isArray(J))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(J));if(!X){if(J[1]>=40)return this.reporter.error("Second objid identifier OOB");J.splice(0,2,J[0]*40+J[1])}let Y=0;for(let U=0;U<J.length;U++){let V=J[U];for(Y++;V>=128;V>>=7)Y++}let H=z$.alloc(Y),G=H.length-1;for(let U=J.length-1;U>=0;U--){let V=J[U];H[G--]=V&127;while((V>>=7)>0)H[G--]=128|V&127}return this._createEncoderBuffer(H)};function $$($){if($<10)return"0"+$;else return $}Y$.prototype._encodeTime=function(J,Z){let X,Y=new Date(J);if(Z==="gentime")X=[$$(Y.getUTCFullYear()),$$(Y.getUTCMonth()+1),$$(Y.getUTCDate()),$$(Y.getUTCHours()),$$(Y.getUTCMinutes()),$$(Y.getUTCSeconds()),"Z"].join("");else if(Z==="utctime")X=[$$(Y.getUTCFullYear()%100),$$(Y.getUTCMonth()+1),$$(Y.getUTCDate()),$$(Y.getUTCHours()),$$(Y.getUTCMinutes()),$$(Y.getUTCSeconds()),"Z"].join("");else this.reporter.error("Encoding "+Z+" time is not supported yet");return this._encodeStr(X,"octstr")};Y$.prototype._encodeNull=function(){return this._createEncoderBuffer("")};Y$.prototype._encodeInt=function(J,Z){if(typeof J==="string"){if(!Z)return this.reporter.error("String int or enum given, but no values map");if(!Z.hasOwnProperty(J))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(J));J=Z[J]}if(typeof J!=="number"&&!z$.isBuffer(J)){let H=J.toArray();if(!J.sign&&H[0]&128)H.unshift(0);J=z$.from(H)}if(z$.isBuffer(J)){let H=J.length;if(J.length===0)H++;let G=z$.alloc(H);if(J.copy(G),J.length===0)G[0]=0;return this._createEncoderBuffer(G)}if(J<128)return this._createEncoderBuffer(J);if(J<256)return this._createEncoderBuffer([0,J]);let X=1;for(let H=J;H>=256;H>>=8)X++;let Y=Array(X);for(let H=Y.length-1;H>=0;H--)Y[H]=J&255,J>>=8;if(Y[0]&128)Y.unshift(0);return this._createEncoderBuffer(z$.from(Y))};Y$.prototype._encodeBool=function(J){return this._createEncoderBuffer(J?255:0)};Y$.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getEncoder("der").tree};Y$.prototype._skipDefault=function(J,Z,X){let Y=this._baseState,H;if(Y.default===null)return!1;let G=J.join();if(Y.defaultBuffer===void 0)Y.defaultBuffer=this._encodeValue(Y.default,Z,X).join();if(G.length!==Y.defaultBuffer.length)return!1;for(H=0;H<G.length;H++)if(G[H]!==Y.defaultBuffer[H])return!1;return!0};function m6($,J,Z,X){let Y;if($==="seqof")$="seq";else if($==="setof")$="set";if(IX.tagByName.hasOwnProperty($))Y=IX.tagByName[$];else if(typeof $==="number"&&($|0)===$)Y=$;else return X.error("Unknown tag: "+$);if(Y>=31)return X.error("Multi-octet tag encoding unsupported");if(!J)Y|=32;return Y|=IX.tagClassByName[Z||"universal"]<<6,Y}});var TH=o((L7,EH)=>{var d6=I$(),PX=qX();function BX($){PX.call(this,$),this.enc="pem"}d6(BX,PX);EH.exports=BX;BX.prototype.encode=function(J,Z){let Y=PX.prototype.encode.call(this,J).toString("base64"),H=["-----BEGIN "+Z.label+"-----"];for(let G=0;G<Y.length;G+=64)H.push(Y.slice(G,G+64));return H.push("-----END "+Z.label+"-----"),H.join(`
|
|
9
|
+
`)}});var jX=o((vH)=>{var NH=vH;NH.der=qX();NH.pem=TH()});var SX=o((T7,hH)=>{var n6=I$(),o6=AX(),DH=s$().DecoderBuffer,xH=lJ(),kH=rJ();function yH($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new l0,this.tree._init($.body)}hH.exports=yH;yH.prototype.decode=function(J,Z){if(!DH.isDecoderBuffer(J))J=new DH(J,Z);return this.tree._decode(J,Z)};function l0($){xH.call(this,"der",$)}n6(l0,xH);l0.prototype._peekTag=function(J,Z,X){if(J.isEmpty())return!1;let Y=J.save(),H=CX(J,'Failed to peek tag: "'+Z+'"');if(J.isError(H))return H;return J.restore(Y),H.tag===Z||H.tagStr===Z||H.tagStr+"of"===Z||X};l0.prototype._decodeTag=function(J,Z,X){let Y=CX(J,'Failed to decode tag of "'+Z+'"');if(J.isError(Y))return Y;let H=fH(J,Y.primitive,'Failed to get length of "'+Z+'"');if(J.isError(H))return H;if(!X&&Y.tag!==Z&&Y.tagStr!==Z&&Y.tagStr+"of"!==Z)return J.error('Failed to match tag: "'+Z+'"');if(Y.primitive||H!==null)return J.skip(H,'Failed to match body of: "'+Z+'"');let G=J.save(),U=this._skipUntilEnd(J,'Failed to skip indefinite length body: "'+this.tag+'"');if(J.isError(U))return U;return H=J.offset-G.offset,J.restore(G),J.skip(H,'Failed to match body of: "'+Z+'"')};l0.prototype._skipUntilEnd=function(J,Z){for(;;){let X=CX(J,Z);if(J.isError(X))return X;let Y=fH(J,X.primitive,Z);if(J.isError(Y))return Y;let H;if(X.primitive||Y!==null)H=J.skip(Y);else H=this._skipUntilEnd(J,Z);if(J.isError(H))return H;if(X.tagStr==="end")break}};l0.prototype._decodeList=function(J,Z,X,Y){let H=[];while(!J.isEmpty()){let G=this._peekTag(J,"end");if(J.isError(G))return G;let U=X.decode(J,"der",Y);if(J.isError(U)&&G)break;H.push(U)}return H};l0.prototype._decodeStr=function(J,Z){if(Z==="bitstr"){let X=J.readUInt8();if(J.isError(X))return X;return{unused:X,data:J.raw()}}else if(Z==="bmpstr"){let X=J.raw();if(X.length%2===1)return J.error("Decoding of string type: bmpstr length mismatch");let Y="";for(let H=0;H<X.length/2;H++)Y+=String.fromCharCode(X.readUInt16BE(H*2));return Y}else if(Z==="numstr"){let X=J.raw().toString("ascii");if(!this._isNumstr(X))return J.error("Decoding of string type: numstr unsupported characters");return X}else if(Z==="octstr")return J.raw();else if(Z==="objDesc")return J.raw();else if(Z==="printstr"){let X=J.raw().toString("ascii");if(!this._isPrintstr(X))return J.error("Decoding of string type: printstr unsupported characters");return X}else if(/str$/.test(Z))return J.raw().toString();else return J.error("Decoding of string type: "+Z+" unsupported")};l0.prototype._decodeObjid=function(J,Z,X){let Y,H=[],G=0,U=0;while(!J.isEmpty())if(U=J.readUInt8(),G<<=7,G|=U&127,(U&128)===0)H.push(G),G=0;if(U&128)H.push(G);let V=H[0]/40|0,K=H[0]%40;if(X)Y=H;else Y=[V,K].concat(H.slice(1));if(Z){let F=Z[Y.join(" ")];if(F===void 0)F=Z[Y.join(".")];if(F!==void 0)Y=F}return Y};l0.prototype._decodeTime=function(J,Z){let X=J.raw().toString(),Y,H,G,U,V,K;if(Z==="gentime")Y=X.slice(0,4)|0,H=X.slice(4,6)|0,G=X.slice(6,8)|0,U=X.slice(8,10)|0,V=X.slice(10,12)|0,K=X.slice(12,14)|0;else if(Z==="utctime")if(Y=X.slice(0,2)|0,H=X.slice(2,4)|0,G=X.slice(4,6)|0,U=X.slice(6,8)|0,V=X.slice(8,10)|0,K=X.slice(10,12)|0,Y<70)Y=2000+Y;else Y=1900+Y;else return J.error("Decoding "+Z+" time is not supported yet");return Date.UTC(Y,H-1,G,U,V,K,0)};l0.prototype._decodeNull=function(){return null};l0.prototype._decodeBool=function(J){let Z=J.readUInt8();if(J.isError(Z))return Z;else return Z!==0};l0.prototype._decodeInt=function(J,Z){let X=J.raw(),Y=new o6(X);if(Z)Y=Z[Y.toString(10)]||Y;return Y};l0.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getDecoder("der").tree};function CX($,J){let Z=$.readUInt8(J);if($.isError(Z))return Z;let X=kH.tagClass[Z>>6],Y=(Z&32)===0;if((Z&31)===31){let G=Z;Z=0;while((G&128)===128){if(G=$.readUInt8(J),$.isError(G))return G;Z<<=7,Z|=G&127}}else Z&=31;let H=kH.tag[Z];return{cls:X,primitive:Y,tag:Z,tagStr:H}}function fH($,J,Z){let X=$.readUInt8(Z);if($.isError(X))return X;if(!J&&X===128)return null;if((X&128)===0)return X;let Y=X&127;if(Y>4)return $.error("length octect is too long");X=0;for(let H=0;H<Y;H++){X<<=8;let G=$.readUInt8(Z);if($.isError(G))return G;X|=G}return X}});var bH=o((N7,gH)=>{var s6=I$(),l6=nJ().Buffer,wX=SX();function LX($){wX.call(this,$),this.enc="pem"}s6(LX,wX);gH.exports=LX;LX.prototype.decode=function(J,Z){let X=J.toString().split(/[\r\n]+/g),Y=Z.label.toUpperCase(),H=/^-----(BEGIN|END) ([^-]+)-----$/,G=-1,U=-1;for(let F=0;F<X.length;F++){let A=X[F].match(H);if(A===null)continue;if(A[2]!==Y)continue;if(G===-1){if(A[1]!=="BEGIN")break;G=F}else{if(A[1]!=="END")break;U=F;break}}if(G===-1||U===-1)throw Error("PEM section not found for: "+Y);let V=X.slice(G+1,U).join("");V.replace(/[^a-z0-9+/=]+/gi,"");let K=l6.from(V,"base64");return wX.prototype.decode.call(this,K,Z)}});var EX=o((pH)=>{var cH=pH;cH.der=SX();cH.pem=bH()});var mH=o((uH)=>{var r6=jX(),i6=EX(),t6=I$(),a6=uH;a6.define=function(J,Z){return new l$(J,Z)};function l$($,J){this.name=$,this.body=J,this.decoders={},this.encoders={}}l$.prototype._createNamed=function(J){let Z=this.name;function X(Y){this._initNamed(Y,Z)}return t6(X,J),X.prototype._initNamed=function(H,G){J.call(this,H,G)},new X(this)};l$.prototype._getDecoder=function(J){if(J=J||"der",!this.decoders.hasOwnProperty(J))this.decoders[J]=this._createNamed(i6[J]);return this.decoders[J]};l$.prototype.decode=function(J,Z,X){return this._getDecoder(Z).decode(J,X)};l$.prototype._getEncoder=function(J){if(J=J||"der",!this.encoders.hasOwnProperty(J))this.encoders[J]=this._createNamed(r6[J]);return this.encoders[J]};l$.prototype.encode=function(J,Z,X){return this._getEncoder(Z).encode(J,X)}});var nH=o((dH)=>{var iJ=dH;iJ.Reporter=oJ().Reporter;iJ.DecoderBuffer=s$().DecoderBuffer;iJ.EncoderBuffer=s$().EncoderBuffer;iJ.Node=lJ()});var lH=o((sH)=>{var oH=sH;oH._reverse=function(J){let Z={};return Object.keys(J).forEach(function(X){if((X|0)==X)X=X|0;let Y=J[X];Z[Y]=X}),Z};oH.der=rJ()});var iH=o((rH)=>{var r$=rH;r$.bignum=AX();r$.define=mH().define;r$.base=nH();r$.constants=lH();r$.decoders=EX();r$.encoders=jX()});var eH=o((TX,aH)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var tJ=K$("buffer"),Q$=tJ.Buffer;function tH($,J){for(var Z in $)J[Z]=$[Z]}if(Q$.from&&Q$.alloc&&Q$.allocUnsafe&&Q$.allocUnsafeSlow)aH.exports=tJ;else tH(tJ,TX),TX.Buffer=w$;function w$($,J,Z){return Q$($,J,Z)}w$.prototype=Object.create(Q$.prototype);tH(Q$,w$);w$.from=function($,J,Z){if(typeof $==="number")throw TypeError("Argument must not be a number");return Q$($,J,Z)};w$.alloc=function($,J,Z){if(typeof $!=="number")throw TypeError("Argument must be a number");var X=Q$($);if(J!==void 0)if(typeof Z==="string")X.fill(J,Z);else X.fill(J);else X.fill(0);return X};w$.allocUnsafe=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return Q$($)};w$.allocUnsafeSlow=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return tJ.SlowBuffer($)}});var JW=o((f7,$W)=>{function NX($){var J=($/8|0)+($%8===0?0:1);return J}var e6={ES256:NX(256),ES384:NX(384),ES512:NX(521)};function $9($){var J=e6[$];if(J)return J;throw Error('Unknown algorithm "'+$+'"')}$W.exports=$9});var QW=o((h7,GW)=>{var aJ=eH().Buffer,XW=JW(),eJ=128,YW=0,J9=32,Z9=16,X9=2,HW=Z9|J9|YW<<6,$Z=X9|YW<<6;function Y9($){return $.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function WW($){if(aJ.isBuffer($))return $;else if(typeof $==="string")return aJ.from($,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function H9($,J){$=WW($);var Z=XW(J),X=Z+1,Y=$.length,H=0;if($[H++]!==HW)throw Error('Could not find expected "seq"');var G=$[H++];if(G===(eJ|1))G=$[H++];if(Y-H<G)throw Error('"seq" specified length of "'+G+'", only "'+(Y-H)+'" remaining');if($[H++]!==$Z)throw Error('Could not find expected "int" for "r"');var U=$[H++];if(Y-H-2<U)throw Error('"r" specified length of "'+U+'", only "'+(Y-H-2)+'" available');if(X<U)throw Error('"r" specified length of "'+U+'", max of "'+X+'" is acceptable');var V=H;if(H+=U,$[H++]!==$Z)throw Error('Could not find expected "int" for "s"');var K=$[H++];if(Y-H!==K)throw Error('"s" specified length of "'+K+'", expected "'+(Y-H)+'"');if(X<K)throw Error('"s" specified length of "'+K+'", max of "'+X+'" is acceptable');var F=H;if(H+=K,H!==Y)throw Error('Expected to consume entire buffer, but "'+(Y-H)+'" bytes remain');var A=Z-U,j=Z-K,C=aJ.allocUnsafe(A+U+j+K);for(H=0;H<A;++H)C[H]=0;$.copy(C,H,V+Math.max(-A,0),V+U),H=Z;for(var w=H;H<w+j;++H)C[H]=0;return $.copy(C,H,F+Math.max(-j,0),F+K),C=C.toString("base64"),C=Y9(C),C}function ZW($,J,Z){var X=0;while(J+X<Z&&$[J+X]===0)++X;var Y=$[J+X]>=eJ;if(Y)--X;return X}function W9($,J){$=WW($);var Z=XW(J),X=$.length;if(X!==Z*2)throw TypeError('"'+J+'" signatures must be "'+Z*2+'" bytes, saw "'+X+'"');var Y=ZW($,0,Z),H=ZW($,Z,$.length),G=Z-Y,U=Z-H,V=2+G+1+1+U,K=V<eJ,F=aJ.allocUnsafe((K?2:3)+V),A=0;if(F[A++]=HW,K)F[A++]=V;else F[A++]=eJ|1,F[A++]=V&255;if(F[A++]=$Z,F[A++]=G,Y<0)F[A++]=0,A+=$.copy(F,A,0,Z);else A+=$.copy(F,A,Y,Z);if(F[A++]=$Z,F[A++]=U,H<0)F[A++]=0,$.copy(F,A,Z);else $.copy(F,A,Z+H);return F}GW.exports={derToJose:H9,joseToDer:W9}});var xX=o((g7,BW)=>{var kX=iH(),{createHmac:VW,createVerify:G9,createSign:Q9,timingSafeEqual:z9,createPublicKey:U9,constants:{RSA_PKCS1_PSS_PADDING:KW,RSA_PSS_SALTLEN_DIGEST:OW,RSA_PKCS1_PADDING:_W,RSA_PSS_SALTLEN_MAX_SIGN:V9,RSA_PSS_SALTLEN_AUTO:K9},sign:zW,verify:UW}=K$("crypto"),{joseToDer:O9,derToJose:_9}=QW(),FW=_X(),{TokenError:J0}=p$(),AW=/[=+/]/g,F9={"=":"","+":"-","/":"_"},RW=/^-----BEGIN(?: (RSA|EC|ENCRYPTED))? PRIVATE KEY-----/,MW=/^-----BEGIN(?: (RSA))? PUBLIC KEY-----/,JZ=new FW(1000),vX=new FW(1000),IW=["HS256","HS384","HS512"],A9=["ES256","ES384","ES512"],DX=["RS256","RS384","RS512","PS256","PS384","PS512"],R9=["EdDSA"],qW={"1.2.840.10045.3.1.7":{bits:"256",names:["P-256","prime256v1"]},"1.3.132.0.10":{bits:"256",names:["secp256k1"]},"1.3.132.0.34":{bits:"384",names:["P-384","secp384r1"]},"1.3.132.0.35":{bits:"512",names:["P-521","secp521r1"]}},M9=kX.define("PrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),I9=kX.define("PublicKey",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),q9=kX.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).optional().choice({namedCurve:this.objid()}))});function PW($){return F9[$]}function VJ($,J,Z,X){return $.set(J,[Z,X]),Z||X}function P9($){if($.match(MW)||$.includes("-----BEGIN CERTIFICATE-----"))throw new J0(J0.codes.invalidKey,"Public keys are not supported for signing.");let J=$.trim().match(RW);if(!J)return"HS256";let Z,X,Y;switch(J[1]){case"RSA":return"RS256";case"EC":Z=q9.decode($,"pem",{label:"EC PRIVATE KEY"}),Y=Z.parameters.value.join(".");break;case"ENCRYPTED":return"ENCRYPTED";default:switch(Z=M9.decode($,"pem",{label:"PRIVATE KEY"}),X=Z.algorithm.algorithm.join("."),X){case"1.2.840.113549.1.1.1":return"RS256";case"1.2.840.10045.2.1":Y=Z.algorithm.parameters.join(".");break;case"1.3.101.112":case"1.3.101.113":return"EdDSA";default:throw new J0(J0.codes.invalidKey,`Unsupported PEM PCKS8 private key with OID ${X}.`)}}let H=qW[Y];if(!H)throw new J0(J0.codes.invalidKey,`Unsupported EC private key with curve ${Y}.`);return`ES${H.bits}`}function B9($){let J=$.match(MW);if($.match(RW))throw new J0(J0.codes.invalidKey,"Private keys are not supported for verifying.");else if(J&&J[1]==="RSA")return DX;else if(!J&&!$.includes("-----BEGIN CERTIFICATE-----"))return IW;if($.includes("-----BEGIN CERTIFICATE-----"))$=U9($).export({type:"spki",format:"pem"});let Z=I9.decode($,"pem",{label:"PUBLIC KEY"}),X=Z.algorithm.algorithm.join("."),Y;switch(X){case"1.2.840.113549.1.1.1":return DX;case"1.2.840.10045.2.1":Y=Z.algorithm.parameters.join(".");break;case"1.3.101.112":case"1.3.101.113":return["EdDSA"];default:throw new J0(J0.codes.invalidKey,`Unsupported PEM PCKS8 public key with OID ${X}.`)}let H=qW[Y];if(!H)throw new J0(J0.codes.invalidKey,`Unsupported EC public key with curve ${Y}.`);return[`ES${H.bits}`]}function j9($,J){if($ instanceof Buffer)$=$.toString("utf-8");else if(typeof $!=="string")throw new J0(J0.codes.invalidKey,"The private key must be a string or a buffer.");let[Z,X]=JZ.get($)||[];if(Z)return Z;else if(X)throw X;try{let Y=P9($);if(Y==="ENCRYPTED")return VJ(JZ,$,J);return VJ(JZ,$,Y)}catch(Y){throw VJ(JZ,$,null,J0.wrap(Y,J0.codes.invalidKey,"Unsupported PEM private key."))}}function C9($){if(!$)return"none";let[J,Z]=vX.get($)||[];if(J)return J;else if(Z)throw Z;try{if($ instanceof Buffer)$=$.toString("utf-8");else if(typeof $!=="string")throw new J0(J0.codes.invalidKey,"The public key must be a string or a buffer.");return VJ(vX,$,B9($))}catch(X){throw VJ(vX,$,null,J0.wrap(X,J0.codes.invalidKey,"Unsupported PEM public key."))}}function S9($,J,Z){try{let X=$.slice(0,2),Y=`sha${$.slice(2)}`,H,G;switch(X){case"HS":H=VW(Y,J).update(Z).digest("base64");break;case"ES":H=_9(zW(Y,Buffer.from(Z,"utf-8"),J),$).toString("base64");break;case"RS":case"PS":if(G={key:J,padding:_W,saltLength:V9},X==="PS")G.padding=KW,G.saltLength=OW;H=Q9(Y).update(Z).sign(G).toString("base64");break;case"Ed":H=zW(void 0,Buffer.from(Z,"utf-8"),J).toString("base64")}return H.replace(AW,PW)}catch(X){throw new J0(J0.codes.signError,"Cannot create the signature.",{originalError:X})}}function w9($,J,Z,X){try{let Y=$.slice(0,2),H=`SHA${$.slice(2)}`;if(X=Buffer.from(X,"base64"),Y==="HS")try{return z9(VW(H,J).update(Z).digest(),X)}catch{return!1}else if(Y==="Ed")if(typeof UW==="function")return UW(void 0,Buffer.from(Z,"utf-8"),J,X);else throw new J0(J0.codes.signError,"EdDSA algorithms are not supported by your Node.js version.");let G={key:J,padding:_W,saltLength:K9};if(Y==="PS")G.padding=KW,G.saltLength=OW;else if(Y==="ES")X=O9(X,$);return G9("RSA-"+H).update(Z).verify(G,X)}catch(Y){throw new J0(J0.codes.verifyError,"Cannot verify the signature.",{originalError:Y})}}BW.exports={base64UrlMatcher:AW,base64UrlReplacer:PW,hsAlgorithms:IW,rsaAlgorithms:DX,esAlgorithms:A9,edAlgorithms:R9,detectPrivateKeyAlgorithm:j9,detectPublicKeyAlgorithms:C9,createSignature:S9,verifySignature:w9}});var yX=o((b7,CW)=>{var{createHash:jW}=K$("crypto"),L9=/"alg"\s*:\s*"[HERP]S(256|384)"/m,E9=/"alg"\s*:\s*"EdDSA"/m,T9=/"crv"\s*:\s*"Ed448"/m;function N9($,J,Z){let X=$(J,Z);if(X&&typeof X.then==="function")X.then((Y)=>{process.nextTick(()=>Z(null,Y))}).catch(Z)}function v9($){if(typeof $==="function")return[$];let J,Z,X=new Promise((Y,H)=>{J=Y,Z=H});return[function(Y,H){if(Y)return Z(Y);return J(H)},X]}function D9($){let J=$.split(".",1)[0],Z=Buffer.from(J,"base64").toString("utf-8"),X=null;if(Z.match(E9)&&Z.match(T9))X=jW("shake256",{outputLength:114});else{let Y=Z.match(L9);X=jW(`sha${Y?Y[1]:"512"}`)}return X.update($).digest("hex")}CW.exports={getAsyncKey:N9,ensurePromiseCallback:v9,hashToken:D9}});var vW=o((c7,NW)=>{var{createPublicKey:k9,createSecretKey:x9}=K$("crypto"),y9=_X(),{hsAlgorithms:wW,verifySignature:f9,detectPublicKeyAlgorithms:LW}=xX(),h9=zX(),{TokenError:m}=p$(),{getAsyncKey:g9,ensurePromiseCallback:b9,hashToken:c9}=yX();function p9($,J){return $===J}function EW($,J){for(let Z of $)if(J.includes(Z))return;throw new m(m.codes.invalidKey,`Invalid public key provided for algorithms ${$.join(", ")}.`)}function TW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J?x9($):k9($)}function KJ($){if(!Array.isArray($))$=[$];return $.filter((J)=>J).map((J)=>{if(J&&typeof J.test==="function")return J;return{test:p9.bind(null,J)}})}function u9($){let J=parseInt($===!0?1000:$,10);return J>0?new y9(J):null}function i$({cache:$,token:J,cacheTTL:Z,payload:X,ignoreExpiration:Y,ignoreNotBefore:H,maxAge:G,clockTimestamp:U=Date.now(),clockTolerance:V,errorCacheTTL:K,cacheKeyBuilder:F},A){if(!$)return A;let j=[A,0,0];if(A instanceof m){let E=typeof K==="function"?K(A):K;return j[2]=U+V+E,$.set(F(J),j),A}if(X&&typeof X.iat==="number"){if(j[1]=!H&&typeof X.nbf==="number"?X.nbf*1000-V:0,!Y){if(typeof X.exp==="number")j[2]=X.exp*1000+V;else if(G)j[2]=X.iat*1000+G+V}}let w=U+V+Z;return j[2]=j[2]===0?w:Math.min(j[2],w),$.set(F(J),j),A}function m9($,J,Z){if($ instanceof m){if(!J)throw $;J($)}else{if(!J)return $;J(null,$)}return Z}function d9($,J,Z,X,Y){if(!Y.includes(J.alg))throw new m(m.codes.invalidAlgorithm,"The token algorithm is invalid.");if(Z&&!f9(J.alg,X,$,Z))throw new m(m.codes.invalidSignature,"The token signature is invalid.")}function n9($,J,Z,X,Y){let H=Z?`The ${J} claim must be a ${Y} or an array of ${Y}s.`:`The ${J} claim must be a ${Y}.`;if(X&&!Z)throw new m(m.codes.invalidClaimValue,H);if($.map((G)=>typeof G).some((G)=>G!==Y))throw new m(m.codes.invalidClaimType,H)}function o9($,J,Z,X){let Y=X?`None of ${J} claim values are allowed.`:`The ${J} claim value is not allowed.`;if(!$.some((H)=>Z.some((G)=>G.test(H))))throw new m(m.codes.invalidClaimValue,Y)}function s9($,J,Z,X,Y,H){let G=$*1000+(J||0);if(!(X?Z>=G:Z<=G))throw new m(m.codes[Y],`The token ${H} at ${new Date(G).toISOString()}.`)}function SW($,{input:J,header:Z,payload:X,signature:Y},{validators:H,allowedAlgorithms:G,checkTyp:U,clockTimestamp:V,requiredClaims:K}){let F=$ instanceof Buffer?$.length:!!$;if(F&&!Y)throw new m(m.codes.missingSignature,"The token signature is missing.");else if(!F&&Y)throw new m(m.codes.missingKey,"The key option is missing.");if(d9(J,Z,Y,$,G),U&&(typeof Z.typ!=="string"||U!==Z.typ.toLowerCase().replace(/^application\//,"")))throw new m(m.codes.invalidType,"Invalid typ.");if(K){for(let j of K)if(!(j in X))throw new m(m.codes.missingRequiredClaim,`The ${j} claim is required.`)}let A=V||Date.now();for(let{type:j,claim:C,allowed:w,array:E,modifier:T,greater:v,errorCode:L,errorVerb:D}of H){let g=X[C],N=Array.isArray(g),f=N?g:[g];if(!(C in X))continue;if(n9(f,C,E,N,j==="date"?"number":"string"),j==="date")s9(g,T,A,v,L,D);else o9(f,C,w,N)}}function l9({key:$,allowedAlgorithms:J,complete:Z,cacheTTL:X,checkTyp:Y,clockTimestamp:H,clockTolerance:G,ignoreExpiration:U,ignoreNotBefore:V,maxAge:K,isAsync:F,validators:A,decode:j,cache:C,requiredClaims:w,errorCacheTTL:E,cacheKeyBuilder:T},v,L){let[D,g]=F?b9(L):[];if(C){let[z,O,_]=C.get(T(v))||[void 0,0,0],I=H||Date.now();if(typeof z<"u"&&(O===0||I<O&&z.code==="FAST_JWT_INACTIVE"||I>=O&&z.code!=="FAST_JWT_INACTIVE")&&(_===0||I<=_))return m9(z,D,g)}let N;try{N=j(v)}catch(z){if(D)return D(z),g;throw z}let{header:f,payload:l,signature:r,input:u0}=N,q={cache:C,token:v,cacheTTL:X,errorCacheTTL:E,ignoreExpiration:U,ignoreNotBefore:V,maxAge:K,clockTimestamp:H,clockTolerance:G,payload:l,cacheKeyBuilder:T},W={validators:A,allowedAlgorithms:J,checkTyp:Y,clockTimestamp:H,clockTolerance:G,requiredClaims:w};if(!D)try{return SW($,N,W),i$(q,Z?{header:f,payload:l,signature:r,input:u0}:l)}catch(z){throw i$(q,z)}return g9($,{header:f,payload:l,signature:r},(z,O)=>{if(z)return D(i$(q,m.wrap(z,m.codes.keyFetchingError,"Cannot fetch key.")));if(typeof O==="string")O=Buffer.from(O,"utf-8");else if(!(O instanceof Buffer))return D(i$(q,new m(m.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a public key.")));try{let _=LW(O);if(W.allowedAlgorithms.length)EW(J,_);else W.allowedAlgorithms=_;O=TW(O,_[0]===wW[0]),SW(O,N,W)}catch(_){return D(i$(q,_))}D(null,i$(q,Z?{header:f,payload:l,signature:r,input:v}:l))}),g}NW.exports=function(J){let{key:Z,algorithms:X,complete:Y,cache:H,cacheTTL:G,errorCacheTTL:U,checkTyp:V,clockTimestamp:K,clockTolerance:F,ignoreExpiration:A,ignoreNotBefore:j,maxAge:C,allowedJti:w,allowedAud:E,allowedIss:T,allowedSub:v,allowedNonce:L,requiredClaims:D,cacheKeyBuilder:g}={cacheTTL:600000,clockTolerance:0,errorCacheTTL:-1,cacheKeyBuilder:c9,...J};if(!Array.isArray(X))X=[];let N=typeof Z;if(N!=="string"&&N!=="object"&&N!=="function")throw new m(m.codes.INVALID_OPTION,"The key option must be a string, a buffer or a function returning the algorithm secret or public key.");if(Z&&N!=="function"){let q=LW(Z);if(X.length)EW(X,q);else X=q;Z=TW(Z,q[0]===wW[0])}if(K&&(typeof K!=="number"||K<0))throw new m(m.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(F&&(typeof F!=="number"||F<0))throw new m(m.codes.invalidOption,"The clockTolerance option must be a positive number.");if(G&&(typeof G!=="number"||G<0))throw new m(m.codes.invalidOption,"The cacheTTL option must be a positive number.");if(U&&typeof U!=="function"&&typeof U!=="number"||U<-1)throw new m(m.codes.invalidOption,"The errorCacheTTL option must be a number greater than -1 or a function.");if(D&&!Array.isArray(D))throw new m(m.codes.invalidOption,"The requiredClaims option must be an array.");let f=[];if(!j)f.push({type:"date",claim:"nbf",errorCode:"inactive",errorVerb:"will be active",greater:!0,modifier:-F});if(!A)f.push({type:"date",claim:"exp",errorCode:"expired",errorVerb:"has expired",modifier:+F});if(typeof C==="number")f.push({type:"date",claim:"iat",errorCode:"expired",errorVerb:"has expired",modifier:C});if(w)f.push({type:"string",claim:"jti",allowed:KJ(w)});if(E)f.push({type:"string",claim:"aud",allowed:KJ(E),array:!0});if(T)f.push({type:"string",claim:"iss",allowed:KJ(T)});if(v)f.push({type:"string",claim:"sub",allowed:KJ(v)});if(L)f.push({type:"string",claim:"nonce",allowed:KJ(L)});let l=V?V.toLowerCase().replace(/^application\//,""):null,r={key:Z,allowedAlgorithms:X,complete:Y,cacheTTL:G,errorCacheTTL:U,checkTyp:l,clockTimestamp:K,clockTolerance:F,ignoreExpiration:A,ignoreNotBefore:j,maxAge:C,isAsync:N==="function",validators:f,decode:h9({complete:!0}),cache:u9(H),requiredClaims:D,cacheKeyBuilder:g},u0=l9.bind(null,r);return u0.cache=r.cache,u0}});var DW=o((a9)=>{var r9=/^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/,ZZ=1000,XZ=ZZ*60,YZ=XZ*60,_J=YZ*24,fX=_J*365.25;function i9($){var J,Z=$.toLowerCase().match(r9);if(Z!=null&&(J=parseFloat(Z[1]))){if(Z[3]!=null)return J*ZZ;if(Z[4]!=null)return J*XZ;if(Z[5]!=null)return J*YZ;if(Z[6]!=null)return J*_J;if(Z[7]!=null)return J*_J*7;if(Z[8]!=null)return J*fX;return J}}function OJ($,J,Z,X){var Y=($|0)===$?$:~~($+0.5);return J+Y+(X?" "+Z+(Y!=1?"s":""):Z[0])}function t9($,J){var Z=$<0?"-":"",X=$<0?-$:$;if(X<ZZ)return $+(J?" ms":"ms");if(X<XZ)return OJ(X/ZZ,Z,"second",J);if(X<YZ)return OJ(X/XZ,Z,"minute",J);if(X<_J)return OJ(X/YZ,Z,"hour",J);if(X<fX)return OJ(X/_J,Z,"day",J);return OJ(X/fX,Z,"year",J)}a9.format=t9;a9.parse=i9});var cW=o((u7,bW)=>{var{base64UrlMatcher:hX,base64UrlReplacer:gX,hsAlgorithms:J8,esAlgorithms:Z8,rsaAlgorithms:X8,edAlgorithms:Y8,detectPrivateKeyAlgorithm:yW,createSignature:kW}=xX(),{TokenError:d}=p$(),{getAsyncKey:H8,ensurePromiseCallback:W8}=yX(),{createPrivateKey:G8,createSecretKey:Q8}=K$("crypto"),{parse:xW}=DW(),fW=new Set([...J8,...Z8,...X8,...Y8,"none"]),z8=Array.from(fW).join(", ");function hW($,J){let Z=$.slice(0,2),X=J.slice(0,2),Y=!0;if(Z==="RS"||Z==="PS")Y=X==="RS"||Z==="RS"&&J==="ENCRYPTED";else if(Z==="ES"||Z==="Ed")Y=Z===X||Z==="ES"&&J==="ENCRYPTED";if(!Y)throw new d(d.codes.invalidKey,`Invalid private key provided for algorithm ${$}.`)}function gW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J[0]==="H"?Q8($):G8($)}function U8({key:$,algorithm:J,noTimestamp:Z,mutatePayload:X,clockTimestamp:Y,expiresIn:H,notBefore:G,kid:U,typ:V,isAsync:K,additionalHeader:F,fixedPayload:A},j,C){let[w,E]=K?W8(C):[];if(typeof j!=="object")throw new d(d.codes.invalidType,"The payload must be an object.");if(j.exp&&(!Number.isInteger(j.exp)||j.exp<0))throw new d(d.codes.invalidClaimValue,"The exp claim must be a positive integer.");let T={alg:J,typ:V||"JWT",kid:U,...F},v="",L=j.iat*1000||Y||Date.now(),D={...j,...A,iat:Z?void 0:Math.floor(L/1000),exp:j.exp?j.exp:H?Math.floor((L+H)/1000):void 0,nbf:j.nbf?j.nbf:G?Math.floor((L+G)/1000):void 0};if(X)Object.assign(j,D);if(v=Buffer.from(JSON.stringify(D),"utf-8").toString("base64").replace(hX,gX),!w){let N=Buffer.from(JSON.stringify(T),"utf-8").toString("base64").replace(hX,gX)+"."+v,f=J==="none"?"":kW(J,$,N);return N+"."+f}return H8($,{header:T,payload:j},(g,N)=>{if(g){let l=d.wrap(g,d.codes.keyFetchingError,"Cannot fetch key.");return w(l)}if(typeof N==="string")N=Buffer.from(N,"utf-8");else if(!(N instanceof Buffer))return w(new d(d.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a private key."));let f;try{let l=yW(N,J);if(J)hW(J,l);else T.alg=J=l;N=gW(N,J);let u0=Buffer.from(JSON.stringify(T),"utf-8").toString("base64").replace(hX,gX)+"."+v;f=u0+"."+kW(J,N,u0)}catch(l){return w(l)}w(null,f)}),E}bW.exports=function(J){let{key:Z,algorithm:X,noTimestamp:Y,mutatePayload:H,clockTimestamp:G,expiresIn:U,notBefore:V,jti:K,aud:F,iss:A,sub:j,nonce:C,kid:w,typ:E,header:T}={clockTimestamp:0,...J};if(X&&!fW.has(X))throw new d(d.codes.invalidOption,`The algorithm option must be one of the following values: ${z8}.`);let v=typeof Z,L=v==="object"&&Z&&Z.key&&Z.passphrase;if(X==="none"){if(Z)throw new d(d.codes.invalidOption,'The key option must not be provided when the algorithm option is "none".')}else if(!Z||v!=="string"&&!(Z instanceof Buffer)&&v!=="function"&&!L)throw new d(d.codes.invalidOption,"The key option must be a string, a buffer, an object containing key/passphrase properties or a function returning the algorithm secret or private key.");else if(L&&!X)throw new d(d.codes.invalidAlgorithm,"When using password protected key you must provide the algorithm option.");if(Z&&v!=="function"){let N=yW(L?Z.key:Z,X);if(X)hW(X,N);else X=N;Z=gW(Z,X)}if(U){if(typeof U==="string")U=xW(U);if(typeof U!=="number")throw new d(d.codes.invalidOption,"The expiresIn option must be a positive number or a valid string.")}if(V){if(typeof V==="string")V=xW(V);if(typeof V!=="number"||V<0)throw new d(d.codes.invalidOption,"The notBefore option must be a positive number or a valid string.")}if(G&&(typeof G!=="number"||G<0))throw new d(d.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(K&&typeof K!=="string")throw new d(d.codes.invalidOption,"The jti option must be a string.");if(F&&typeof F!=="string"&&!Array.isArray(F))throw new d(d.codes.invalidOption,"The aud option must be a string or an array of strings.");if(A&&typeof A!=="string")throw new d(d.codes.invalidOption,"The iss option must be a string.");if(j&&typeof j!=="string")throw new d(d.codes.invalidOption,"The sub option must be a string.");if(C&&typeof C!=="string")throw new d(d.codes.invalidOption,"The nonce option must be a string.");if(w&&typeof w!=="string")throw new d(d.codes.invalidOption,"The kid option must be a string.");if(T&&typeof T!=="object")throw new d(d.codes.invalidOption,"The header option must be a object.");let g=Object.entries({jti:K,aud:F,iss:A,sub:j,nonce:C}).reduce((N,[f,l])=>{if(l!==void 0)N[f]=l;return N},{});return U8.bind(null,{key:Z,algorithm:X,noTimestamp:Y,mutatePayload:H,clockTimestamp:G,expiresIn:U,notBefore:V,kid:w,typ:E,isAsync:v==="function",additionalHeader:T,fixedPayload:g})}});var uW=o((m7,pW)=>{var{TokenError:V8,TOKEN_ERROR_CODES:K8}=p$(),O8=zX(),_8=vW(),F8=cW();pW.exports={TokenError:V8,TOKEN_ERROR_CODES:K8,createDecoder:O8,createVerifier:_8,createSigner:F8}});var{Glob:XG}=globalThis.Bun;var H1=new Map;function YG($){if(typeof $>"u")return[];if(!Array.isArray($))throw Error("disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A\u5FC5\u987B\u662F string[]");let J=[];for(let Z of $){if(typeof Z!=="string")throw Error("disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A\u6570\u7EC4\u5143\u7D20\u5FC5\u987B\u662F string");let X=Z.trim();if(!X)throw Error("disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A\u4E0D\u5141\u8BB8\u7A7A\u5B57\u7B26\u4E32");J.push(X)}return J}function HG($){let J=H1.get($);if(J)return J;let Z=new XG($);return H1.set($,Z),Z}function T$($){let J=YG($);if(J.length===0)return[];let Z=[];for(let X of J)try{let Y=HG(X);Z.push({type:"glob",raw:X,glob:Y})}catch(Y){throw Error(`disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1Aglob \u89C4\u5219 ${X} \u89E3\u6790\u5931\u8D25\uFF1A${Y?.message||String(Y)}`)}return Z}function t$($,J){for(let Z of J)if(Z.glob.match($))return!0;return!1}import{existsSync as UG}from"fs";import{isAbsolute as VG,join as V1}from"path";import{pathToFileURL as KG}from"url";function _$($){if(Array.isArray($)){let J=[];for(let Z of $)J.push(_$(Z));return J}if(s($)){let J={};for(let Z of Object.keys($))J[Z]=_$($[Z]);return J}return $}function U1($,J){if(J===void 0)return $;if(Array.isArray($)&&Array.isArray(J)){for(let Z of J)$.push(_$(Z));return $}if(s($)&&s(J)){for(let Z of Object.keys(J)){let X=J[Z];if(X===void 0)continue;let Y=$[Z];if(Array.isArray(Y)&&Array.isArray(X)){let H=[];for(let G of Y)H.push(_$(G));for(let G of X)H.push(_$(G));$[Z]=H;continue}if(s(Y)&&s(X)){$[Z]=U1(_$(Y),X);continue}$[Z]=_$(X)}return $}return _$(J)}function EZ(...$){let J={};for(let Z of $){if(Z===void 0)continue;J=U1(J,Z)}return J}async function K1($){let{cwd:J=process.cwd(),dirs:Z,files:X,extensions:Y=[".ts",".js",".json"],mode:H="first",paths:G,defaults:U={}}=$;if(!Array.isArray(Z)||Z.length===0)throw Error("dirs \u5FC5\u987B\u662F\u975E\u7A7A\u6570\u7EC4");if(!Array.isArray(X)||X.length===0)throw Error("files \u5FC5\u987B\u662F\u975E\u7A7A\u6570\u7EC4");let V=[];for(let F of Z){let A=VG(F)?F:V1(J,F);for(let j of X)for(let C of Y){let w=j.endsWith(C)?j:j+C,E=V1(A,w);if(UG(E))try{let T=KG(E).href+`?t=${Date.now()}`,v;if(C===".json")v=(await import(T,{with:{type:"json"}})).default;else{let L=await import(T);if(v=L.default||L,v instanceof Promise)v=await v}if(!s(v))continue;if(V.push(v),H==="first"){let L=EZ(U,v);if(G&&G.length>0){let D={};for(let g of G){let N=wZ(L,g);if(N!==void 0)LZ(D,g,N)}return D}return L}break}catch{}}}let K=EZ(U,...V);if(G&&G.length>0){let F={};for(let A of G){let j=wZ(K,A);if(j!==void 0)LZ(F,A,j)}return F}return K}var OG={nodeEnv:"development",appName:"\u91CE\u8702\u98DE\u821E",appPort:3000,appHost:"127.0.0.1",devEmail:"dev@qq.com",devPassword:"beflydev123456",bodyLimit:1048576,tz:"Asia/Shanghai",logger:{debug:1,excludeFields:["password","token","secret"],dir:"./logs",console:1,maxSize:10485760,maxStringLen:100,maxArrayItems:100},db:{type:"mysql",host:"127.0.0.1",port:3306,username:"root",password:"root",database:"befly_demo",poolMax:10},redis:{host:"127.0.0.1",port:6379,username:"",password:"",db:0,prefix:"befly_demo"},auth:{secret:"befly-secret",expiresIn:"7d",algorithm:"HS256"},cors:{origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",allowedHeaders:"Content-Type,Authorization",exposedHeaders:"",maxAge:86400,credentials:"true"},rateLimit:{enable:1,defaultLimit:1000,defaultWindow:60,key:"ip",skipRoutes:[],rules:[]},disableMenus:["**/404","**/403","**/500","**/login"],addons:{}},TZ=new Map;async function O1(){let X=TZ.get("development");if(X)return await X;let Y=(async()=>{let H=await K1({dirs:["configs"],files:["befly.common","befly.development"],extensions:[".json"],mode:"merge",defaults:OG}),G=H?.redis?.prefix;if(typeof G==="string"){if(G.trim().includes(":"))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Aredis.prefix \u4E0D\u5141\u8BB8\u5305\u542B ':'\uFF08RedisHelper \u4F1A\u81EA\u52A8\u62FC\u63A5\u5206\u9694\u7B26 ':'\uFF09\uFF0C\u8BF7\u6539\u4E3A\u4E0D\u5E26\u5192\u53F7\u7684\u524D\u7F00\uFF0C\u4F8B\u5982 'befly_demo'\uFF0C\u5F53\u524D\u503C=${G}`)}return T$(H?.disableMenus),H})();TZ.set("development",Y);try{return await Y}catch(H){throw TZ.delete("development"),H}}a();async function g1($){let J=!1;for(let Z of $)try{if(typeof Z?.name!=="string"||Z.name.trim()===""){P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 name \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32"),J=!0;continue}if(typeof Z?.handler!=="function"){P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"),J=!0;continue}if(typeof Z?.routePath!=="string"||Z.routePath.trim()==="")P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 routePath \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"),J=!0;else{let X=Z.routePath.trim();if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(X))P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 routePath \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09"),J=!0;if(!X.startsWith("/api/"))P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 routePath \u5FC5\u987B\u4EE5 /api/ \u5F00\u5934"),J=!0;if(X.includes(" "))P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 routePath \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C"),J=!0;if(X.includes("/api//"))P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 routePath \u4E0D\u5141\u8BB8\u51FA\u73B0 /api//\uFF08\u91CD\u590D\u659C\u6760\uFF09"),J=!0}if(typeof Z?.routePrefix!=="string"||Z.routePrefix.trim()==="")P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 routePrefix \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"),J=!0;if(Z.method&&!["GET","POST","GET,POST","POST,GET"].includes(String(Z.method).toUpperCase()))P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 method \u5C5E\u6027\u5FC5\u987B\u662F\u6709\u6548\u7684 HTTP \u65B9\u6CD5 (GET, POST, GET,POST, POST,GET)"),J=!0;if(Z.auth!==void 0&&typeof Z.auth!=="boolean")P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 auth \u5C5E\u6027\u5FC5\u987B\u662F\u5E03\u5C14\u503C (true=\u9700\u767B\u5F55, false=\u516C\u5F00)"),J=!0;if(Z.fields&&!s(Z.fields))P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 fields \u5C5E\u6027\u5FC5\u987B\u662F\u5BF9\u8C61"),J=!0;if(Z.required&&!Array.isArray(Z.required))P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u6570\u7EC4"),J=!0;if(Z.required&&Z.required.some((X)=>typeof X!=="string"))P.warn(u(Z,["handler"]),"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"),J=!0}catch(X){P.error({err:X,item:Z},"\u63A5\u53E3\u89E3\u6790\u5931\u8D25"),J=!0}if(J)throw Error("\u63A5\u53E3\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();async function b1($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let X of $)try{if(!s(X)){P.warn(u(X,["handler"]),"\u94A9\u5B50\u5BFC\u51FA\u5FC5\u987B\u662F\u5BF9\u8C61\uFF08export default { deps, handler }\uFF09"),J=!0;continue}if(typeof X.moduleName!=="string"||X.moduleName.trim()===""){P.warn(u(X,["handler"]),"\u94A9\u5B50\u7684 moduleName \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u7528\u4E8E deps \u4E0E\u8FD0\u884C\u65F6\u6302\u8F7D\uFF09"),J=!0;continue}if(!Object.prototype.hasOwnProperty.call(X,"enable")){P.warn(u(X,["handler"]),"\u94A9\u5B50\u7684 enable \u5C5E\u6027\u662F\u5FC5\u586B\u9879\uFF0C\u4E14\u5FC5\u987B\u663E\u5F0F\u58F0\u660E\u4E3A true \u6216 false"),J=!0;continue}if(typeof X.enable!=="boolean"){P.warn(u(X,["handler"]),"\u94A9\u5B50\u7684 enable \u5C5E\u6027\u5FC5\u987B\u662F boolean\uFF08true/false\uFF09\uFF0C\u4E0D\u5141\u8BB8 0/1 \u7B49\u5176\u4ED6\u7C7B\u578B"),J=!0;continue}if(X.source==="core"){let Y=typeof X.name==="string"?X.name:"";if(Y===""){P.warn(u(X,["handler"]),"core \u5185\u7F6E\u94A9\u5B50\u5FC5\u987B\u663E\u5F0F\u8BBE\u7F6E name\uFF08string\uFF09\uFF0C\u7528\u4E8E\u786E\u5B9A\u94A9\u5B50\u540D\u79F0"),J=!0;continue}if(!Z.test(Y)){P.warn(u(X,["handler"]),"core \u5185\u7F6E\u94A9\u5B50\u7684 name \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u4F8B\u5982 auth / rate_limit\uFF09\uFF0C\u4E0D\u5141\u8BB8\u7A7A\u683C\u3001\u9A7C\u5CF0\u6216\u5176\u4ED6\u5B57\u7B26"),J=!0;continue}if(!Z.test(X.moduleName)){P.warn(u(X,["handler"]),"core \u5185\u7F6E\u94A9\u5B50\u7684 moduleName \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u4E14\u5FC5\u987B\u4E0E name \u4E00\u81F4\uFF09"),J=!0;continue}if(Y!==X.moduleName){P.warn(u(X,["handler"]),"core \u5185\u7F6E\u94A9\u5B50\u7684 name \u5FC5\u987B\u4E0E moduleName \u5B8C\u5168\u4E00\u81F4"),J=!0;continue}if(typeof X.filePath!=="string"||!X.filePath.startsWith(`core:hook:${Y}`)){P.warn(u(X,["handler"]),"core \u5185\u7F6E\u94A9\u5B50\u5FC5\u987B\u6765\u81EA\u9759\u6001\u6CE8\u518C\uFF08filePath \u5FC5\u987B\u4EE5 core:hook:<name> \u5F00\u5934\uFF09\uFF0C\u4E0D\u5141\u8BB8\u901A\u8FC7\u626B\u63CF\u76EE\u5F55\u52A0\u8F7D"),J=!0;continue}}if(!Array.isArray(X.deps)){P.warn(u(X,["handler"]),"\u94A9\u5B50\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"),J=!0;continue}if(X.deps.some((Y)=>typeof Y!=="string"))P.warn(u(X,["handler"]),"\u94A9\u5B50\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"),J=!0;if(typeof X.handler!=="function"){P.warn(u(X,["handler"]),"\u94A9\u5B50\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"),J=!0;continue}}catch(Y){P.error({err:Y,item:X},"\u94A9\u5B50\u89E3\u6790\u5931\u8D25"),J=!0}if(J)throw Error("\u94A9\u5B50\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();oZ();function tG($){if(!$)return{ok:!1,reason:"path \u4E0D\u80FD\u4E3A\u7A7A"};if(!$.startsWith("/"))return{ok:!1,reason:"path \u5FC5\u987B\u4EE5 / \u5F00\u5934"};if($.length>1&&$.endsWith("/"))return{ok:!1,reason:"path \u672B\u5C3E\u4E0D\u80FD\u662F /\uFF08\u6839\u8DEF\u5F84 / \u9664\u5916\uFF09"};if($.includes("//"))return{ok:!1,reason:"path \u4E0D\u80FD\u5305\u542B //"};if($.includes(".."))return{ok:!1,reason:"path \u4E0D\u80FD\u5305\u542B .."};return{ok:!0,reason:""}}function r1($,J){if(J.length===0)return $;let Z=[];for(let X of $){let Y=typeof X?.path==="string"?String(X.path).trim():"";if(Y&&t$(Y,J))continue;let H=Array.isArray(X?.children)?X.children:null;if(H&&H.length>0){let G=r1(H,J);if(G.length>0)X.children=G;else delete X.children}Z.push(X)}return Z}var i1=async($,J={})=>{let Z=!1,X=await l1($),Y=T$(J.disableMenus),H=r1(X,Y),G=[];for(let V of H)G.push({menu:V,depth:1});let U=new Set;while(G.length>0){let V=G.pop(),K=V?.menu,F=typeof V?.depth==="number"?V.depth:0;if(K===null||typeof K!=="object"){Z=!0,P.warn({menu:K},"\u83DC\u5355\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61");continue}if(F>3){Z=!0,P.warn({path:K?.path,depth:F},"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09");continue}let A=K.children;if(typeof A<"u"&&!Array.isArray(A)){Z=!0,P.warn({path:K?.path,childrenType:typeof A},"\u83DC\u5355 children \u5FC5\u987B\u662F\u6570\u7EC4");continue}if(Array.isArray(A)&&A.length>0)if(F>=3)Z=!0,P.warn({path:K?.path,depth:F},"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09");else for(let T of A)G.push({menu:T,depth:F+1});let j=typeof K.path==="string"?K.path.trim():"",C=typeof K.name==="string"?K.name.trim():"",w=typeof K.sort==="number"?K.sort:999999;if(typeof K.path==="string")K.path=j;if(typeof K.name==="string")K.name=C;if(typeof K.sort>"u")K.sort=w;if(!j){Z=!0,P.warn({menu:K},"\u83DC\u5355\u7F3A\u5C11 path\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09");continue}let E=tG(j);if(!E.ok)Z=!0,P.warn({path:j,reason:E.reason},"\u83DC\u5355 path \u4E0D\u5408\u6CD5");if(!C)Z=!0,P.warn({path:j,menu:K},"\u83DC\u5355\u7F3A\u5C11 name\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09");if(typeof K.sort<"u"&&typeof K.sort!=="number")Z=!0,P.warn({path:j,sort:K.sort},"\u83DC\u5355 sort \u5FC5\u987B\u662F number");if(typeof K.sort==="number"&&(!Number.isFinite(K.sort)||K.sort<1))Z=!0,P.warn({path:j,sort:K.sort},"\u83DC\u5355 sort \u6700\u5C0F\u503C\u4E3A 1");if(U.has(j)){Z=!0,P.warn({path:j},"\u83DC\u5355 path \u91CD\u590D\uFF08\u4E25\u683C\u6A21\u5F0F\u7981\u6B62\u91CD\u590D path\uFF09");continue}U.add(j)}if(Z)throw Error("\u83DC\u5355\u7ED3\u6784\u68C0\u67E5\u5931\u8D25");return H};a();async function t1($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let X of $)try{if(!s(X)){P.warn(u(X,["handler"]),"\u63D2\u4EF6\u5BFC\u51FA\u5FC5\u987B\u662F\u5BF9\u8C61\uFF08export default { deps, handler }\uFF09"),J=!0;continue}if(typeof X.moduleName!=="string"||X.moduleName.trim()===""){P.warn(u(X,["handler"]),"\u63D2\u4EF6\u7684 moduleName \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u7528\u4E8E deps \u4E0E\u8FD0\u884C\u65F6\u6302\u8F7D\uFF09"),J=!0;continue}if(!Object.prototype.hasOwnProperty.call(X,"enable")){P.warn(u(X,["handler"]),"\u63D2\u4EF6\u7684 enable \u5C5E\u6027\u662F\u5FC5\u586B\u9879\uFF0C\u4E14\u5FC5\u987B\u663E\u5F0F\u58F0\u660E\u4E3A true \u6216 false"),J=!0;continue}if(typeof X.enable!=="boolean"){P.warn(u(X,["handler"]),"\u63D2\u4EF6\u7684 enable \u5C5E\u6027\u5FC5\u987B\u662F boolean\uFF08true/false\uFF09\uFF0C\u4E0D\u5141\u8BB8 0/1 \u7B49\u5176\u4ED6\u7C7B\u578B"),J=!0;continue}if(X.source==="core"){let Y=typeof X.name==="string"?X.name:"";if(Y===""){P.warn(u(X,["handler"]),"core \u5185\u7F6E\u63D2\u4EF6\u5FC5\u987B\u663E\u5F0F\u8BBE\u7F6E name\uFF08string\uFF09\uFF0C\u7528\u4E8E\u786E\u5B9A\u63D2\u4EF6\u540D\u79F0"),J=!0;continue}if(!Z.test(Y)){P.warn(u(X,["handler"]),"core \u5185\u7F6E\u63D2\u4EF6\u7684 name \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u4F8B\u5982 logger / redis_cache\uFF09\uFF0C\u4E0D\u5141\u8BB8\u7A7A\u683C\u3001\u9A7C\u5CF0\u6216\u5176\u4ED6\u5B57\u7B26"),J=!0;continue}if(!Z.test(X.moduleName)){P.warn(u(X,["handler"]),"core \u5185\u7F6E\u63D2\u4EF6\u7684 moduleName \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u4E14\u5FC5\u987B\u4E0E name \u4E00\u81F4\uFF09"),J=!0;continue}if(Y!==X.moduleName){P.warn(u(X,["handler"]),"core \u5185\u7F6E\u63D2\u4EF6\u7684 name \u5FC5\u987B\u4E0E moduleName \u5B8C\u5168\u4E00\u81F4"),J=!0;continue}if(typeof X.filePath!=="string"||!X.filePath.startsWith(`core:plugin:${Y}`)){P.warn(u(X,["handler"]),"core \u5185\u7F6E\u63D2\u4EF6\u5FC5\u987B\u6765\u81EA\u9759\u6001\u6CE8\u518C\uFF08filePath \u5FC5\u987B\u4EE5 core:plugin:<name> \u5F00\u5934\uFF09\uFF0C\u4E0D\u5141\u8BB8\u901A\u8FC7\u626B\u63CF\u76EE\u5F55\u52A0\u8F7D"),J=!0;continue}}if(!Array.isArray(X.deps)){P.warn(u(X,["handler"]),"\u63D2\u4EF6\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"),J=!0;continue}if(X.deps.some((Y)=>typeof Y!=="string"))P.warn(u(X,["handler"]),"\u63D2\u4EF6\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"),J=!0;if(typeof X.handler!=="function"){P.warn(u(X,["handler"]),"\u63D2\u4EF6\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"),J=!0;continue}}catch(Y){P.error({err:Y,item:X},"\u63D2\u4EF6\u89E3\u6790\u5931\u8D25"),J=!0}if(J)throw Error("\u63D2\u4EF6\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var a1=["id","created_at","updated_at","deleted_at","state"],e1=["string","number","text","array_string","array_text","array_number_string","array_number_text"],$Y=["name","type","min","max","default","detail","index","unique","nullable","unsigned","regexp"],aG=/^_?[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)*$/,eG=/^[\u4e00-\u9fa5a-zA-Z0-9 _-]+$/,JY=65535;async function ZY($){let J=!1;for(let Z of $){if(Z.type!=="table")continue;let X=typeof Z.sourceName==="string"?Z.sourceName:"";try{let Y=Z.fileName,H=Z.content||{};if(!aG.test(Y)){P.warn(`${X}\u8868 ${Y} \u6587\u4EF6\u540D\u5FC5\u987B\u4F7F\u7528\u5C0F\u9A7C\u5CF0\u547D\u540D\uFF08\u4F8B\u5982 testCustomers.json\uFF09`),J=!0;continue}for(let[G,U]of Object.entries(H)){if(typeof U!=="object"||U===null||Array.isArray(U)){P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u89C4\u5219\u5FC5\u987B\u4E3A\u5BF9\u8C61`),J=!0;continue}if(a1.includes(G))P.warn(`${X}\u8868 ${Y} \u6587\u4EF6\u5305\u542B\u4FDD\u7559\u5B57\u6BB5 ${G}\uFF0C`+`\u4E0D\u80FD\u5728\u8868\u5B9A\u4E49\u4E2D\u4F7F\u7528\u4EE5\u4E0B\u5B57\u6BB5: ${a1.join(", ")}`),J=!0;let V=U,F=Object.keys(V).filter((T)=>!$Y.includes(T));if(F.length>0)P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5305\u542B\u975E\u6CD5\u5C5E\u6027: ${F.join(", ")}\uFF0C`+`\u5141\u8BB8\u7684\u5C5E\u6027\u4E3A: ${$Y.join(", ")}`),J=!0;if(!V.name||typeof V.name!=="string"){P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5 name \u6216\u7C7B\u578B\u9519\u8BEF`),J=!0;continue}if(!V.type||typeof V.type!=="string"){P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5 type \u6216\u7C7B\u578B\u9519\u8BEF`),J=!0;continue}if(V.min!==void 0&&!(V.min===null||typeof V.min==="number"))P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5 min \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u6570\u5B57`),J=!0;if(V.max!==void 0&&!(V.max===null||typeof V.max==="number"))P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5 max \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u6570\u5B57`),J=!0;if(V.detail!==void 0&&typeof V.detail!=="string")P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5 detail \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32`),J=!0;if(V.index!==void 0&&typeof V.index!=="boolean")P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5 index \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(V.unique!==void 0&&typeof V.unique!=="boolean")P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5 unique \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(V.nullable!==void 0&&typeof V.nullable!=="boolean")P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5 nullable \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(V.unsigned!==void 0&&typeof V.unsigned!=="boolean")P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5 unsigned \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(V.regexp!==void 0&&V.regexp!==null&&typeof V.regexp!=="string")P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5 regexp \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u5B57\u7B26\u4E32`),J=!0;let{name:A,type:j,min:C,max:w,default:E}=V;if(!eG.test(A))P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5\u540D\u79F0 "${A}" \u683C\u5F0F\u9519\u8BEF\uFF0C`+"\u5FC5\u987B\u4E3A\u4E2D\u6587\u3001\u6570\u5B57\u3001\u5B57\u6BCD\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u3001\u7A7A\u683C"),J=!0;if(!e1.includes(j))P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5\u7C7B\u578B "${j}" \u683C\u5F0F\u9519\u8BEF\uFF0C`+`\u5FC5\u987B\u4E3A${e1.join("\u3001")}\u4E4B\u4E00`),J=!0;if(j!=="number"&&V.unsigned!==void 0)P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u5B57\u6BB5\u7C7B\u578B\u4E3A ${j}\uFF0C\u4E0D\u5141\u8BB8\u8BBE\u7F6E unsigned\uFF08\u4EC5 number \u7C7B\u578B\u6709\u6548\uFF09`),J=!0;if(V.unique===!0&&V.index===!0)P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u540C\u65F6\u8BBE\u7F6E\u4E86 unique=true \u548C index=true\uFF0C`+"unique \u548C index \u4E0D\u80FD\u540C\u65F6\u8BBE\u7F6E\uFF0C\u8BF7\u5220\u9664\u5176\u4E00\uFF08\u5426\u5219\u4F1A\u521B\u5EFA\u91CD\u590D\u7D22\u5F15\uFF09"),J=!0;if(C!==void 0&&w!==void 0&&C!==null&&w!==null){if(C>w)P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u6700\u5C0F\u503C "${C}" \u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u503C "${w}"`),J=!0}if(j==="text"||j==="array_text"||j==="array_number_text"){if(C!==void 0&&C!==null)P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u7684 ${j} \u7C7B\u578B\u6700\u5C0F\u503C\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${C}"`),J=!0;if(w!==void 0&&w!==null)P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u7684 ${j} \u7C7B\u578B\u6700\u5927\u957F\u5EA6\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${w}"`),J=!0;if(E!==void 0&&E!==null)P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u4E3A ${j} \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${E}"`),J=!0;if(V.index===!0)P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u4E3A ${j} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u521B\u5EFA\u7D22\u5F15\uFF08index=true \u65E0\u6548\uFF09`),J=!0;if(V.unique===!0)P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u4E3A ${j} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u552F\u4E00\u7EA6\u675F\uFF08unique=true \u65E0\u6548\uFF09`),J=!0}else if(j==="string"||j==="array_string"||j==="array_number_string"){if(w!==void 0&&(w===null||typeof w!=="number"))P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u4E3A ${j} \u7C7B\u578B\uFF0C`+`\u6700\u5927\u957F\u5EA6\u5FC5\u987B\u4E3A\u6570\u5B57\uFF0C\u5F53\u524D\u4E3A "${w}"`),J=!0;else if(w!==void 0&&w>JY)P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u6700\u5927\u957F\u5EA6 ${w} \u8D8A\u754C\uFF0C`+`${j} \u7C7B\u578B\u957F\u5EA6\u5FC5\u987B\u5728 1..${JY} \u8303\u56F4\u5185`),J=!0}else if(j==="number"){if(E!==void 0&&E!==null&&typeof E!=="number")P.warn(`${X}\u8868 ${Y} \u6587\u4EF6 ${G} \u4E3A number \u7C7B\u578B\uFF0C`+`\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A\u6570\u5B57\u6216 null\uFF0C\u5F53\u524D\u4E3A "${E}"`),J=!0}}}catch(Y){P.error(`${X}\u8868 ${Z.fileName} \u89E3\u6790\u5931\u8D25`,Y),J=!0}}if(J)throw Error("\u8868\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var{SQL:XY,RedisClient:$Q}=globalThis.Bun;class H${static sqlClient=null;static redisClient=null;static sqlConnectedAt=null;static redisConnectedAt=null;static sqlPoolMax=1;static async connectSql($){let J=$||{},Z=J.type||"mysql",X=J.host||"127.0.0.1",Y=J.port||3306,H=encodeURIComponent(J.username||"root"),G=encodeURIComponent(J.password||"root"),U=encodeURIComponent(J.database||"befly_demo"),V;if(Z==="sqlite")V=U;else{if(!X||!U)throw Error("\u6570\u636E\u5E93\u914D\u7F6E\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E\u53C2\u6570");V=`${Z}://${H}:${G}@${X}:${Y}/${U}`}let K;if(Z==="sqlite")K=new XY(V);else K=new XY({url:V,max:J.poolMax??1,bigint:!1});try{let A=(async()=>{let C="";if(Z==="sqlite")C=(await K`SELECT sqlite_version() AS version`)?.[0]?.version;else if(Z==="postgresql"||Z==="postgres")C=(await K`SELECT version() AS version`)?.[0]?.version;else C=(await K`SELECT VERSION() AS version`)?.[0]?.version;return C})(),j=new Promise((C,w)=>{setTimeout(()=>{w(Error(`\u6570\u636E\u5E93\u8FDE\u63A5\u8D85\u65F6 (${30000}ms)`))},30000)});return await Promise.race([A,j]),this.sqlClient=K,this.sqlConnectedAt=Date.now(),this.sqlPoolMax=J.poolMax??1,K}catch(F){P.error({err:F},"[Connect] SQL \u8FDE\u63A5\u5931\u8D25");try{await K?.close()}catch{}throw F}}static async disconnectSql(){if(this.sqlClient){try{await this.sqlClient.close()}catch($){P.error({err:$},"[Connect] \u5173\u95ED SQL \u8FDE\u63A5\u65F6\u51FA\u9519")}this.sqlClient=null,this.sqlConnectedAt=null}}static getSql(){if(!this.sqlClient)throw Error("SQL \u5BA2\u6237\u7AEF\u672A\u8FDE\u63A5\uFF0C\u8BF7\u5148\u8C03\u7528 Connect.connectSql()");return this.sqlClient}static async connectRedis($){let J=$||{};try{let Z=J.host||"127.0.0.1",X=J.port||6379,Y=J.username||"",H=J.password||"",G=J.db||0,U="";if(Y&&H)U=`${Y}:${H}@`;else if(H)U=`:${H}@`;let V=`redis://${U}${Z}:${X}/${G}`,K=new $Q(V,{connectionTimeout:30000,idleTimeout:0,autoReconnect:!0,maxRetries:3,enableOfflineQueue:!0,enableAutoPipelining:!0});return await K.ping(),this.redisClient=K,this.redisConnectedAt=Date.now(),K}catch(Z){throw P.error({err:Z},"[Connect] Redis \u8FDE\u63A5\u5931\u8D25"),Error(`Redis \u8FDE\u63A5\u5931\u8D25: ${Z.message}`)}}static async disconnectRedis(){if(this.redisClient){try{this.redisClient.close(),this.redisConnectedAt=null}catch($){P.error({err:$},"[Connect] \u5173\u95ED Redis \u8FDE\u63A5\u65F6\u51FA\u9519")}this.redisClient=null}}static getRedis(){if(!this.redisClient)throw Error("Redis \u5BA2\u6237\u7AEF\u672A\u8FDE\u63A5\uFF0C\u8BF7\u5148\u8C03\u7528 Connect.connectRedis()");return this.redisClient}static async connect($){try{await this.connectSql($.db||{}),await this.connectRedis($.redis||{})}catch(J){throw P.error({err:J},"\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25"),await this.disconnect(),J}}static async disconnect(){await this.disconnectSql(),await this.disconnectRedis()}static isConnected(){return{sql:this.sqlClient!==null,redis:this.redisClient!==null}}static getStatus(){let $=Date.now();return{sql:{connected:this.sqlClient!==null,connectedAt:this.sqlConnectedAt,uptime:this.sqlConnectedAt?$-this.sqlConnectedAt:null,poolMax:this.sqlPoolMax},redis:{connected:this.redisClient!==null,connectedAt:this.redisConnectedAt,uptime:this.redisConnectedAt?$-this.redisConnectedAt:null}}}static __setMockSql($){this.sqlClient=$}static __setMockRedis($){this.redisClient=$}static __reset(){this.sqlClient=null,this.redisClient=null,this.sqlConnectedAt=null,this.redisConnectedAt=null,this.sqlPoolMax=1}}a();a();var LJ={"@id":{name:"ID",type:"number",min:1,max:null},"@page":{name:"\u9875\u7801",type:"number",min:1,max:9999,default:1},"@limit":{name:"\u6BCF\u9875\u6570\u91CF",type:"number",min:1,max:100,default:30},"@keyword":{name:"\u5173\u952E\u8BCD",type:"string",min:0,max:50},"@state":{name:"\u72B6\u6001",type:"number",regex:"^[0-2]$"}};function YY($,J,Z){if(!$||typeof $!=="object")return $;let X={};for(let[Y,H]of Object.entries($)){if(typeof H==="string"&&H.startsWith("@")){if(LJ[H]){X[Y]=LJ[H];continue}let G=Object.keys(LJ).join(", ");throw Error(`API [${J}] (${Z}) \u5B57\u6BB5 [${Y}] \u5F15\u7528\u4E86\u672A\u5B9A\u4E49\u7684\u9884\u8BBE\u5B57\u6BB5 "${H}"\u3002\u53EF\u7528\u7684\u9884\u8BBE\u5B57\u6BB5\u6709: ${G}`)}X[Y]=H}return X}async function HY($){let J=new Map;for(let Z of $){let X=Z.type;if(X&&X!=="api")continue;try{let Y=Z;Y.fields=YY(Y.fields||{},Y.name,Y.routePath),J.set(Y.routePath,Y)}catch(Y){throw P.error({err:Y,api:Z.relativePath,file:Z.filePath},"\u63A5\u53E3\u52A0\u8F7D\u5931\u8D25"),Y}}return J}a();function EJ($,J={}){let Z=J.moduleLabel||"\u6A21\u5757",X=J.getName||((A)=>{let j=A.moduleName;if(typeof j==="string"&&j.trim()!=="")return j;return O$(A.fileName)}),Y=J.getDeps||((A)=>A.deps),H=[],G=new Set,U=new Set,V={},K=!0;for(let A of $){let j=X(A);if(typeof j!=="string"||j.trim()===""){P.error({item:A},`${Z} \u540D\u79F0\u89E3\u6790\u5931\u8D25\uFF08getName \u8FD4\u56DE\u7A7A\u5B57\u7B26\u4E32\uFF09`),K=!1;continue}if(V[j]){P.error({name:j,first:V[j],second:A},`${Z} \u540D\u79F0\u91CD\u590D\uFF0C\u65E0\u6CD5\u6839\u636E deps \u552F\u4E00\u5B9A\u4F4D`),K=!1;continue}V[j]=A}if(!K)return!1;for(let A of $){let j=X(A),C=Y(A);if(!Array.isArray(C)){P.error({module:j,item:A},`${Z} \u7684 deps \u5FC5\u987B\u662F\u6570\u7EC4`),K=!1;continue}for(let w of C){if(typeof w!=="string"){P.error({module:j,dependency:w,item:A},`${Z} \u7684 deps \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4`),K=!1;continue}if(!V[w])P.error({module:j,dependency:w},`${Z} \u4F9D\u8D56\u672A\u627E\u5230`),K=!1}}if(!K)return!1;let F=(A)=>{if(G.has(A))return;if(U.has(A)){P.error({module:A},`${Z} \u5FAA\u73AF\u4F9D\u8D56`),K=!1;return}let j=V[A];if(!j)return;let C=Y(j);U.add(A);for(let w of C)F(w);U.delete(A),G.add(A),H.push(j)};for(let A of $){let j=X(A);F(j)}return K?H:!1}async function WY($){let J=[],Z=$.filter((Y)=>{let H=Y?.moduleName;if(typeof H!=="string"||H.trim()==="")return!1;if(Y?.enable===!1)return!1;return!0}),X=EJ(Z,{moduleLabel:"\u94A9\u5B50"});if(X===!1)throw Error("\u94A9\u5B50\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let Y of X){let H=Y.moduleName,G=Y;J.push({name:H,enable:!0,deps:G.deps,handler:G.handler})}return J}a();async function GY($,J){let Z=[],X=$.filter((H)=>{let G=H?.moduleName;if(typeof G!=="string"||G.trim()==="")return!1;if(H?.enable===!1)return!1;return!0}),Y=EJ(X,{moduleLabel:"\u63D2\u4EF6"});if(Y===!1)throw Error("\u63D2\u4EF6\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let H of Y){let G=H.moduleName,U=H;try{let V=typeof U.handler==="function"?await U.handler(J):{};J[G]=V,Z.push({name:G,enable:!0,deps:U.deps,handler:U.handler})}catch(V){throw P.error({err:V,plugin:G},"\u63D2\u4EF6\u521D\u59CB\u5316\u5931\u8D25"),V}}return Z}RJ();a();function QY($,J){let Z=$.headers.get("x-forwarded-for");if(typeof Z==="string"&&Z.trim()){let U=Z.split(",")[0];if(typeof U==="string"&&U.trim())return U.trim()}let X=$.headers.get("x-real-ip");if(typeof X==="string"&&X.trim())return X.trim();let Y=$.headers.get("cf-connecting-ip");if(typeof Y==="string"&&Y.trim())return Y.trim();let H=$.headers.get("x-client-ip");if(typeof H==="string"&&H.trim())return H.trim();let G=$.headers.get("true-client-ip");if(typeof G==="string"&&G.trim())return G.trim();if(J&&typeof J.requestIP==="function"){let U=J.requestIP($);if(U&&typeof U.address==="string"&&U.address.trim())return U.address.trim()}return"unknown"}a();function R$($,J,Z=1,X=null,Y=null,H=null){if($.requestId)P.info({event:"request_blocked",reason:J,reasonCode:H,code:Z,detail:Y},"request blocked");return Response.json({code:Z,msg:J,data:X,detail:Y},{headers:$.corsHeaders})}function sZ($){if($.api&&$.requestId)P.info({event:"request_done"},"request done");if($.response)return $.response;if($.result!==void 0){let J=$.result;if(typeof J==="string")J={code:0,msg:J};else if(J&&typeof J==="object"){if(!("code"in J))J={code:0,...J}}if(J&&typeof J==="object"){let Z=JSON.stringify(J,(X,Y)=>typeof Y==="bigint"?Y.toString():Y);return new Response(Z,{headers:{...$.corsHeaders,"Content-Type":"application/json"}})}else return Response.json(J,{headers:$.corsHeaders})}return Response.json({code:1,msg:"\u672A\u751F\u6210\u54CD\u5E94"},{headers:$.corsHeaders})}function zY($,J,Z){return async(X,Y)=>{let H=z1(),U=new URL(X.url).pathname||"/",V=QY(X,Y),K=Date.now(),F={method:X.method,body:{},user:{},req:X,now:K,ip:V,headers:X.headers,route:U,requestId:H,corsHeaders:{"X-Request-ID":H},api:$.get(U),response:void 0,result:void 0};return _1({requestId:H,method:X.method,route:U,ip:V,now:K},async()=>{try{for(let A of J)if(await A.handler(Z,F),F.response)return F.response;if(F.api&&X.method!=="OPTIONS"){let A={event:"request",apiName:F.api.name};if(F.body&&Object.keys(F.body).length>0)A.body=F.body;P.info(A,"request")}if(!F.api){if(X.method!=="OPTIONS")F.response=Response.json({code:1,msg:"\u63A5\u53E3\u4E0D\u5B58\u5728"},{headers:F.corsHeaders})}else if(F.api.handler){let A=await F.api.handler(Z,F);if(A instanceof Response)F.response=A;else F.result=A}return sZ(F)}catch(A){let j=F.api?U:X.url;return P.error({err:A,path:j},"\u8BF7\u6C42\u9519\u8BEF"),F.result={code:1,msg:"\u5185\u90E8\u670D\u52A1\u9519\u8BEF"},sZ(F)}})}}A$();a();A$();import{fileURLToPath as JQ}from"url";var ZQ=JQ(import.meta.url),M$=SJ(ZQ);var a4=P$(M$).endsWith("/dist")?M$:n(M$,"dist"),e4=n(M$,"checks"),$5=n(M$,"plugins"),J5=n(M$,"hooks"),Z5=n(M$,"apis"),X5=n(M$,"tables"),d0=process.cwd(),Y5=n(d0,"checks"),H5=n(d0,"plugins"),W5=n(d0,"hooks"),G5=n(d0,"apis"),Q5=n(d0,"tables"),UY=n(d0,"addons");function TJ($,J={}){let Z=J.origin||"*";return{"Access-Control-Allow-Origin":Z==="*"?$.headers.get("origin")||"*":Z,"Access-Control-Allow-Methods":J.methods||"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":J.allowedHeaders||"Content-Type, Authorization, authorization, token","Access-Control-Expose-Headers":J.exposedHeaders||"Content-Range, X-Content-Range, Authorization, authorization, token","Access-Control-Max-Age":String(J.maxAge||86400),"Access-Control-Allow-Credentials":J.credentials||"true"}}function VY($=void 0){return async(J)=>{let Z=TJ(J,$),X=new URL(J.url),Y=n(d0,"public",X.pathname);try{if(J.method==="OPTIONS")return new Response(null,{status:204,headers:Z});let H=Bun.file(Y);if(await H.exists())return new Response(H,{headers:{"Content-Type":H.type||"application/octet-stream",...Z}});else return Response.json({code:1,msg:"\u6587\u4EF6\u672A\u627E\u5230"},{headers:Z})}catch(H){return P.error({err:H},"\u9759\u6001\u6587\u4EF6\u5904\u7406\u5931\u8D25"),Response.json({code:1,msg:"\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25"},{headers:Z})}}}a();async function KY($,J){if(!$.db)throw Error("syncApi: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncApi: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_api")).data){P.debug(`${"addon_admin_api"} \u8868\u4E0D\u5B58\u5728`);return}let Y=(await $.db.getAll({table:"addon_admin_api",fields:["id","routePath","name","addonName","state"],where:{state$gte:0}})).data.lists||[],H=Q1(Y,(F)=>F.routePath),G=[],U=[],V=[],K=new Set;for(let F of J){let A=F.type;if(A&&A!=="api")continue;let j=F.routePath;K.add(F.routePath);let C=H[j];if(C){if(F.name!==C.name||F.routePath!==C.routePath||F.addonName!==C.addonName)U.push({id:C.id,api:F})}else G.push(F)}for(let F of Y)if(!K.has(F.routePath))V.push(F.id);if(U.length>0)try{await $.db.updBatch("addon_admin_api",U.map((F)=>{return{id:F.id,data:{name:F.api.name,routePath:F.api.routePath,addonName:F.api.addonName}}}))}catch(F){P.error({err:F},"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u66F4\u65B0\u5931\u8D25")}if(G.length>0)try{await $.db.insBatch("addon_admin_api",G.map((F)=>{return{name:F.name,routePath:F.routePath,addonName:F.addonName}}))}catch(F){P.error({err:F},"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u65B0\u589E\u5931\u8D25")}if(V.length>0)try{await $.db.delForceBatch("addon_admin_api",V)}catch(F){P.error({err:F},"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u5220\u9664\u5931\u8D25")}}async function OY($){if(!$.cache)throw Error("syncCache: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");await $.cache.cacheApis(),await $.cache.cacheMenus(),await $.cache.rebuildRoleApiPermissions()}import{createSign as XQ}from"crypto";class y${static md5($,J="hex"){let Z=new Bun.CryptoHasher("md5");return Z.update($),Z.digest(J)}static hmacMd5($,J,Z="hex"){let X=new Bun.CryptoHasher("md5",$);return X.update(J),X.digest(Z)}static sha1($,J="hex"){let Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest(J)}static hmacSha1($,J,Z="hex"){let X=new Bun.CryptoHasher("sha1",$);return X.update(J),X.digest(Z)}static sha256($,J="hex"){let Z=new Bun.CryptoHasher("sha256");return Z.update($),Z.digest(J)}static rsaSha256($,J,Z="hex"){let X=XQ("RSA-SHA256");return X.update($),X.sign(J,Z)}static hmacSha256($,J,Z="hex"){let X=new Bun.CryptoHasher("sha256",$);return X.update(J),X.digest(Z)}static sha512($,J="hex"){let Z=new Bun.CryptoHasher("sha512");return Z.update($),Z.digest(J)}static hmacSha512($,J,Z="hex"){let X=new Bun.CryptoHasher("sha512",$);return X.update(J),X.digest(Z)}static hash($,J,Z="hex"){let X=new Bun.CryptoHasher($);return X.update(J),X.digest(Z)}static hmac($,J,Z,X="hex"){let Y=new Bun.CryptoHasher($,J);return Y.update(Z),Y.digest(X)}static async hashFile($,J="sha256",Z="hex"){let X=Bun.file($),Y=new Bun.CryptoHasher(J),G=X.stream().getReader();try{while(!0){let{done:U,value:V}=await G.read();if(U)break;Y.update(V)}return Y.digest(Z)}finally{G.releaseLock()}}static async hashPassword($,J={}){let Z={algorithm:"bcrypt",...J};return await Bun.password.hash($,Z)}static async verifyPassword($,J){return await Bun.password.verify($,J)}static base64Encode($){return Buffer.from($,"utf8").toString("base64")}static base64Decode($){return Buffer.from($,"base64").toString("utf8")}static randomString($){let J=Math.ceil($/2),Z=crypto.getRandomValues(new Uint8Array(J)),X="";for(let Y=0;Y<Z.length;Y++)X+=Z[Y].toString(16).padStart(2,"0");return X.slice(0,$)}static fastHash($,J=0){let Z=Bun.hash($,J);return typeof Z==="bigint"?Number(Z):Z}}a();async function _Y($,J={}){if(!J.devPassword)return;let Z=typeof J.devEmail==="string"&&J.devEmail.length>0?J.devEmail:"dev@qq.com";if(!$.db)throw Error("syncDev: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncDev: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_admin")).data){P.debug("addon_admin_admin \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_role")).data){P.debug("addon_admin_role \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_menu")).data){P.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}let X=await $.db.getAll({table:"addon_admin_menu",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),Y=Array.from(new Set((X.data.lists||[]).map((C)=>typeof C?.path==="string"?C.path.trim():"").filter((C)=>C.length>0))),H=await $.db.tableExists("addon_admin_api"),G=[];if(H.data){let C=await $.db.getAll({table:"addon_admin_api",fields:["routePath"],where:{state$gte:0},orderBy:["id#ASC"]});G=Array.from(new Set((C.data.lists||[]).map((w)=>{if(typeof w?.routePath!=="string")throw Error("syncDev: addon_admin_api.routePath \u5FC5\u987B\u662F\u5B57\u7B26\u4E32");let E=w.routePath.trim();if(E.length===0)throw Error("syncDev: addon_admin_api.routePath \u4E0D\u5141\u8BB8\u4E3A\u7A7A\u5B57\u7B26\u4E32");if(!E.startsWith("/"))throw Error(`syncDev: addon_admin_api.routePath \u5FC5\u987B\u662F pathname\uFF08\u4EE5 / \u5F00\u5934\uFF09\uFF0C\u5F53\u524D\u503C=${E}`);return E})))}let U=[{code:"dev",name:"\u5F00\u53D1\u8005\u89D2\u8272",description:"\u62E5\u6709\u6240\u6709\u83DC\u5355\u548C\u63A5\u53E3\u6743\u9650\u7684\u5F00\u53D1\u8005\u89D2\u8272",menus:Y,apis:G,sort:0},{code:"user",name:"\u7528\u6237\u89D2\u8272",description:"\u666E\u901A\u7528\u6237\u89D2\u8272",menus:[],apis:[],sort:1},{code:"admin",name:"\u7BA1\u7406\u5458\u89D2\u8272",description:"\u7BA1\u7406\u5458\u89D2\u8272",menus:[],apis:[],sort:2},{code:"guest",name:"\u8BBF\u5BA2\u89D2\u8272",description:"\u8BBF\u5BA2\u89D2\u8272",menus:[],apis:[],sort:3}],V=null;for(let C of U){let w=await $.db.getOne({table:"addon_admin_role",where:{code:C.code}});if(w.data){let{menus:E,apis:T}=C,v=Array.isArray(w.data.menus)?w.data.menus:[],L=Array.isArray(w.data.apis)?w.data.apis:[],D=v.length!==E.length||v.some((f,l)=>f!==E[l]),g=L.length!==T.length||L.some((f,l)=>f!==T[l]);if(w.data.name!==C.name||w.data.description!==C.description||D||g||w.data.sort!==C.sort)await $.db.updData({table:"addon_admin_role",where:{code:C.code},data:{name:C.name,description:C.description,menus:C.menus,apis:C.apis,sort:C.sort}});if(C.code==="dev")V=w.data}else{let E=await $.db.insData({table:"addon_admin_role",data:C});if(C.code==="dev")V={id:E.data}}}if(!V){P.error("dev \u89D2\u8272\u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u521B\u5EFA\u5F00\u53D1\u8005\u8D26\u53F7");return}let K=y$.sha256(J.devPassword+"befly"),F=await y$.hashPassword(K),A={nickname:"\u5F00\u53D1\u8005",email:Z,username:"dev",password:F,roleCode:"dev",roleType:"admin"};if((await $.db.getOne({table:"addon_admin_admin",where:{email:Z}})).data)await $.db.updData({table:"addon_admin_admin",where:{email:Z},data:A});else await $.db.insData({table:"addon_admin_admin",data:A})}a();oZ();function YQ($){let J=new Map,Z=[];for(let X of $)Z.push({menu:X,parentPathFromTree:""});while(Z.length>0){let X=Z.pop(),Y=X?X.menu:null;if(!Y)continue;let H=typeof Y.path==="string"?Y.path:"",G=Y.children;if(G&&Array.isArray(G)&&G.length>0){let A=typeof H==="string"?H:"";for(let j of G)Z.push({menu:j,parentPathFromTree:A})}if(!H)continue;let U=typeof Y.name==="string"?Y.name:"";if(!U)continue;let V=typeof Y.sort==="number"?Y.sort:999999,F=typeof Y.parentPath==="string"?Y.parentPath:typeof X?.parentPathFromTree==="string"?X.parentPathFromTree:s1(H);J.set(H,{path:H,name:U,sort:V,parentPath:F})}return J}async function FY($,J){if(!$.db)throw Error("syncMenu: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncMenu: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.config)throw Error("syncMenu: ctx.config \u672A\u521D\u59CB\u5316\uFF08config \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_menu")).data){P.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}let Z=T$($.config?.disableMenus),X=Z.length===0?J:(()=>{let U=(V)=>{let K=[];for(let F of V){let A=typeof F?.path==="string"?String(F.path).trim():"";if(A&&t$(A,Z))continue;let j=Array.isArray(F?.children)?F.children:null;if(j&&j.length>0){let C=U(j);if(C.length>0)F.children=C;else delete F.children}K.push(F)}return K};return U(J)})(),Y=YQ(X),H=new Set;for(let U of Y.keys())H.add(U);let G="addon_admin_menu";await $.db.trans(async(U)=>{let K=(await U.getAll({table:G,fields:["id","name","path","parentPath","sort","state"]})).data.lists||[],F=K.filter((L)=>typeof L?.state==="number"&&L.state>=0),A=new Map,j=new Set,C=new Map;for(let L of F){if(typeof L?.path!=="string"||!L.path)continue;if(typeof L?.id!=="number")continue;let D=A.get(L.path);if(!D){A.set(L.path,L);continue}let g=typeof D?.id==="number"?D.id:0,N=L.id;if(N>g){if(A.set(L.path,L),g>0)j.add(g);let f=C.get(L.path)||{keptId:N,removedIds:[]};if(f.keptId=N,g>0)f.removedIds.push(g);C.set(L.path,f)}else{if(N>0)j.add(N);let f=C.get(L.path)||{keptId:g,removedIds:[]};if(f.keptId=g,N>0)f.removedIds.push(N);C.set(L.path,f)}}if(C.size>0){let L=[];for(let D of C.entries()){let g=D[0],N=D[1];if(L.push({path:g,keptId:N.keptId,removedIds:N.removedIds}),L.length>=10)break}P.warn({table:G,duplicatePaths:C.size,duplicateIds:j.size,examples:L},"addon_admin_menu \u68C0\u6D4B\u5230\u91CD\u590D path \u8BB0\u5F55\uFF1A\u5DF2\u4FDD\u7559 id \u6700\u5927\u7684\u4E00\u6761\u5E76\u5220\u9664\u5176\u4F59\u8BB0\u5F55")}let w=[],E=[];for(let L of Y.values()){let D=A.get(L.path);if(D){let g=typeof D.parentPath==="string"?D.parentPath:"";if(D.name!==L.name||D.sort!==L.sort||g!==L.parentPath)w.push({id:D.id,data:{name:L.name,path:L.path,parentPath:L.parentPath,sort:L.sort}})}else E.push({name:L.name,path:L.path,parentPath:L.parentPath,sort:L.sort})}if(w.length>0)await U.updBatch(G,w);if(E.length>0)await U.insBatch(G,E);let T=new Set;if(Z.length>0)for(let L of K){let D=typeof L?.path==="string"?String(L.path).trim():"";if(!D)continue;if(t$(D,Z)){if(typeof L?.id==="number"&&L.id>0)T.add(L.id)}}for(let L of F){if(typeof L?.path!=="string"||!L.path)continue;if(!H.has(L.path)){if(typeof L?.id==="number")T.add(L.id)}}for(let L of j)if(typeof L==="number"&&L>0)T.add(L);let v=Array.from(T);if(v.length>0)await U.delForceBatch(G,v)})}class X0{static apisAll(){return"apis:all"}static menusAll(){return"menus:all"}static roleInfo($){return`role:info:${$}`}static roleApis($){return`role:apis:${$}`}static tableColumns($){return`table:columns:${$}`}}var f$=null;function h$($){let J=Error(`\u672A\u77E5\u6570\u636E\u5E93\u65B9\u8A00: ${String($)}`);if($!=="mysql"&&$!=="postgresql"&&$!=="sqlite")throw J;if(!f$)f$=new Map,f$.set("mysql",new vJ),f$.set("postgresql",new AY),f$.set("sqlite",new RY);let Z=f$.get($);if(!Z)throw J;return Z}function NJ($){if($.dialect==="mysql")return{columns:{sql:"SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION",params:[$.dbName,$.table]}};if($.dialect==="postgresql"){let X=$.schema&&$.schema.trim()!==""?$.schema:"public",Y={sql:"SELECT column_name, data_type, character_maximum_length, is_nullable, column_default FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position",params:[X,$.table]},H={sql:"SELECT a.attname AS column_name, col_description(c.oid, a.attnum) AS column_comment FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname = ? AND c.relname = ? AND a.attnum > 0",params:[X,$.table]};return{columns:Y,comments:H}}return{columns:h$("sqlite").getTableColumnsQuery($.table)}}function lZ($){if($.dialect==="mysql")return{sql:"SELECT INDEX_NAME, COLUMN_NAME FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND INDEX_NAME != 'PRIMARY' ORDER BY INDEX_NAME",params:[$.dbName,$.table]};if($.dialect==="postgresql")return{sql:"SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = ? AND tablename = ?",params:[$.schema&&$.schema.trim()!==""?$.schema:"public",$.table]};throw Error(`getSyncTableIndexesQuery \u4E0D\u652F\u6301\u65B9\u8A00: ${String($.dialect)}`)}class vJ{name="mysql";supportsSchema=!0;quoteIdent($){if(typeof $!=="string")throw Error(`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`);let J=$.trim();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684 SQL \u6807\u8BC6\u7B26: ${J}`);return`\`${J}\``}getTableColumnsQuery($,J){return{sql:`SHOW COLUMNS FROM ${this.quoteIdent($)}`,params:[]}}getTableColumnsFromResult($){if(!Array.isArray($))return[];let J=[];for(let Z of $){let X=Z?.Field;if(typeof X==="string"&&X.length>0)J.push(X)}return J}tableExistsQuery($,J){if(typeof J==="string"&&J.trim()!=="")return{sql:"SELECT COUNT(*) as count FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?",params:[J,$]};return{sql:"SELECT COUNT(*) as count FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?",params:[$]}}}class AY{name="postgresql";supportsSchema=!0;quoteIdent($){if(typeof $!=="string")throw Error(`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`);let J=$.trim();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684 SQL \u6807\u8BC6\u7B26: ${J}`);return`"${J}"`}getTableColumnsQuery($,J){if(typeof J==="string"&&J.trim()!=="")return{sql:"SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position",params:[J,$]};return{sql:"SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position",params:[$]}}getTableColumnsFromResult($){if(!Array.isArray($))return[];let J=[];for(let Z of $){let X=Z?.column_name;if(typeof X==="string"&&X.length>0)J.push(X)}return J}tableExistsQuery($,J){if(typeof J==="string"&&J.trim()!=="")return{sql:"SELECT COUNT(*)::int as count FROM information_schema.tables WHERE table_schema = ? AND table_name = ?",params:[J,$]};return{sql:"SELECT COUNT(*)::int as count FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = ?",params:[$]}}}class RY{name="sqlite";supportsSchema=!1;quoteIdent($){if(typeof $!=="string")throw Error(`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`);let J=$.trim();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684 SQL \u6807\u8BC6\u7B26: ${J}`);return`"${J}"`}getTableColumnsQuery($,J){return{sql:`PRAGMA table_info(${this.quoteIdent($)})`,params:[]}}getTableColumnsFromResult($){if(!Array.isArray($))return[];let J=[];for(let Z of $){let X=Z?.name;if(typeof X==="string"&&X.length>0)J.push(X)}return J}tableExistsQuery($,J){return{sql:"SELECT COUNT(*) as count FROM sqlite_master WHERE type = 'table' AND name = ?",params:[$]}}}a();var kJ=async($,J)=>{try{let Z=[];if(!Array.isArray(J))throw Error("syncTable(items) \u53C2\u6570\u5FC5\u987B\u662F\u6570\u7EC4");if(!$)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx");if(!$.db)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.db");if(!$.redis)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.redis");if(!$.config)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.config");let X=String($.config.db?.type||"mysql").toLowerCase(),Y="mysql";if(X==="postgres"||X==="postgresql")Y="postgresql";else if(X==="sqlite")Y="sqlite";await HQ(Y,$.db);let H=$.config.db?.database||"",G={dbDialect:Y,db:$.db,dbName:H};for(let U of J){if(!U||U.type!=="table")continue;if(U.source!=="app"&&U.source!=="addon"&&U.source!=="core"){P.warn(`syncTable \u8DF3\u8FC7\u672A\u77E5\u6765\u6E90\u8868\u5B9A\u4E49: source=${String(U.source)} fileName=${String(U.fileName)}`);continue}let V=p(U.fileName),K=V;if(U.source==="addon"){if(!U.addonName||String(U.addonName).trim()==="")throw Error(`syncTable addon \u8868\u7F3A\u5C11 addonName: fileName=${String(U.fileName)}`);K=`addon_${p(U.addonName)}_${V}`}let F=U.content;if(!F||typeof F!=="object")throw Error(`syncTable \u8868\u5B9A\u4E49\u65E0\u6548: table=${K}`);for(let j of Object.values(F))jY(j);if(await EY(G,K))await QQ(G,K,F);else await vY(G,K,F);Z.push(K)}if(Z.length>0){let U=Z.map((V)=>X0.tableColumns(V));await $.redis.delBatch(U)}}catch(Z){throw P.error({err:Z},"\u6570\u636E\u5E93\u540C\u6B65\u5931\u8D25"),Z}},B$={MYSQL_MIN_MAJOR:8,POSTGRES_MIN_MAJOR:17,SQLITE_MIN_VERSION:"3.50.0",SQLITE_MIN_VERSION_NUM:35000},IY={length:"\u957F\u5EA6",datatype:"\u7C7B\u578B",comment:"\u6CE8\u91CA",default:"\u9ED8\u8BA4\u503C",nullable:"\u53EF\u7A7A\u7EA6\u675F",unique:"\u552F\u4E00\u7EA6\u675F"},qY={ENGINE:"InnoDB",CHARSET:"utf8mb4",COLLATE:"utf8mb4_0900_ai_ci"},WJ=[{name:"id",comment:"\u4E3B\u952EID",needsIndex:!1,mysqlDdl:"BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT",pgDdl:"BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY",sqliteDdl:"INTEGER PRIMARY KEY"},{name:"created_at",comment:"\u521B\u5EFA\u65F6\u95F4",needsIndex:!0,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 0",pgDdl:"BIGINT NOT NULL DEFAULT 0",sqliteDdl:"INTEGER NOT NULL DEFAULT 0"},{name:"updated_at",comment:"\u66F4\u65B0\u65F6\u95F4",needsIndex:!0,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 0",pgDdl:"BIGINT NOT NULL DEFAULT 0",sqliteDdl:"INTEGER NOT NULL DEFAULT 0"},{name:"deleted_at",comment:"\u5220\u9664\u65F6\u95F4",needsIndex:!1,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 0",pgDdl:"BIGINT NOT NULL DEFAULT 0",sqliteDdl:"INTEGER NOT NULL DEFAULT 0"},{name:"state",comment:"\u72B6\u6001\u5B57\u6BB5",needsIndex:!0,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 1",pgDdl:"BIGINT NOT NULL DEFAULT 1",sqliteDdl:"INTEGER NOT NULL DEFAULT 1"}],iZ=WJ.filter(($)=>$.needsIndex).map(($)=>$.name),PY={};for(let $ of WJ)PY[$.name]=$;var BY={DB_VERSION_REQUIREMENTS:B$,CHANGE_TYPE_LABELS:IY,MYSQL_TABLE_CONFIG:qY,SYSTEM_INDEX_FIELDS:iZ,getTypeMapping:xJ,quoteIdentifier:Y0,escapeComment:yJ,applyFieldDefaults:jY,isStringOrArrayType:HJ,getSqlType:tZ,resolveDefaultValue:GJ,generateDefaultSql:fJ,buildIndexSQL:DJ,buildSystemColumnDefs:SY,buildBusinessColumnDefs:wY,generateDDLClause:rZ,isCompatibleTypeChange:LY,compareFieldDefinition:NY,tableExistsRuntime:EY,getTableColumnsRuntime:TY,getTableIndexesRuntime:aZ,createRuntime:($,J,Z="")=>{return{dbDialect:$,db:J,dbName:Z}}};kJ.TestKit=BY;Object.defineProperty(kJ,"TestKit",{value:BY,writable:!1,enumerable:!0,configurable:!1});function xJ($){return{number:$==="sqlite"?"INTEGER":$==="postgresql"?"BIGINT":"BIGINT",string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",text:$==="mysql"?"MEDIUMTEXT":"TEXT",array_string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",array_text:$==="mysql"?"MEDIUMTEXT":"TEXT",array_number_string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",array_number_text:$==="mysql"?"MEDIUMTEXT":"TEXT"}}function Y0($,J){return h$($).quoteIdent(J)}function yJ($){return String($).replace(/"/g,"\\\"")}function jY($){$.detail=$.detail??"",$.min=$.min??0,$.max=$.max??($.type==="number"?Number.MAX_SAFE_INTEGER:100),$.default=$.default??null,$.index=$.index??!1,$.unique=$.unique??!1,$.nullable=$.nullable??!1,$.unsigned=$.unsigned??!0,$.regexp=$.regexp??null}function HJ($){return $==="string"||$==="array_string"||$==="array_number_string"}function tZ($,J,Z,X=!1){let Y=xJ($);if(HJ(J))return`${Y[J]}(${Z})`;let H=Y[J]||"TEXT";if($==="mysql"&&J==="number"&&X)return`${H} UNSIGNED`;return H}function GJ($,J){if($!==null&&$!=="null")return $;switch(J){case"number":return 0;case"string":return"";case"array_string":case"array_number_string":return"[]";case"text":case"array_text":case"array_number_text":return"null";default:return $}}function fJ($,J){if(J==="text"||J==="array_text"||$==="null")return"";if(J==="number"||J==="string"||J==="array_string"||J==="array_number_string")if(typeof $==="number"&&!Number.isNaN($))return` DEFAULT ${$}`;else return` DEFAULT '${String($).replace(/'/g,"''")}'`;return""}function DJ($,J,Z,X,Y){let H=Y0($,J),G=Y0($,Z),U=Y0($,X);if($==="mysql"){let V=[];if(Y==="create")V.push(`ADD INDEX ${G} (${U})`);else V.push(`DROP INDEX ${G}`);return`ALTER TABLE ${H} ALGORITHM=INPLACE, LOCK=NONE, ${V.join(", ")}`}if($==="postgresql"){if(Y==="create")return`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${G} ON ${H}(${U})`;return`DROP INDEX CONCURRENTLY IF EXISTS ${G}`}if(Y==="create")return`CREATE INDEX IF NOT EXISTS ${G} ON ${H}(${U})`;return`DROP INDEX IF EXISTS ${G}`}function CY($,J){let Z=PY[J];if(!Z)return null;let X=Y0($,Z.name);if($==="mysql")return`${X} ${Z.mysqlDdl} COMMENT "${yJ(Z.comment)}"`;if($==="postgresql")return`${X} ${Z.pgDdl}`;return`${X} ${Z.sqliteDdl}`}function SY($){let J=[];for(let Z of WJ){let X=CY($,Z.name);if(X)J.push(X)}return J}function wY($,J){let Z=[];for(let[X,Y]of Object.entries(J)){let H=p(X),G=Y0($,H),U=tZ($,Y.type,Y.max,Y.unsigned),V=GJ(Y.default,Y.type),K=fJ(V,Y.type),F=Y.unique?" UNIQUE":"",A=Y.nullable?" NULL":" NOT NULL";if($==="mysql")Z.push(`${G} ${U}${F}${A}${K} COMMENT "${yJ(Y.name)}"`);else Z.push(`${G} ${U}${F}${A}${K}`)}return Z}function rZ($,J,Z,X=!1){let Y=p(J),H=Y0($,Y),G=tZ($,Z.type,Z.max,Z.unsigned),U=GJ(Z.default,Z.type),V=fJ(U,Z.type),K=Z.unique?" UNIQUE":"",F=Z.nullable?" NULL":" NOT NULL";if($==="mysql")return`${X?"ADD COLUMN":"MODIFY COLUMN"} ${H} ${G}${K}${F}${V} COMMENT "${yJ(Z.name)}"`;if($==="postgresql"){if(X)return`ADD COLUMN IF NOT EXISTS ${H} ${G}${K}${F}${V}`;return`ALTER COLUMN ${H} TYPE ${G}`}if(X)return`ADD COLUMN IF NOT EXISTS ${H} ${G}${K}${F}${V}`;return""}async function MY($,J){try{return await $.unsafe(J),!0}catch(Z){if(J.includes("ALGORITHM=INSTANT")){let X=J.replace(/ALGORITHM=INSTANT/g,"ALGORITHM=INPLACE");try{return await $.unsafe(X),!0}catch{let Y=J;return Y=Y.replace(/\bALGORITHM\s*=\s*(INPLACE|INSTANT)\b\s*,?\s*/g,"").replace(/\bLOCK\s*=\s*(NONE|SHARED|EXCLUSIVE)\b\s*,?\s*/g,""),Y=Y.replace(/,\s*,/g,", ").replace(/,\s*$/g,"").replace(/\s{2,}/g," ").trim(),await $.unsafe(Y),!0}}else throw Z}}function LY($,J){let Z=String($||"").toLowerCase(),X=String(J||"").toLowerCase();if(Z===X)return!1;let Y=Z.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),H=X.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),G=["tinyint","smallint","mediumint","int","integer","bigint"],U=G.indexOf(Y),V=G.indexOf(H);if(U!==-1&&V!==-1&&V>U)return!0;if(Y==="varchar"&&(H==="text"||H==="mediumtext"||H==="longtext"))return!0;if(Y==="character varying"&&H==="text")return!0;return!1}async function EY($,J){if(!$.db)throw Error("SQL \u6267\u884C\u5668\u672A\u521D\u59CB\u5316");try{let Z=void 0;if($.dbDialect==="mysql")Z=$.dbName;else if($.dbDialect==="postgresql")Z="public";let X=h$($.dbDialect).tableExistsQuery(J,Z);return((await $.db.unsafe(X.sql,X.params)).data?.[0]?.count||0)>0}catch(Z){let X=String(Z?.message||Z),Y=Error(`runtime I/O \u5931\u8D25: op=tableExists table=${J} err=${X}`);if(Z?.sqlInfo)Y.sqlInfo=Z.sqlInfo;throw Y}}async function TY($,J){let Z={};try{if($.dbDialect==="mysql"){let X=NJ({dialect:"mysql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.columns.sql,X.columns.params);for(let H of Y.data){let G=H.COLUMN_DEFAULT;Z[H.COLUMN_NAME]={type:H.DATA_TYPE,columnType:H.COLUMN_TYPE,length:H.CHARACTER_MAXIMUM_LENGTH,max:H.CHARACTER_MAXIMUM_LENGTH,nullable:H.IS_NULLABLE==="YES",defaultValue:G,comment:H.COLUMN_COMMENT}}}else if($.dbDialect==="postgresql"){let X=NJ({dialect:"postgresql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.columns.sql,X.columns.params),H=X.comments?(await $.db.unsafe(X.comments.sql,X.comments.params)).data:[],G={};for(let U of H)G[U.column_name]=U.column_comment;for(let U of Y.data)Z[U.column_name]={type:U.data_type,columnType:U.data_type,length:U.character_maximum_length,max:U.character_maximum_length,nullable:String(U.is_nullable).toUpperCase()==="YES",defaultValue:U.column_default,comment:G[U.column_name]??null}}else if($.dbDialect==="sqlite"){let X=NJ({dialect:"sqlite",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.columns.sql,X.columns.params);for(let H of Y.data){let G=String(H.type||"").toUpperCase(),U=null,V=/^(\w+)\s*\((\d+)\)/.exec(G);if(V)G=V[1],U=Number(V[2]);Z[H.name]={type:G.toLowerCase(),columnType:G.toLowerCase(),length:U,max:U,nullable:H.notnull===0,defaultValue:H.dflt_value,comment:null}}}return Z}catch(X){let Y=String(X?.message||X),H=Error(`runtime I/O \u5931\u8D25: op=getTableColumns table=${J} err=${Y}`);if(X?.sqlInfo)H.sqlInfo=X.sqlInfo;throw H}}async function aZ($,J){let Z={};try{if($.dbDialect==="mysql"){let X=lZ({dialect:"mysql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.sql,X.params);for(let H of Y.data){if(!Z[H.INDEX_NAME])Z[H.INDEX_NAME]=[];Z[H.INDEX_NAME].push(H.COLUMN_NAME)}}else if($.dbDialect==="postgresql"){let X=lZ({dialect:"postgresql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.sql,X.params);for(let H of Y.data){let G=/\(([^)]+)\)/.exec(H.indexdef);if(G){let U=G[1].replace(/"/g,"").trim();Z[H.indexname]=[U]}}}else if($.dbDialect==="sqlite"){let X=Y0("sqlite",J),Y=await $.db.unsafe(`PRAGMA index_list(${X})`);for(let H of Y.data){let G=Y0("sqlite",H.name),V=(await $.db.unsafe(`PRAGMA index_info(${G})`)).data.map((K)=>K.name);if(V.length===1)Z[H.name]=V}}return Z}catch(X){let Y=String(X?.message||X),H=Error(`runtime I/O \u5931\u8D25: op=getTableIndexes table=${J} err=${Y}`);if(X?.sqlInfo)H.sqlInfo=X.sqlInfo;throw H}}async function HQ($,J){if(!J)throw Error("SQL \u6267\u884C\u5668\u672A\u521D\u59CB\u5316");if($==="mysql"){let Z=await J.unsafe("SELECT VERSION() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 MySQL \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,Y=parseInt(String(X).split(".")[0],10);if(!Number.isFinite(Y)||Y<B$.MYSQL_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u4EC5\u652F\u6301 MySQL ${B$.MYSQL_MIN_MAJOR}.0+\uFF0C\u5F53\u524D\u7248\u672C: ${X}`);return}if($==="postgresql"){let Z=await J.unsafe("SELECT version() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 PostgreSQL \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,Y=/PostgreSQL\s+(\d+)/i.exec(X),H=Y?parseInt(Y[1],10):NaN;if(!Number.isFinite(H)||H<B$.POSTGRES_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 PostgreSQL >= ${B$.POSTGRES_MIN_MAJOR}\uFF0C\u5F53\u524D: ${X}`);return}if($==="sqlite"){let Z=await J.unsafe("SELECT sqlite_version() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 SQLite \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,[Y,H,G]=String(X).split(".").map((V)=>parseInt(V,10)||0),U=Y*1e4+H*100+G;if(!Number.isFinite(U)||U<B$.SQLITE_MIN_VERSION_NUM)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 SQLite >= ${B$.SQLITE_MIN_VERSION}\uFF0C\u5F53\u524D: ${X}`);return}}function NY($,J,Z){let X=[];if($!=="sqlite"&&HJ(Z.type)){if(J.max!==Z.max)X.push({type:"length",current:J.max,expected:Z.max})}if($!=="sqlite"){let K=J.comment||"";if(K!==Z.name)X.push({type:"comment",current:K,expected:Z.name})}let H=xJ($)[Z.type].toLowerCase(),G=J.type.toLowerCase();if(G!==H)X.push({type:"datatype",current:G,expected:H});let U=Z.nullable;if(J.nullable!==U)X.push({type:"nullable",current:J.nullable,expected:U});let V=GJ(Z.default,Z.type);if(String(J.defaultValue)!==String(V))X.push({type:"default",current:J.defaultValue,expected:V});return X}async function WQ($,J,Z){if($.dbDialect!=="sqlite")throw Error(`rebuildSqliteTable \u4EC5\u652F\u6301 sqlite \u65B9\u8A00\uFF0C\u5F53\u524D: ${String($.dbDialect)}`);let X=Y0("sqlite",J),H=(await $.db.unsafe(`PRAGMA table_info(${X})`)).data.map((A)=>A.name),U=["id","created_at","updated_at","deleted_at","state",...Object.keys(Z).map((A)=>p(A))],V=`${J}__tmp__${Date.now()}`;await vY($,V,Z);let K=U.filter((A)=>H.includes(A));if(K.length>0){let A=K.map((C)=>Y0("sqlite",C)).join(", "),j=Y0("sqlite",V);await $.db.unsafe(`INSERT INTO ${j} (${A}) SELECT ${A} FROM ${X}`)}await $.db.unsafe(`DROP TABLE ${X}`);let F=Y0("sqlite",V);await $.db.unsafe(`ALTER TABLE ${F} RENAME TO ${X}`)}async function GQ($,J,Z,X){if(!X||!X.changed)return;if($.dbDialect==="sqlite")if(X.modifyClauses.length>0||X.defaultClauses.length>0)await WQ($,J,Z);else for(let Y of X.addClauses){let H=`ALTER TABLE ${Y0($.dbDialect,J)} ${Y}`;await $.db.unsafe(H)}else{let Y=[...X.addClauses,...X.modifyClauses];if(Y.length>0){let H=Y0($.dbDialect,J),G=$.dbDialect==="mysql"?`ALTER TABLE ${H} ALGORITHM=INSTANT, LOCK=NONE, ${Y.join(", ")}`:`ALTER TABLE ${H} ${Y.join(", ")}`;if($.dbDialect==="mysql")await MY($.db,G);else await $.db.unsafe(G)}}if(X.defaultClauses.length>0)if($.dbDialect==="sqlite")P.warn(`SQLite \u4E0D\u652F\u6301\u4FEE\u6539\u9ED8\u8BA4\u503C\uFF0C\u8868 ${J} \u7684\u9ED8\u8BA4\u503C\u53D8\u66F4\u5DF2\u8DF3\u8FC7`);else{let Y=Y0($.dbDialect,J),H=$.dbDialect==="mysql"?`ALTER TABLE ${Y} ALGORITHM=INSTANT, LOCK=NONE, ${X.defaultClauses.join(", ")}`:`ALTER TABLE ${Y} ${X.defaultClauses.join(", ")}`;if($.dbDialect==="mysql")await MY($.db,H);else await $.db.unsafe(H)}for(let Y of X.indexActions){let H=DJ($.dbDialect,J,Y.indexName,Y.fieldName,Y.action);try{if(await $.db.unsafe(H),Y.action==="create")P.debug(`[\u7D22\u5F15\u53D8\u5316] \u65B0\u5EFA\u7D22\u5F15 ${J}.${Y.indexName} (${Y.fieldName})`);else P.debug(`[\u7D22\u5F15\u53D8\u5316] \u5220\u9664\u7D22\u5F15 ${J}.${Y.indexName} (${Y.fieldName})`)}catch(G){throw P.error({err:G,table:J,index:Y.indexName,field:Y.fieldName},`${Y.action==="create"?"\u521B\u5EFA":"\u5220\u9664"}\u7D22\u5F15\u5931\u8D25`),G}}if($.dbDialect==="postgresql"&&X.commentActions&&X.commentActions.length>0)for(let Y of X.commentActions)await $.db.unsafe(Y)}async function vY($,J,Z,X=iZ){let H=[...SY($.dbDialect),...wY($.dbDialect,Z)].join(`,
|
|
10
|
+
`),G=Y0($.dbDialect,J),{ENGINE:U,CHARSET:V,COLLATE:K}=qY,F=$.dbDialect==="mysql"?`CREATE TABLE ${G} (
|
|
11
|
+
${H}
|
|
12
|
+
) ENGINE=${U} DEFAULT CHARSET=${V} COLLATE=${K}`:`CREATE TABLE ${G} (
|
|
13
|
+
${H}
|
|
14
|
+
)`;if(await $.db.unsafe(F),$.dbDialect==="postgresql"){for(let C of WJ){let w=String(C.comment).replace(/'/g,"''"),E=Y0($.dbDialect,C.name),T=`COMMENT ON COLUMN ${G}.${E} IS '${w}'`;await $.db.unsafe(T)}for(let[C,w]of Object.entries(Z)){let E=p(C),T=Y0($.dbDialect,E),v=w.name&&w.name!=="null"?String(w.name):"",L=v.replace(/'/g,"''"),D=v?`'${L}'`:"NULL",g=`COMMENT ON COLUMN ${G}.${T} IS ${D}`;await $.db.unsafe(g)}}let A=[],j={};if($.dbDialect==="mysql")j=await aZ($,J);for(let C of X){let w=`idx_${C}`;if($.dbDialect==="mysql"&&j[w])continue;let E=DJ($.dbDialect,J,w,C,"create");A.push($.db.unsafe(E))}for(let[C,w]of Object.entries(Z)){let E=p(C);if(w.index===!0&&w.unique!==!0){let T=`idx_${E}`;if($.dbDialect==="mysql"&&j[T])continue;let v=DJ($.dbDialect,J,T,E,"create");A.push($.db.unsafe(v))}}if(A.length>0)await Promise.all(A)}async function QQ($,J,Z){let X=await TY($,J),Y=await aZ($,J),H=!1,G=[],U=[],V=[],K=[];for(let[C,w]of Object.entries(Z)){let E=p(C);if(X[E]){let T=NY($.dbDialect,X[E],w);if(T.length>0){for(let N of T){let f=IY[N.type]||"\u672A\u77E5";P.debug(` ~ \u4FEE\u6539 ${E} ${f}: ${N.current} -> ${N.expected}`)}if(HJ(w.type)&&X[E].max&&w.max!==null){if(X[E].max>w.max)P.warn(`[\u8DF3\u8FC7\u5371\u9669\u53D8\u66F4] ${J}.${E} \u957F\u5EA6\u6536\u7F29 ${X[E].max} -> ${w.max} \u5DF2\u88AB\u8DF3\u8FC7\uFF08\u9700\u624B\u52A8\u5904\u7406\uFF09`)}let v=T.some((N)=>N.type==="datatype"),L=T.some((N)=>N.type==="length"),D=T.every((N)=>N.type==="default"),g=T.some((N)=>N.type==="default");if(v){let N=T.find((u0)=>u0.type==="datatype"),f=String(N?.current||"").toLowerCase(),r=xJ($.dbDialect)[w.type]?.toLowerCase()||"";if(!LY(f,r)){let u0=[`\u7981\u6B62\u5B57\u6BB5\u7C7B\u578B\u53D8\u66F4: ${J}.${E}`,`\u5F53\u524D\u7C7B\u578B: ${N?.current}`,`\u76EE\u6807\u7C7B\u578B: ${N?.expected}`,"\u8BF4\u660E: \u4EC5\u5141\u8BB8\u5BBD\u5316\u578B\u53D8\u66F4\uFF08\u5982 INT->BIGINT, VARCHAR->TEXT\uFF09\uFF0C\u5176\u4ED6\u7C7B\u578B\u53D8\u66F4\u9700\u8981\u624B\u52A8\u5904\u7406"].join(`
|
|
15
|
+
`);throw Error(u0)}P.debug(`[\u517C\u5BB9\u7C7B\u578B\u53D8\u66F4] ${J}.${E} ${f} -> ${r}`)}if(g){let N=GJ(w.default,w.type),f=null;if(N!=="null")f=fJ(N,w.type).trim().replace(/^DEFAULT\s+/,"");if(f!==null&&f!==""){if($.dbDialect==="postgresql"){let l=Y0($.dbDialect,E);V.push(`ALTER COLUMN ${l} SET DEFAULT ${f}`)}else if($.dbDialect==="mysql"&&D){if(w.type!=="text"){let l=Y0($.dbDialect,E);V.push(`ALTER COLUMN ${l} SET DEFAULT ${f}`)}}}}if(!D){let N=!1;if(L&&HJ(w.type)&&X[E].max&&w.max!==null){if(X[E].max>w.max)N=!0}if(!N)U.push(rZ($.dbDialect,C,w,!1))}H=!0}}else G.push(rZ($.dbDialect,C,w,!0)),H=!0}let F=WJ.filter((C)=>C.name!=="id").map((C)=>C.name);for(let C of F)if(!X[C]){let w=CY($.dbDialect,C);if(w)P.debug(` + \u65B0\u589E\u7CFB\u7EDF\u5B57\u6BB5 ${C}`),G.push(`ADD COLUMN ${w}`),H=!0}for(let C of iZ){let w=`idx_${C}`;if((X[C]||F.includes(C))&&!Y[w])K.push({action:"create",indexName:w,fieldName:C}),H=!0}for(let[C,w]of Object.entries(Z)){let E=p(C),T=`idx_${E}`;if(w.index&&!w.unique&&!Y[T])K.push({action:"create",indexName:T,fieldName:E}),H=!0;else if(!w.index&&Y[T]&&Y[T].length===1)K.push({action:"drop",indexName:T,fieldName:E}),H=!0}let A=[];if($.dbDialect==="postgresql"){let C=Y0($.dbDialect,J);for(let[w,E]of Object.entries(Z)){let T=p(w),v=Y0($.dbDialect,T);if(X[T]){let L=X[T].comment||"",D=E.name&&E.name!=="null"?String(E.name):"";if(D!==L){let g=D.replace(/'/g,"''");A.push(`COMMENT ON COLUMN ${C}.${v} IS ${D?`'${g}'`:"NULL"}`),H=!0}}}}H=G.length>0||U.length>0||V.length>0||K.length>0||A.length>0;let j={changed:H,addClauses:G,modifyClauses:U,defaultClauses:V,indexActions:K,commentActions:A};if(j.changed)await GQ($,J,Z,j);return j}var DY=($,J=Bun.nanoseconds())=>{let Z=(J-$)/1e6;if(Z<1000)return`${Z.toFixed(2)} \u6BEB\u79D2`;else return`${(Z/1000).toFixed(2)} \u79D2`};function kY(){let $=process.env.BUN_WORKER_ID,J=process.env.PM2_INSTANCE_ID;if($!==void 0)return{role:$===""?"primary":"worker",instanceId:$||"0",env:"bun-cluster"};if(J!==void 0)return{role:J==="0"?"primary":"worker",instanceId:J,env:"pm2-cluster"};return{role:"primary",instanceId:null,env:"standalone"}}A$();A$();import{existsSync as zQ,readdirSync as UQ}from"fs";nZ();var xY=()=>{let $=new Map,J=(Z,X,Y)=>{if(!zQ(Z))return;let H=UQ(Z,{withFileTypes:!0});for(let G of H){if(G.name.startsWith("_"))continue;if(!wJ(Z,G))continue;let U=JJ(Z,G.name),V={source:X,sourceName:Y,name:G.name,camelName:O$(G.name),rootDir:U,fullPath:U};$.set(G.name,V)}};return J(n(d0,"node_modules","@befly-addon"),"addon","\u7EC4\u4EF6"),J(UY,"app","\u9879\u76EE"),Array.from($.values())};RJ();var yY={name:"auth",enable:!0,deps:["cors"],handler:async($,J)=>{let Z=J.req.headers.get("authorization");if(Z&&Z.startsWith("Bearer ")){let X=Z.substring(7);try{let Y=await $.jwt.verify(X);J.user=Y,A1(Y.id,Y.roleCode,Y.nickname,Y.roleType)}catch{J.user={}}}else J.user={}}};var fY={name:"cors",enable:!0,deps:[],handler:async($,J)=>{let Z=J.req,Y=Object.assign({},{origin:"*",methods:"GET, POST, PUT, DELETE, OPTIONS",allowedHeaders:"Content-Type, Authorization, authorization, token",exposedHeaders:"Content-Range, X-Content-Range, Authorization, authorization, token",maxAge:86400,credentials:"true"},$.config&&$.config.cors?$.config.cors:{}),H=TJ(Z,Y);if(J.corsHeaders=H,Z.method==="OPTIONS"){J.response=new Response(null,{status:204,headers:H});return}}};var VQ=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",KQ="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+VQ+"]*",OQ=new RegExp("^"+KQ+"$");function hJ($,J){let Z=[],X=J.exec($);while(X){let Y=[];Y.startIndex=J.lastIndex-X[0].length;let H=X.length;for(let G=0;G<H;G++)Y.push(X[G]);Z.push(Y),X=J.exec($)}return Z}var g$=function($){let J=OQ.exec($);return!(J===null||typeof J>"u")};function hY($){return typeof $<"u"}var _Q={allowBooleanAttributes:!1,unpairedTags:[]};function uY($,J){J=Object.assign({},_Q,J);let Z=[],X=!1,Y=!1;if($[0]==="\uFEFF")$=$.substr(1);for(let H=0;H<$.length;H++)if($[H]==="<"&&$[H+1]==="?"){if(H+=2,H=bY($,H),H.err)return H}else if($[H]==="<"){let G=H;if(H++,$[H]==="!"){H=cY($,H);continue}else{let U=!1;if($[H]==="/")U=!0,H++;let V="";for(;H<$.length&&$[H]!==">"&&$[H]!==" "&&$[H]!=="\t"&&$[H]!==`
|
|
16
|
+
`&&$[H]!=="\r";H++)V+=$[H];if(V=V.trim(),V[V.length-1]==="/")V=V.substring(0,V.length-1),H--;if(!BQ(V)){let A;if(V.trim().length===0)A="Invalid space after '<'.";else A="Tag '"+V+"' is an invalid name.";return H0("InvalidTag",A,n0($,H))}let K=RQ($,H);if(K===!1)return H0("InvalidAttr","Attributes for '"+V+"' have open quote.",n0($,H));let F=K.value;if(H=K.index,F[F.length-1]==="/"){let A=H-F.length;F=F.substring(0,F.length-1);let j=pY(F,J);if(j===!0)X=!0;else return H0(j.err.code,j.err.msg,n0($,A+j.err.line))}else if(U)if(!K.tagClosed)return H0("InvalidTag","Closing tag '"+V+"' doesn't have proper closing.",n0($,H));else if(F.trim().length>0)return H0("InvalidTag","Closing tag '"+V+"' can't have attributes or invalid starting.",n0($,G));else if(Z.length===0)return H0("InvalidTag","Closing tag '"+V+"' has not been opened.",n0($,G));else{let A=Z.pop();if(V!==A.tagName){let j=n0($,A.tagStartPos);return H0("InvalidTag","Expected closing tag '"+A.tagName+"' (opened in line "+j.line+", col "+j.col+") instead of closing tag '"+V+"'.",n0($,G))}if(Z.length==0)Y=!0}else{let A=pY(F,J);if(A!==!0)return H0(A.err.code,A.err.msg,n0($,H-F.length+A.err.line));if(Y===!0)return H0("InvalidXml","Multiple possible root nodes found.",n0($,H));else if(J.unpairedTags.indexOf(V)!==-1);else Z.push({tagName:V,tagStartPos:G});X=!0}for(H++;H<$.length;H++)if($[H]==="<")if($[H+1]==="!"){H++,H=cY($,H);continue}else if($[H+1]==="?"){if(H=bY($,++H),H.err)return H}else break;else if($[H]==="&"){let A=qQ($,H);if(A==-1)return H0("InvalidChar","char '&' is not expected.",n0($,H));H=A}else if(Y===!0&&!gY($[H]))return H0("InvalidXml","Extra text at the end",n0($,H));if($[H]==="<")H--}}else{if(gY($[H]))continue;return H0("InvalidChar","char '"+$[H]+"' is not expected.",n0($,H))}if(!X)return H0("InvalidXml","Start tag expected.",1);else if(Z.length==1)return H0("InvalidTag","Unclosed tag '"+Z[0].tagName+"'.",n0($,Z[0].tagStartPos));else if(Z.length>0)return H0("InvalidXml","Invalid '"+JSON.stringify(Z.map((H)=>H.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function gY($){return $===" "||$==="\t"||$===`
|
|
17
|
+
`||$==="\r"}function bY($,J){let Z=J;for(;J<$.length;J++)if($[J]=="?"||$[J]==" "){let X=$.substr(Z,J-Z);if(J>5&&X==="xml")return H0("InvalidXml","XML declaration allowed only at the start of the document.",n0($,J));else if($[J]=="?"&&$[J+1]==">"){J++;break}else continue}return J}function cY($,J){if($.length>J+5&&$[J+1]==="-"&&$[J+2]==="-"){for(J+=3;J<$.length;J++)if($[J]==="-"&&$[J+1]==="-"&&$[J+2]===">"){J+=2;break}}else if($.length>J+8&&$[J+1]==="D"&&$[J+2]==="O"&&$[J+3]==="C"&&$[J+4]==="T"&&$[J+5]==="Y"&&$[J+6]==="P"&&$[J+7]==="E"){let Z=1;for(J+=8;J<$.length;J++)if($[J]==="<")Z++;else if($[J]===">"){if(Z--,Z===0)break}}else if($.length>J+9&&$[J+1]==="["&&$[J+2]==="C"&&$[J+3]==="D"&&$[J+4]==="A"&&$[J+5]==="T"&&$[J+6]==="A"&&$[J+7]==="["){for(J+=8;J<$.length;J++)if($[J]==="]"&&$[J+1]==="]"&&$[J+2]===">"){J+=2;break}}return J}var FQ='"',AQ="'";function RQ($,J){let Z="",X="",Y=!1;for(;J<$.length;J++){if($[J]===FQ||$[J]===AQ)if(X==="")X=$[J];else if(X!==$[J]);else X="";else if($[J]===">"){if(X===""){Y=!0;break}}Z+=$[J]}if(X!=="")return!1;return{value:Z,index:J,tagClosed:Y}}var MQ=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function pY($,J){let Z=hJ($,MQ),X={};for(let Y=0;Y<Z.length;Y++){if(Z[Y][1].length===0)return H0("InvalidAttr","Attribute '"+Z[Y][2]+"' has no space in starting.",QJ(Z[Y]));else if(Z[Y][3]!==void 0&&Z[Y][4]===void 0)return H0("InvalidAttr","Attribute '"+Z[Y][2]+"' is without value.",QJ(Z[Y]));else if(Z[Y][3]===void 0&&!J.allowBooleanAttributes)return H0("InvalidAttr","boolean attribute '"+Z[Y][2]+"' is not allowed.",QJ(Z[Y]));let H=Z[Y][2];if(!PQ(H))return H0("InvalidAttr","Attribute '"+H+"' is an invalid name.",QJ(Z[Y]));if(!X.hasOwnProperty(H))X[H]=1;else return H0("InvalidAttr","Attribute '"+H+"' is repeated.",QJ(Z[Y]))}return!0}function IQ($,J){let Z=/\d/;if($[J]==="x")J++,Z=/[\da-fA-F]/;for(;J<$.length;J++){if($[J]===";")return J;if(!$[J].match(Z))break}return-1}function qQ($,J){if(J++,$[J]===";")return-1;if($[J]==="#")return J++,IQ($,J);let Z=0;for(;J<$.length;J++,Z++){if($[J].match(/\w/)&&Z<20)continue;if($[J]===";")break;return-1}return J}function H0($,J,Z){return{err:{code:$,msg:J,line:Z.line||Z,col:Z.col}}}function PQ($){return g$($)}function BQ($){return g$($)}function n0($,J){let Z=$.substring(0,J).split(/\r?\n/);return{line:Z.length,col:Z[Z.length-1].length+1}}function QJ($){return $.startIndex+$[1].length}var jQ={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function($,J){return J},attributeValueProcessor:function($,J){return J},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function($,J,Z){return $},captureMetaData:!1},mY=function($){return Object.assign({},jQ,$)};var gJ;if(typeof Symbol!=="function")gJ="@@xmlMetadata";else gJ=Symbol("XML Node Metadata");class r0{constructor($){this.tagname=$,this.child=[],this[":@"]={}}add($,J){if($==="__proto__")$="#__proto__";this.child.push({[$]:J})}addChild($,J){if($.tagname==="__proto__")$.tagname="#__proto__";if($[":@"]&&Object.keys($[":@"]).length>0)this.child.push({[$.tagname]:$.child,[":@"]:$[":@"]});else this.child.push({[$.tagname]:$.child});if(J!==void 0)this.child[this.child.length-1][gJ]={startIndex:J}}static getMetaDataSymbol(){return gJ}}class bJ{constructor($){this.suppressValidationErr=!$}readDocType($,J){let Z={};if($[J+3]==="O"&&$[J+4]==="C"&&$[J+5]==="T"&&$[J+6]==="Y"&&$[J+7]==="P"&&$[J+8]==="E"){J=J+9;let X=1,Y=!1,H=!1,G="";for(;J<$.length;J++)if($[J]==="<"&&!H){if(Y&&j$($,"!ENTITY",J)){J+=7;let U,V;if([U,V,J]=this.readEntityExp($,J+1,this.suppressValidationErr),V.indexOf("&")===-1)Z[U]={regx:RegExp(`&${U};`,"g"),val:V}}else if(Y&&j$($,"!ELEMENT",J)){J+=8;let{index:U}=this.readElementExp($,J+1);J=U}else if(Y&&j$($,"!ATTLIST",J))J+=8;else if(Y&&j$($,"!NOTATION",J)){J+=9;let{index:U}=this.readNotationExp($,J+1,this.suppressValidationErr);J=U}else if(j$($,"!--",J))H=!0;else throw Error("Invalid DOCTYPE");X++,G=""}else if($[J]===">"){if(H){if($[J-1]==="-"&&$[J-2]==="-")H=!1,X--}else X--;if(X===0)break}else if($[J]==="[")Y=!0;else G+=$[J];if(X!==0)throw Error("Unclosed DOCTYPE")}else throw Error("Invalid Tag instead of DOCTYPE");return{entities:Z,i:J}}readEntityExp($,J){J=s0($,J);let Z="";while(J<$.length&&!/\s/.test($[J])&&$[J]!=='"'&&$[J]!=="'")Z+=$[J],J++;if(zJ(Z),J=s0($,J),!this.suppressValidationErr){if($.substring(J,J+6).toUpperCase()==="SYSTEM")throw Error("External entities are not supported");else if($[J]==="%")throw Error("Parameter entities are not supported")}let X="";return[J,X]=this.readIdentifierVal($,J,"entity"),J--,[Z,X,J]}readNotationExp($,J){J=s0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;!this.suppressValidationErr&&zJ(Z),J=s0($,J);let X=$.substring(J,J+6).toUpperCase();if(!this.suppressValidationErr&&X!=="SYSTEM"&&X!=="PUBLIC")throw Error(`Expected SYSTEM or PUBLIC, found "${X}"`);J+=X.length,J=s0($,J);let Y=null,H=null;if(X==="PUBLIC"){if([J,Y]=this.readIdentifierVal($,J,"publicIdentifier"),J=s0($,J),$[J]==='"'||$[J]==="'")[J,H]=this.readIdentifierVal($,J,"systemIdentifier")}else if(X==="SYSTEM"){if([J,H]=this.readIdentifierVal($,J,"systemIdentifier"),!this.suppressValidationErr&&!H)throw Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:Z,publicIdentifier:Y,systemIdentifier:H,index:--J}}readIdentifierVal($,J,Z){let X="",Y=$[J];if(Y!=='"'&&Y!=="'")throw Error(`Expected quoted string, found "${Y}"`);J++;while(J<$.length&&$[J]!==Y)X+=$[J],J++;if($[J]!==Y)throw Error(`Unterminated ${Z} value`);return J++,[J,X]}readElementExp($,J){J=s0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;if(!this.suppressValidationErr&&!g$(Z))throw Error(`Invalid element name: "${Z}"`);J=s0($,J);let X="";if($[J]==="E"&&j$($,"MPTY",J))J+=4;else if($[J]==="A"&&j$($,"NY",J))J+=2;else if($[J]==="("){J++;while(J<$.length&&$[J]!==")")X+=$[J],J++;if($[J]!==")")throw Error("Unterminated content model")}else if(!this.suppressValidationErr)throw Error(`Invalid Element Expression, found "${$[J]}"`);return{elementName:Z,contentModel:X.trim(),index:J}}readAttlistExp($,J){J=s0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;zJ(Z),J=s0($,J);let X="";while(J<$.length&&!/\s/.test($[J]))X+=$[J],J++;if(!zJ(X))throw Error(`Invalid attribute name: "${X}"`);J=s0($,J);let Y="";if($.substring(J,J+8).toUpperCase()==="NOTATION"){if(Y="NOTATION",J+=8,J=s0($,J),$[J]!=="(")throw Error(`Expected '(', found "${$[J]}"`);J++;let G=[];while(J<$.length&&$[J]!==")"){let U="";while(J<$.length&&$[J]!=="|"&&$[J]!==")")U+=$[J],J++;if(U=U.trim(),!zJ(U))throw Error(`Invalid notation name: "${U}"`);if(G.push(U),$[J]==="|")J++,J=s0($,J)}if($[J]!==")")throw Error("Unterminated list of notations");J++,Y+=" ("+G.join("|")+")"}else{while(J<$.length&&!/\s/.test($[J]))Y+=$[J],J++;let G=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!G.includes(Y.toUpperCase()))throw Error(`Invalid attribute type: "${Y}"`)}J=s0($,J);let H="";if($.substring(J,J+8).toUpperCase()==="#REQUIRED")H="#REQUIRED",J+=8;else if($.substring(J,J+7).toUpperCase()==="#IMPLIED")H="#IMPLIED",J+=7;else[J,H]=this.readIdentifierVal($,J,"ATTLIST");return{elementName:Z,attributeName:X,attributeType:Y,defaultValue:H,index:J}}}var s0=($,J)=>{while(J<$.length&&/\s/.test($[J]))J++;return J};function j$($,J,Z){for(let X=0;X<J.length;X++)if(J[X]!==$[Z+X+1])return!1;return!0}function zJ($){if(g$($))return $;else throw Error(`Invalid entity name ${$}`)}var CQ=/^[-+]?0x[a-fA-F0-9]+$/,SQ=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,wQ={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function eZ($,J={}){if(J=Object.assign({},wQ,J),!$||typeof $!=="string")return $;let Z=$.trim();if(J.skipLike!==void 0&&J.skipLike.test(Z))return $;else if($==="0")return 0;else if(J.hex&&CQ.test(Z))return NQ(Z,16);else if(Z.includes("e")||Z.includes("E"))return EQ($,Z,J);else{let X=SQ.exec(Z);if(X){let Y=X[1]||"",H=X[2],G=TQ(X[3]),U=Y?$[H.length+1]===".":$[H.length]===".";if(!J.leadingZeros&&(H.length>1||H.length===1&&!U))return $;else{let V=Number(Z),K=String(V);if(V===0)return V;if(K.search(/[eE]/)!==-1)if(J.eNotation)return V;else return $;else if(Z.indexOf(".")!==-1)if(K==="0")return V;else if(K===G)return V;else if(K===`${Y}${G}`)return V;else return $;let F=H?G:Z;if(H)return F===K||Y+F===K?V:$;else return F===K||F===Y+K?V:$}}else return $}}var LQ=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function EQ($,J,Z){if(!Z.eNotation)return $;let X=J.match(LQ);if(X){let Y=X[1]||"",H=X[3].indexOf("e")===-1?"E":"e",G=X[2],U=Y?$[G.length+1]===H:$[G.length]===H;if(G.length>1&&U)return $;else if(G.length===1&&(X[3].startsWith(`.${H}`)||X[3][0]===H))return Number(J);else if(Z.leadingZeros&&!U)return J=(X[1]||"")+X[3],Number(J);else return $}else return $}function TQ($){if($&&$.indexOf(".")!==-1){if($=$.replace(/0+$/,""),$===".")$="0";else if($[0]===".")$="0"+$;else if($[$.length-1]===".")$=$.substring(0,$.length-1);return $}return $}function NQ($,J){if(parseInt)return parseInt($,J);else if(Number.parseInt)return Number.parseInt($,J);else if(window&&window.parseInt)return window.parseInt($,J);else throw Error("parseInt, Number.parseInt, window.parseInt are not supported")}function $X($){if(typeof $==="function")return $;if(Array.isArray($))return(J)=>{for(let Z of $){if(typeof Z==="string"&&J===Z)return!0;if(Z instanceof RegExp&&Z.test(J))return!0}};return()=>!1}class cJ{constructor($){if(this.options=$,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(J,Z)=>String.fromCodePoint(Number.parseInt(Z,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(J,Z)=>String.fromCodePoint(Number.parseInt(Z,16))}},this.addExternalEntities=vQ,this.parseXml=fQ,this.parseTextData=DQ,this.resolveNameSpace=kQ,this.buildAttributesMap=yQ,this.isItStopNode=cQ,this.replaceEntitiesValue=gQ,this.readStopNodeData=uQ,this.saveTextToParentTag=bQ,this.addChild=hQ,this.ignoreAttributesFn=$X(this.options.ignoreAttributes),this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let J=0;J<this.options.stopNodes.length;J++){let Z=this.options.stopNodes[J];if(typeof Z!=="string")continue;if(Z.startsWith("*."))this.stopNodesWildcard.add(Z.substring(2));else this.stopNodesExact.add(Z)}}}}function vQ($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let X=J[Z];this.lastEntities[X]={regex:new RegExp("&"+X+";","g"),val:$[X]}}}function DQ($,J,Z,X,Y,H,G){if($!==void 0){if(this.options.trimValues&&!X)$=$.trim();if($.length>0){if(!G)$=this.replaceEntitiesValue($);let U=this.options.tagValueProcessor(J,$,Z,Y,H);if(U===null||U===void 0)return $;else if(typeof U!==typeof $||U!==$)return U;else if(this.options.trimValues)return ZX($,this.options.parseTagValue,this.options.numberParseOptions);else if($.trim()===$)return ZX($,this.options.parseTagValue,this.options.numberParseOptions);else return $}}}function kQ($){if(this.options.removeNSPrefix){let J=$.split(":"),Z=$.charAt(0)==="/"?"/":"";if(J[0]==="xmlns")return"";if(J.length===2)$=Z+J[1]}return $}var xQ=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function yQ($,J){if(this.options.ignoreAttributes!==!0&&typeof $==="string"){let Z=hJ($,xQ),X=Z.length,Y={};for(let H=0;H<X;H++){let G=this.resolveNameSpace(Z[H][1]);if(this.ignoreAttributesFn(G,J))continue;let U=Z[H][4],V=this.options.attributeNamePrefix+G;if(G.length){if(this.options.transformAttributeName)V=this.options.transformAttributeName(V);if(V==="__proto__")V="#__proto__";if(U!==void 0){if(this.options.trimValues)U=U.trim();U=this.replaceEntitiesValue(U);let K=this.options.attributeValueProcessor(G,U,J);if(K===null||K===void 0)Y[V]=U;else if(typeof K!==typeof U||K!==U)Y[V]=K;else Y[V]=ZX(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else if(this.options.allowBooleanAttributes)Y[V]=!0}}if(!Object.keys(Y).length)return;if(this.options.attributesGroupName){let H={};return H[this.options.attributesGroupName]=Y,H}return Y}}var fQ=function($){$=$.replace(/\r\n?/g,`
|
|
18
|
+
`);let J=new r0("!xml"),Z=J,X="",Y="",H=new bJ(this.options.processEntities);for(let G=0;G<$.length;G++)if($[G]==="<")if($[G+1]==="/"){let V=C$($,">",G,"Closing Tag is not closed."),K=$.substring(G+2,V).trim();if(this.options.removeNSPrefix){let j=K.indexOf(":");if(j!==-1)K=K.substr(j+1)}if(this.options.transformTagName)K=this.options.transformTagName(K);if(Z)X=this.saveTextToParentTag(X,Z,Y);let F=Y.substring(Y.lastIndexOf(".")+1);if(K&&this.options.unpairedTags.indexOf(K)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${K}>`);let A=0;if(F&&this.options.unpairedTags.indexOf(F)!==-1)A=Y.lastIndexOf(".",Y.lastIndexOf(".")-1),this.tagsNodeStack.pop();else A=Y.lastIndexOf(".");Y=Y.substring(0,A),Z=this.tagsNodeStack.pop(),X="",G=V}else if($[G+1]==="?"){let V=JX($,G,!1,"?>");if(!V)throw Error("Pi Tag is not closed.");if(X=this.saveTextToParentTag(X,Z,Y),this.options.ignoreDeclaration&&V.tagName==="?xml"||this.options.ignorePiTags);else{let K=new r0(V.tagName);if(K.add(this.options.textNodeName,""),V.tagName!==V.tagExp&&V.attrExpPresent)K[":@"]=this.buildAttributesMap(V.tagExp,Y);this.addChild(Z,K,Y,G)}G=V.closeIndex+1}else if($.substr(G+1,3)==="!--"){let V=C$($,"-->",G+4,"Comment is not closed.");if(this.options.commentPropName){let K=$.substring(G+4,V-2);X=this.saveTextToParentTag(X,Z,Y),Z.add(this.options.commentPropName,[{[this.options.textNodeName]:K}])}G=V}else if($.substr(G+1,2)==="!D"){let V=H.readDocType($,G);this.docTypeEntities=V.entities,G=V.i}else if($.substr(G+1,2)==="!["){let V=C$($,"]]>",G,"CDATA is not closed.")-2,K=$.substring(G+9,V);X=this.saveTextToParentTag(X,Z,Y);let F=this.parseTextData(K,Z.tagname,Y,!0,!1,!0,!0);if(F==null)F="";if(this.options.cdataPropName)Z.add(this.options.cdataPropName,[{[this.options.textNodeName]:K}]);else Z.add(this.options.textNodeName,F);G=V+2}else{let V=JX($,G,this.options.removeNSPrefix),K=V.tagName,F=V.rawTagName,A=V.tagExp,j=V.attrExpPresent,C=V.closeIndex;if(this.options.transformTagName){let T=this.options.transformTagName(K);if(A===K)A=T;K=T}if(Z&&X){if(Z.tagname!=="!xml")X=this.saveTextToParentTag(X,Z,Y,!1)}let w=Z;if(w&&this.options.unpairedTags.indexOf(w.tagname)!==-1)Z=this.tagsNodeStack.pop(),Y=Y.substring(0,Y.lastIndexOf("."));if(K!==J.tagname)Y+=Y?"."+K:K;let E=G;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,Y,K)){let T="";if(A.length>0&&A.lastIndexOf("/")===A.length-1){if(K[K.length-1]==="/")K=K.substr(0,K.length-1),Y=Y.substr(0,Y.length-1),A=K;else A=A.substr(0,A.length-1);G=V.closeIndex}else if(this.options.unpairedTags.indexOf(K)!==-1)G=V.closeIndex;else{let L=this.readStopNodeData($,F,C+1);if(!L)throw Error(`Unexpected end of ${F}`);G=L.i,T=L.tagContent}let v=new r0(K);if(K!==A&&j)v[":@"]=this.buildAttributesMap(A,Y);if(T)T=this.parseTextData(T,K,Y,!0,j,!0,!0);Y=Y.substr(0,Y.lastIndexOf(".")),v.add(this.options.textNodeName,T),this.addChild(Z,v,Y,E)}else{if(A.length>0&&A.lastIndexOf("/")===A.length-1){if(K[K.length-1]==="/")K=K.substr(0,K.length-1),Y=Y.substr(0,Y.length-1),A=K;else A=A.substr(0,A.length-1);if(this.options.transformTagName){let v=this.options.transformTagName(K);if(A===K)A=v;K=v}let T=new r0(K);if(K!==A&&j)T[":@"]=this.buildAttributesMap(A,Y);this.addChild(Z,T,Y,E),Y=Y.substr(0,Y.lastIndexOf("."))}else{let T=new r0(K);if(this.tagsNodeStack.push(Z),K!==A&&j)T[":@"]=this.buildAttributesMap(A,Y);this.addChild(Z,T,Y,E),Z=T}X="",G=C}}else X+=$[G];return J.child};function hQ($,J,Z,X){if(!this.options.captureMetaData)X=void 0;let Y=this.options.updateTag(J.tagname,Z,J[":@"]);if(Y===!1);else if(typeof Y==="string")J.tagname=Y,$.addChild(J,X);else $.addChild(J,X)}var gQ=function($){if(this.options.processEntities){for(let J in this.docTypeEntities){let Z=this.docTypeEntities[J];$=$.replace(Z.regx,Z.val)}for(let J in this.lastEntities){let Z=this.lastEntities[J];$=$.replace(Z.regex,Z.val)}if(this.options.htmlEntities)for(let J in this.htmlEntities){let Z=this.htmlEntities[J];$=$.replace(Z.regex,Z.val)}$=$.replace(this.ampEntity.regex,this.ampEntity.val)}return $};function bQ($,J,Z,X){if($){if(X===void 0)X=J.child.length===0;if($=this.parseTextData($,J.tagname,Z,!1,J[":@"]?Object.keys(J[":@"]).length!==0:!1,X),$!==void 0&&$!=="")J.add(this.options.textNodeName,$);$=""}return $}function cQ($,J,Z,X){if(J&&J.has(X))return!0;if($&&$.has(Z))return!0;return!1}function pQ($,J,Z=">"){let X,Y="";for(let H=J;H<$.length;H++){let G=$[H];if(X){if(G===X)X=""}else if(G==='"'||G==="'")X=G;else if(G===Z[0])if(Z[1]){if($[H+1]===Z[1])return{data:Y,index:H}}else return{data:Y,index:H};else if(G==="\t")G=" ";Y+=G}}function C$($,J,Z,X){let Y=$.indexOf(J,Z);if(Y===-1)throw Error(X);else return Y+J.length-1}function JX($,J,Z,X=">"){let Y=pQ($,J+1,X);if(!Y)return;let{data:H,index:G}=Y,U=H.search(/\s/),V=H,K=!0;if(U!==-1)V=H.substring(0,U),H=H.substring(U+1).trimStart();let F=V;if(Z){let A=V.indexOf(":");if(A!==-1)V=V.substr(A+1),K=V!==Y.data.substr(A+1)}return{tagName:V,tagExp:H,closeIndex:G,attrExpPresent:K,rawTagName:F}}function uQ($,J,Z){let X=Z,Y=1;for(;Z<$.length;Z++)if($[Z]==="<")if($[Z+1]==="/"){let H=C$($,">",Z,`${J} is not closed`);if($.substring(Z+2,H).trim()===J){if(Y--,Y===0)return{tagContent:$.substring(X,Z),i:H}}Z=H}else if($[Z+1]==="?")Z=C$($,"?>",Z+1,"StopNode is not closed.");else if($.substr(Z+1,3)==="!--")Z=C$($,"-->",Z+3,"StopNode is not closed.");else if($.substr(Z+1,2)==="![")Z=C$($,"]]>",Z,"StopNode is not closed.")-2;else{let H=JX($,Z,">");if(H){if((H&&H.tagName)===J&&H.tagExp[H.tagExp.length-1]!=="/")Y++;Z=H.closeIndex}}}function ZX($,J,Z){if(J&&typeof $==="string"){let X=$.trim();if(X==="true")return!0;else if(X==="false")return!1;else return eZ($,Z)}else if(hY($))return $;else return""}var XX=r0.getMetaDataSymbol();function YX($,J){return dY($,J)}function dY($,J,Z){let X,Y={};for(let H=0;H<$.length;H++){let G=$[H],U=mQ(G),V="";if(Z===void 0)V=U;else V=Z+"."+U;if(U===J.textNodeName)if(X===void 0)X=G[U];else X+=""+G[U];else if(U===void 0)continue;else if(G[U]){let K=dY(G[U],J,V),F=nQ(K,J);if(G[XX]!==void 0)K[XX]=G[XX];if(G[":@"])dQ(K,G[":@"],V,J);else if(Object.keys(K).length===1&&K[J.textNodeName]!==void 0&&!J.alwaysCreateTextNode)K=K[J.textNodeName];else if(Object.keys(K).length===0)if(J.alwaysCreateTextNode)K[J.textNodeName]="";else K="";if(Y[U]!==void 0&&Y.hasOwnProperty(U)){if(!Array.isArray(Y[U]))Y[U]=[Y[U]];Y[U].push(K)}else if(J.isArray(U,V,F))Y[U]=[K];else Y[U]=K}}if(typeof X==="string"){if(X.length>0)Y[J.textNodeName]=X}else if(X!==void 0)Y[J.textNodeName]=X;return Y}function mQ($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X!==":@")return X}}function dQ($,J,Z,X){if(J){let Y=Object.keys(J),H=Y.length;for(let G=0;G<H;G++){let U=Y[G];if(X.isArray(U,Z+"."+U,!0,!0))$[U]=[J[U]];else $[U]=J[U]}}}function nQ($,J){let{textNodeName:Z}=J,X=Object.keys($).length;if(X===0)return!0;if(X===1&&($[Z]||typeof $[Z]==="boolean"||$[Z]===0))return!0;return!1}class UJ{constructor($){this.externalEntities={},this.options=mY($)}parse($,J){if(typeof $!=="string"&&$.toString)$=$.toString();else if(typeof $!=="string")throw Error("XML data is accepted in String or Bytes[] form.");if(J){if(J===!0)J={};let Y=uY($,J);if(Y!==!0)throw Error(`${Y.err.msg}:${Y.err.line}:${Y.err.col}`)}let Z=new cJ(this.options);Z.addExternalEntities(this.externalEntities);let X=Z.parseXml($);if(this.options.preserveOrder||X===void 0)return X;else return YX(X,this.options)}addEntity($,J){if(J.indexOf("&")!==-1)throw Error("Entity value can't have '&'");else if($.indexOf("&")!==-1||$.indexOf(";")!==-1)throw Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");else if(J==="&")throw Error("An entity with value '&' is not permitted");else this.externalEntities[$]=J}static getMetaDataSymbol(){return r0.getMetaDataSymbol()}}var oQ=new UJ,nY={name:"parser",enable:!0,deps:["auth"],handler:async($,J)=>{if(!J.api)return;if(J.api.rawBody){J.body={};return}if(J.req.method==="GET"){let Z=new URL(J.req.url),X=Object.fromEntries(Z.searchParams);if(s(J.api.fields)&&!FJ(J.api.fields))J.body=AJ(X,Object.keys(J.api.fields));else J.body=X}else if(J.req.method==="POST"){let Z=J.req.headers.get("content-type")||"",X=new URL(J.req.url),Y=Object.fromEntries(X.searchParams);try{if(Z.includes("application/json")){let H=await J.req.json(),G={...Y,...H};if(s(J.api.fields)&&!FJ(J.api.fields))J.body=AJ(G,Object.keys(J.api.fields));else J.body=G}else if(Z.includes("application/xml")||Z.includes("text/xml")){let H=await J.req.text(),G=oQ.parse(H),U=Object.keys(G)[0],V=U&&typeof G[U]==="object"?G[U]:G,K={...Y,...V};if(s(J.api.fields)&&!FJ(J.api.fields))J.body=AJ(K,Object.keys(J.api.fields));else J.body=K}else{J.response=R$(J,"\u65E0\u6548\u7684\u8BF7\u6C42\u53C2\u6570\u683C\u5F0F",1,null,{location:"content-type",value:Z},"parser");return}}catch{J.response=R$(J,"\u65E0\u6548\u7684\u8BF7\u6C42\u53C2\u6570\u683C\u5F0F",1,null,{location:"body",reason:Z.includes("application/json")?"invalid_json":Z.includes("xml")?"invalid_xml":"invalid_body"},"parser");return}}}};a();var oY={name:"permission",enable:!0,deps:["validator"],handler:async($,J)=>{if(!J.api)return;if(J.api.auth===!1)return;if(!J.user||!J.user.id){J.response=R$(J,"\u672A\u767B\u5F55",1,null,null,"auth");return}if(J.user.roleCode==="dev")return;let Z=J.route,X=J.user.roleCode,Y=!1;if(X&&$.redis)try{let H=X0.roleApis(X);Y=await $.redis.sismember(H,Z)}catch(H){P.error({event:"hook_permission_redis_error",apiPath:Z,roleCode:X,err:H},"hook permission redis error"),Y=!1}if(!Y){let H=typeof J.api.name==="string"&&J.api.name.length>0?J.api.name:null,G=typeof Z==="string"&&Z.length>0?Z:null,U=H?H:G?G:"\u672A\u77E5\u63A5\u53E3";J.response=R$(J,`\u65E0\u6743\u8BBF\u95EE ${U} \u63A5\u53E3`,1,null,{apiLabel:U},"permission");return}}};var HX={number:"^\\d+$",integer:"^-?\\d+$",float:"^-?\\d+(\\.\\d+)?$",positive:"^[1-9]\\d*$",negative:"^-\\d+$",zero:"^0$",word:"^[a-zA-Z]+$",alphanumeric:"^[a-zA-Z0-9]+$",alphanumeric_:"^[a-zA-Z0-9_]+$",alphanumericDash_:"^[a-zA-Z0-9_-]+$",lowercase:"^[a-z]+$",uppercase:"^[A-Z]+$",chinese:"^[\\u4e00-\\u9fa5]+$",chineseWord:"^[\\u4e00-\\u9fa5a-zA-Z]+$",email:"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",phone:"^1[3-9]\\d{9}$",telephone:"^0\\d{2,3}-?\\d{7,8}$",url:"^https?://",ip:"^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$",ipv6:"^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$",domain:"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$",uuid:"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",hex:"^[0-9a-fA-F]+$",base64:"^[A-Za-z0-9+/=]+$",md5:"^[a-f0-9]{32}$",sha1:"^[a-f0-9]{40}$",sha256:"^[a-f0-9]{64}$",date:"^\\d{4}-\\d{2}-\\d{2}$",time:"^\\d{2}:\\d{2}:\\d{2}$",datetime:"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}",year:"^\\d{4}$",month:"^(0[1-9]|1[0-2])$",day:"^(0[1-9]|[12]\\d|3[01])$",variable:"^[a-zA-Z_][a-zA-Z0-9_]*$",constant:"^[A-Z][A-Z0-9_]*$",package:"^[a-z][a-z0-9-]*$",idCard:"^\\d{17}[\\dXx]$",passport:"^[a-zA-Z0-9]{5,17}$",bankCard:"^\\d{16,19}$",wechat:"^[a-zA-Z][a-zA-Z0-9_-]{5,19}$",qq:"^[1-9]\\d{4,10}$",alipay:"^(1[3-9]\\d{9}|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,})$",username:"^[a-zA-Z][a-zA-Z0-9_]{3,19}$",nickname:"^[\\u4e00-\\u9fa5a-zA-Z0-9]{2,20}$",passwordWeak:"^.{6,}$",passwordMedium:"^(?=.*[a-zA-Z])(?=.*\\d).{8,}$",passwordStrong:"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*]).{8,}$",licensePlate:"^[\u4EAC\u6D25\u6CAA\u6E1D\u5180\u8C6B\u4E91\u8FBD\u9ED1\u6E58\u7696\u9C81\u65B0\u82CF\u6D59\u8D63\u9102\u6842\u7518\u664B\u8499\u9655\u5409\u95FD\u8D35\u7CA4\u9752\u85CF\u5DDD\u5B81\u743C\u4F7F\u9886][A-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9\u6302\u5B66\u8B66\u6E2F\u6FB3]$",postalCode:"^\\d{6}$",semver:"^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.]+)?(\\+[a-zA-Z0-9.]+)?$",colorHex:"^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$",empty:"^$",notempty:".+"},sY=new Map;function sQ($){if($.startsWith("@")){let J=$.slice(1);return HX[J]||$}return $}function lY($,J){let Z=sQ($),X=`${Z}:${J||""}`,Y=sY.get(X);if(!Y)Y=new RegExp(Z,J),sY.set(X,Y);return Y}class WX{static validate($,J,Z=[]){let X={};if(!$||typeof $!=="object"||Array.isArray($))return this.buildResult({_error:"\u6570\u636E\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F"});if(!J||typeof J!=="object")return this.buildResult({_error:"\u9A8C\u8BC1\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F"});for(let Y of Z){let H=$[Y];if(H===void 0||H===null||H===""){let G=J[Y]?.name||Y;X[Y]=`${G}\u4E3A\u5FC5\u586B\u9879`}}for(let[Y,H]of Object.entries(J)){if(X[Y])continue;if($[Y]===void 0&&!Z.includes(Y))continue;let G=this.checkField($[Y],H,Y);if(G)X[Y]=G}return this.buildResult(X)}static single($,J){let{type:Z,default:X}=J;if($===void 0||$===null||$==="")return{value:this.defaultFor(Z,X),error:null};let Y=this.convert($,Z);if(Y.error)return{value:null,error:Y.error};let H=this.checkRule(Y.value,J);if(H)return{value:null,error:H};return{value:Y.value,error:null}}static buildResult($){let J=Object.values($),Z=Object.keys($),X=J.length>0;return{code:X?1:0,failed:X,firstError:X?J[0]:null,errors:J,errorFields:Z,fieldErrors:$}}static checkField($,J,Z){let X=J.name||Z,Y=this.convert($,J.type);if(Y.error)return`${X}${Y.error}`;let H=this.checkRule(Y.value,J);return H?`${X}${H}`:null}static convert($,J){switch(J.toLowerCase()){case"number":if(typeof $==="number")return Number.isNaN($)||!isFinite($)?{value:null,error:"\u5FC5\u987B\u662F\u6709\u6548\u6570\u5B57"}:{value:$,error:null};if(typeof $==="string"){let Z=Number($);return Number.isNaN(Z)||!isFinite(Z)?{value:null,error:"\u5FC5\u987B\u662F\u6570\u5B57"}:{value:Z,error:null}}return{value:null,error:"\u5FC5\u987B\u662F\u6570\u5B57"};case"string":case"text":return typeof $==="string"?{value:$,error:null}:{value:null,error:"\u5FC5\u987B\u662F\u5B57\u7B26\u4E32"};case"array_string":case"array_text":return Array.isArray($)?{value:$,error:null}:{value:null,error:"\u5FC5\u987B\u662F\u6570\u7EC4"};case"array_number_string":case"array_number_text":if(!Array.isArray($))return{value:null,error:"\u5FC5\u987B\u662F\u6570\u7EC4"};for(let Z of $)if(typeof Z!=="number"||!isFinite(Z))return{value:null,error:"\u6570\u7EC4\u5143\u7D20\u5FC5\u987B\u662F\u6570\u5B57"};return{value:$,error:null};default:return{value:$,error:null}}}static checkRule($,J){let{type:Z,min:X,max:Y,regexp:H}=J,G=this.resolveRegex(H);switch(Z.toLowerCase()){case"number":if(X!==null&&$<X)return`\u4E0D\u80FD\u5C0F\u4E8E${X}`;if(Y!==null&&Y>0&&$>Y)return`\u4E0D\u80FD\u5927\u4E8E${Y}`;if(G&&!this.testRegex(G,String($)))return"\u683C\u5F0F\u4E0D\u6B63\u786E";break;case"string":case"text":if(X!==null&&$.length<X)return`\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E${X}\u4E2A\u5B57\u7B26`;if(Y!==null&&Y>0&&$.length>Y)return`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7${Y}\u4E2A\u5B57\u7B26`;if(G&&!this.testRegex(G,$))return"\u683C\u5F0F\u4E0D\u6B63\u786E";break;case"array_string":case"array_text":case"array_number_string":case"array_number_text":if(X!==null&&$.length<X)return`\u81F3\u5C11\u9700\u8981${X}\u4E2A\u5143\u7D20`;if(Y!==null&&Y>0&&$.length>Y)return`\u6700\u591A\u53EA\u80FD\u6709${Y}\u4E2A\u5143\u7D20`;if(G){for(let U of $)if(!this.testRegex(G,String(U)))return"\u5143\u7D20\u683C\u5F0F\u4E0D\u6B63\u786E"}break}return null}static resolveRegex($){if(!$)return null;if($.startsWith("@")){let J=$.substring(1);return HX[J]||$}return $}static testRegex($,J){try{return lY($).test(J)}catch{return!1}}static defaultFor($,J){if(J!==null&&J!==void 0){if(($==="array_string"||$==="array_text"||$==="array_number_string"||$==="array_number_text")&&typeof J==="string"){if(J==="[]")return[];try{let Z=JSON.parse(J);return Array.isArray(Z)?Z:[]}catch{return[]}}if($==="number"&&typeof J==="string"){let Z=Number(J);return isNaN(Z)?0:Z}return J}switch($.toLowerCase()){case"number":return 0;case"array_string":case"array_text":case"array_number_string":case"array_number_text":return[];default:return""}}}var rY={name:"validator",enable:!0,deps:["parser"],handler:async($,J)=>{if(!J.api)return;if(!J.api.fields)return;for(let[X,Y]of Object.entries(J.api.fields))if(J.body[X]===void 0&&Y?.default!==void 0&&Y?.default!==null)J.body[X]=Y.default;let Z=WX.validate(J.body,J.api.fields,J.api.required||[]);if(Z.code!==0){J.response=R$(J,Z.firstError||"\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25",1,null,Z.fieldErrors,"validator");return}}};a();class GX{db;redis;constructor($){this.db=$.db,this.redis=$.redis}assertApiPathname($,J){if(typeof $!=="string")throw Error(`${J} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32`);let Z=$.trim();if(!Z)throw Error(`${J} \u4E0D\u5141\u8BB8\u4E3A\u7A7A\u5B57\u7B26\u4E32`);if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(Z))throw Error(`${J} \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09`);if(!Z.startsWith("/"))throw Error(`${J} \u5FC5\u987B\u662F pathname\uFF08\u4EE5 / \u5F00\u5934\uFF09`);if(Z.includes(" "))throw Error(`${J} \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C`);return Z}assertApiPathList($,J){if($===null||$===void 0)return[];let Z=$;if(typeof Z==="string"){let Y=Z.trim();if(Y===""||Y==="null")return[];if(Y.startsWith("[")&&Y.endsWith("]"))try{Z=JSON.parse(Y)}catch{throw Error(`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis JSON \u89E3\u6790\u5931\u8D25\uFF0CroleCode=${J}`)}}if(!Array.isArray(Z))throw Error(`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\u6216 JSON \u6570\u7EC4\u5B57\u7B26\u4E32\uFF0CroleCode=${J}\uFF0Ctype=${typeof Z}`);let X=[];for(let Y of Z)X.push(this.assertApiPathname(Y,`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5143\u7D20\uFF0CroleCode=${J}`));return X}async cacheApis(){try{if(!(await this.db.tableExists("addon_admin_api")).data){P.warn("\u26A0\uFE0F \u63A5\u53E3\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u63A5\u53E3\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_api"});if(await this.redis.setObject(X0.apisAll(),J.data.lists)===null)P.warn("\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5931\u8D25")}catch($){P.error({err:$},"\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5F02\u5E38")}}async cacheMenus(){try{if(!(await this.db.tableExists("addon_admin_menu")).data){P.warn("\u26A0\uFE0F \u83DC\u5355\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u83DC\u5355\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_menu"});if(await this.redis.setObject(X0.menusAll(),J.data.lists)===null)P.warn("\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5931\u8D25")}catch($){P.warn({err:$},"\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5F02\u5E38")}}async rebuildRoleApiPermissions(){try{if(!(await this.db.tableExists("addon_admin_role")).data){P.warn("\u26A0\uFE0F \u89D2\u8272\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u89D2\u8272\u6743\u9650\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_role",fields:["code","apis"]}),Z=new Map;for(let G of J.data.lists){if(!G?.code)continue;let U=this.assertApiPathList(G.apis,G.code);Z.set(G.code,U)}let X=Array.from(Z.keys());if(X.length===0){P.info("\u2705 \u6CA1\u6709\u9700\u8981\u7F13\u5B58\u7684\u89D2\u8272\u6743\u9650");return}let Y=X.map((G)=>X0.roleApis(G));await this.redis.delBatch(Y);let H=[];for(let G of X){let U=Z.get(G)||[],V=Array.from(new Set(U)).sort();if(V.length>0)H.push({key:X0.roleApis(G),members:V})}if(H.length>0)await this.redis.saddBatch(H)}catch($){throw P.error({err:$},"\u26A0\uFE0F \u89D2\u8272\u6743\u9650\u7F13\u5B58\u5F02\u5E38\uFF08\u5C06\u963B\u65AD\u542F\u52A8\uFF09"),$}}async refreshRoleApiPermissions($,J){if(!$||typeof $!=="string")throw Error("roleCode \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!Array.isArray(J))throw Error("apiPaths \u5FC5\u987B\u662F\u6570\u7EC4");let Z=J.map((H)=>this.assertApiPathname(H,`refreshRoleApiPermissions: apiPaths \u5143\u7D20\uFF0CroleCode=${$}`)),X=X0.roleApis($);if(Z.length===0){await this.redis.del(X);return}let Y=Array.from(new Set(Z));if(await this.redis.del(X),Y.length>0)await this.redis.sadd(X,Y)}async cacheAll(){await this.cacheApis(),await this.cacheMenus(),await this.rebuildRoleApiPermissions()}async getApis(){try{return await this.redis.getObject(X0.apisAll())||[]}catch($){return P.error({err:$},"\u83B7\u53D6\u63A5\u53E3\u7F13\u5B58\u5931\u8D25"),[]}}async getMenus(){try{return await this.redis.getObject(X0.menusAll())||[]}catch($){return P.error({err:$},"\u83B7\u53D6\u83DC\u5355\u7F13\u5B58\u5931\u8D25"),[]}}async getRolePermissions($){try{return await this.redis.smembers(X0.roleApis($))||[]}catch(J){return P.error({err:J,roleCode:$},"\u83B7\u53D6\u89D2\u8272\u6743\u9650\u7F13\u5B58\u5931\u8D25"),[]}}async checkRolePermission($,J){try{let Z=this.assertApiPathname(J,"checkRolePermission: apiPath");return await this.redis.sismember(X0.roleApis($),Z)}catch(Z){return P.error({err:Z,roleCode:$},"\u68C0\u67E5\u89D2\u8272\u6743\u9650\u5931\u8D25"),!1}}async deleteRolePermissions($){try{if(await this.redis.del(X0.roleApis($))>0)return P.info(`\u2705 \u5DF2\u5220\u9664\u89D2\u8272 ${$} \u7684\u6743\u9650\u7F13\u5B58`),!0;return!1}catch(J){return P.error({err:J,roleCode:$},"\u5220\u9664\u89D2\u8272\u6743\u9650\u7F13\u5B58\u5931\u8D25"),!1}}}var iY={name:"cache",enable:!0,deps:["logger","redis","db"],async handler($){if(!$.db)throw Error("\u7F13\u5B58\u521D\u59CB\u5316\u5931\u8D25\uFF1Actx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.redis)throw Error("\u7F13\u5B58\u521D\u59CB\u5316\u5931\u8D25\uFF1Actx.redis \u672A\u521D\u59CB\u5316\uFF08Redis \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");return new GX({db:$.db,redis:$.redis})}};var tY={name:"cipher",enable:!0,deps:[],handler:()=>{return y$}};var aY={name:"config",enable:!0,deps:[],handler:($)=>{return $.config}};function pJ($,J=["id","pid","sort"]){if(!$||!Array.isArray($))return $;return $.map((Z)=>{let X={};for(let[Y,H]of Object.entries(Z))X[Y]=H;for(let[Y,H]of Object.entries(X)){if(H===void 0||H===null)continue;if((J.includes(Y)||Y.endsWith("Id")||Y.endsWith("_id")||Y.endsWith("At")||Y.endsWith("_at"))&&typeof H==="string"){let U=Number(H);if(!isNaN(U))X[Y]=U}}return X})}function QX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function lQ($){return Array.isArray($)}function S$($,J={}){let{pickKeys:Z,omitKeys:X,keepValues:Y,excludeValues:H,keepMap:G}=J,U=(V)=>{let K={},F=Object.keys(V);if(Z&&Z.length)F=F.filter((A)=>Z.includes(A));if(X&&X.length)F=F.filter((A)=>!X.includes(A));for(let A of F){let j=V[A];if(G&&A in G){if(Object.is(G[A],j)){K[A]=j;continue}}if(Y&&Y.length&&!Y.includes(j))continue;if(H&&H.length&&H.includes(j))continue;K[A]=j}return K};if(lQ($))return $.map((V)=>QX(V)?U(V):V).filter((V)=>{if(QX(V))return Object.keys(V).length>0;return!0});if(QX($))return U($);return $}class h{static parseTableRef($){if(typeof $!=="string")throw Error(`tableRef \u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (tableRef: ${String($)})`);let J=$.trim();if(!J)throw Error("tableRef \u4E0D\u80FD\u4E3A\u7A7A");let Z=J.split(/\s+/).filter((V)=>V.length>0);if(Z.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08\u5305\u542B\u8FC7\u591A\u7247\u6BB5\uFF09\u3002\u8BF7\u4F7F\u7528\u6700\u7B80\u5F62\u5F0F\uFF1Atable \u6216 table alias \u6216 schema.table \u6216 schema.table alias (tableRef: ${J})`);let X=Z[0],Y=Z.length===2?Z[1]:null,H=X.split(".");if(H.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09 (tableRef: ${J})`);let G=H.length===2?H[0]:null,U=H.length===2?H[1]:H[0];return{schema:G,table:U,alias:Y}}static normalizeTableRef($){let J=h.parseTableRef($),Z=J.schema?p(J.schema):null,X=p(J.table),Y=Z?`${Z}.${X}`:X;if(J.alias)Y=`${Y} ${J.alias}`;return Y}static getJoinMainQualifier($){let J=h.parseTableRef($);if(J.alias)return J.alias;return p(J.table)}static async fieldsToSnake($,J,Z){if(!J||!Array.isArray(J))return["*"];let X=h.validateAndClassifyFields(J);if(X.type==="all")return["*"];if(X.type==="include")return X.fields.map((Y)=>{if(Y.includes("(")||Y.includes(" "))return Y;return p(Y)});if(X.type==="exclude"){let Y=await Z($),H=X.fields.map((U)=>p(U)),G=Y.filter((U)=>!H.includes(U));if(G.length===0)throw Error(`\u6392\u9664\u5B57\u6BB5\u540E\u6CA1\u6709\u5269\u4F59\u5B57\u6BB5\u53EF\u67E5\u8BE2\u3002\u8868: ${$}, \u6392\u9664: ${H.join(", ")}`);return G}return["*"]}static validateAndClassifyFields($){if(!$||$.length===0)return{type:"all",fields:[]};if($.some((X)=>X==="*"))throw Error("fields \u4E0D\u652F\u6301 * \u661F\u53F7\uFF0C\u8BF7\u4F7F\u7528\u7A7A\u6570\u7EC4 [] \u6216\u4E0D\u4F20\u53C2\u6570\u8868\u793A\u67E5\u8BE2\u6240\u6709\u5B57\u6BB5");if($.some((X)=>!X||typeof X!=="string"||X.trim()===""))throw Error("fields \u4E0D\u80FD\u5305\u542B\u7A7A\u5B57\u7B26\u4E32\u6216\u65E0\u6548\u503C");let J=$.filter((X)=>!X.startsWith("!")),Z=$.filter((X)=>X.startsWith("!"));if(J.length>0&&Z.length===0)return{type:"include",fields:J};if(Z.length>0&&J.length===0)return{type:"exclude",fields:Z.map((Y)=>Y.substring(1))};throw Error(`fields \u4E0D\u80FD\u540C\u65F6\u5305\u542B\u666E\u901A\u5B57\u6BB5\u548C\u6392\u9664\u5B57\u6BB5\uFF08! \u5F00\u5934\uFF09\u3002\u53EA\u80FD\u4F7F\u7528\u4EE5\u4E0B3\u79CD\u65B9\u5F0F\u4E4B\u4E00\uFF1A
|
|
19
|
+
1. \u7A7A\u6570\u7EC4 [] \u6216\u4E0D\u4F20\uFF08\u67E5\u8BE2\u6240\u6709\uFF09
|
|
20
|
+
2. \u5168\u90E8\u6307\u5B9A\u5B57\u6BB5 ["id", "name"]
|
|
21
|
+
3. \u5168\u90E8\u6392\u9664\u5B57\u6BB5 ["!password", "!token"]`)}static orderByToSnake($){if(!$||!Array.isArray($))return $;return $.map((J)=>{if(typeof J!=="string"||!J.includes("#"))return J;let[Z,X]=J.split("#");return`${p(Z.trim())}#${X.trim()}`})}static processJoinField($){if($.includes("(")||$==="*"||$.startsWith("`"))return $;if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i),Z=J[0].trim(),X=J[1].trim();return`${h.processJoinField(Z)} AS ${X}`}if($.includes(".")){let J=$.split("."),Z=J[0],X=J[1];return`${Z.trim()}.${p(X)}`}return p($)}static processJoinWhereKey($){if($==="$or"||$==="$and")return $;if($.includes("$")){let J=$.lastIndexOf("$"),Z=$.substring(0,J),X=$.substring(J);if(Z.includes(".")){let Y=Z.split("."),H=Y[0],G=Y[1];return`${H.trim()}.${p(G)}${X}`}return`${p(Z)}${X}`}if($.includes(".")){let J=$.split("."),Z=J[0],X=J[1];return`${Z.trim()}.${p(X)}`}return p($)}static processJoinWhere($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>h.processJoinWhere(Z));let J={};for(let[Z,X]of Object.entries($)){let Y=h.processJoinWhereKey(Z);if(Z==="$or"||Z==="$and")J[Y]=X.map((H)=>h.processJoinWhere(H));else if(typeof X==="object"&&X!==null&&!Array.isArray(X))J[Y]=h.processJoinWhere(X);else J[Y]=X}return J}static processJoinOrderBy($){if(!$||!Array.isArray($))return $;return $.map((J)=>{if(typeof J!=="string"||!J.includes("#"))return J;let[Z,X]=J.split("#");return`${h.processJoinField(Z.trim())}#${X.trim()}`})}static addDefaultStateFilter($={},J,Z=!1){if(Object.keys($).some((H)=>H.startsWith("state")||H.includes(".state")))return $;if(Z&&J){let H={};for(let[G,U]of Object.entries($))H[G]=U;return H[`${J}.state$gt`]=0,H}let Y={};for(let[H,G]of Object.entries($))Y[H]=G;return Y.state$gt=0,Y}static whereKeysToSnake($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>h.whereKeysToSnake(Z));let J={};for(let[Z,X]of Object.entries($)){if(Z==="$or"||Z==="$and"){J[Z]=X.map((H)=>h.whereKeysToSnake(H));continue}if(Z.includes("$")){let H=Z.lastIndexOf("$"),G=Z.substring(0,H),U=Z.substring(H),V=p(G)+U;J[V]=X;continue}let Y=p(Z);if(typeof X==="object"&&X!==null&&!Array.isArray(X))J[Y]=h.whereKeysToSnake(X);else J[Y]=X}return J}static serializeArrayFields($){let J={};for(let[Z,X]of Object.entries($)){if(X===null||X===void 0){J[Z]=X;continue}if(Array.isArray(X)){J[Z]=JSON.stringify(X);continue}J[Z]=X}return J}static deserializeArrayFields($){if(!$)return null;let J={};for(let[Z,X]of Object.entries($))J[Z]=X;for(let[Z,X]of Object.entries(J)){if(typeof X!=="string")continue;if(X.startsWith("[")&&X.endsWith("]"))try{let Y=JSON.parse(X);if(Array.isArray(Y))J[Z]=Y}catch{}}return J}static cleanAndSnakeAndSerializeWriteData($,J=[null,void 0]){let Z=S$($,{excludeValues:J}),X=G1(Z);return h.serializeArrayFields(X)}static stripSystemFieldsForWrite($,J){let Z={};for(let[X,Y]of Object.entries($)){if(X==="id")continue;if(X==="created_at")continue;if(X==="updated_at")continue;if(X==="deleted_at")continue;if(!J.allowState&&X==="state")continue;Z[X]=Y}return Z}static buildInsertRow($){let J=h.cleanAndSnakeAndSerializeWriteData($.data),Z=h.stripSystemFieldsForWrite(J,{allowState:!1}),X={};for(let[Y,H]of Object.entries(Z))X[Y]=H;return X.id=$.id,X.created_at=$.now,X.updated_at=$.now,X.state=1,X}static buildUpdateRow($){let J=h.cleanAndSnakeAndSerializeWriteData($.data),Z=h.stripSystemFieldsForWrite(J,{allowState:$.allowState}),X={};for(let[Y,H]of Object.entries(Z))X[Y]=H;return X.updated_at=$.now,X}static buildPartialUpdateData($){let J=h.cleanAndSnakeAndSerializeWriteData($.data);return h.stripSystemFieldsForWrite(J,{allowState:$.allowState})}}a();class c0{static SAFE_IDENTIFIER_RE=/^[a-zA-Z_][a-zA-Z0-9_]*$/;static assertNonEmptyString($,J){if(typeof $!=="string")throw Error(`${J} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (value: ${String($)})`);if(!$.trim())throw Error(`${J} \u4E0D\u80FD\u4E3A\u7A7A`)}static assertNoUndefinedParam($,J){if($===void 0)throw Error(`${J} \u4E0D\u80FD\u4E3A undefined`)}static startsWithQuote($){let J=$.trim();return J.startsWith("`")||J.startsWith('"')}static isQuotedIdentPaired($){let J=$.trim();if(J.length<2)return!1;let Z=J[0],X=J[J.length-1];if(Z==="`"&&X==="`")return!0;if(Z==='"'&&X==='"')return!0;return!1}static assertPairedQuotedIdentIfStartsWithQuote($,J){if(c0.startsWithQuote($)&&!c0.isQuotedIdentPaired($))throw Error(`${J} \u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (value: ${$})`)}static assertSafeIdentifierPart($,J){if(!c0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684 ${J} \u6807\u8BC6\u7B26: ${$}`)}static assertSafeAlias($){if(c0.isQuotedIdentPaired($))return;if(!c0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u522B\u540D: ${$}`)}static assertNoExprField($){if(typeof $!=="string")return;let J=$.trim();if(!J)return;if(J.includes("(")||J.includes(")"))throw Error(`\u5B57\u6BB5\u5305\u542B\u51FD\u6570/\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${J})`)}static assertNoUndefinedInRecord($,J){for(let[Z,X]of Object.entries($))if(X===void 0)throw Error(`${J} \u5B58\u5728 undefined \u5B57\u6BB5\u503C (field: ${Z})`)}static assertBatchInsertRowsConsistent($,J){if(!Array.isArray($))throw Error("\u6279\u91CF\u63D2\u5165 rows \u5FC5\u987B\u662F\u6570\u7EC4");if($.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A (table: ${J.table})`);let Z=$[0];if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`\u6279\u91CF\u63D2\u5165\u7684\u6BCF\u4E00\u884C\u5FC5\u987B\u662F\u5BF9\u8C61 (table: ${J.table}, rowIndex: 0)`);let X=Object.keys(Z);if(X.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${J.table})`);let Y=new Set(X);for(let H=0;H<$.length;H++){let G=$[H];if(!G||typeof G!=="object"||Array.isArray(G))throw Error(`\u6279\u91CF\u63D2\u5165\u7684\u6BCF\u4E00\u884C\u5FC5\u987B\u662F\u5BF9\u8C61 (table: ${J.table}, rowIndex: ${H})`);let U=Object.keys(G);if(U.length!==X.length)throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${H})`);for(let V of U)if(!Y.has(V))throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${H}, extraField: ${V})`);for(let V of X){if(!(V in G))throw Error(`\u6279\u91CF\u63D2\u5165\u7F3A\u5C11\u5B57\u6BB5 (table: ${J.table}, rowIndex: ${H}, field: ${V})`);c0.assertNoUndefinedParam(G[V],`\u6279\u91CF\u63D2\u5165\u5B57\u6BB5\u503C (table: ${J.table}, rowIndex: ${H}, field: ${V})`)}}return X}}var b={QUOTE_IDENT_NEED_STRING:($)=>`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`,IDENT_EMPTY:"SQL \u6807\u8BC6\u7B26\u4E0D\u80FD\u4E3A\u7A7A",FIELD_EXPR_NOT_ALLOWED:($)=>`\u5B57\u6BB5\u5305\u542B\u51FD\u6570/\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${$})`,FROM_EMPTY:"FROM \u8868\u540D\u4E0D\u80FD\u4E3A\u7A7A",FROM_NEED_NON_EMPTY:($)=>`FROM \u8868\u540D\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32 (table: ${String($)})`,FROM_REQUIRED:"FROM \u8868\u540D\u662F\u5FC5\u9700\u7684",COUNT_NEED_FROM:"COUNT \u9700\u8981 FROM \u8868\u540D",TABLE_REF_TOO_MANY_PARTS:($)=>`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08\u5305\u542B\u8FC7\u591A\u7247\u6BB5\uFF09\u3002\u8BF7\u4F7F\u7528 fromRaw \u663E\u5F0F\u4F20\u5165\u590D\u6742\u8868\u8FBE\u5F0F (table: ${$})`,TABLE_REF_SCHEMA_TOO_DEEP:($)=>`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09\u3002\u8BF7\u4F7F\u7528 fromRaw (table: ${$})`,SCHEMA_QUOTE_NOT_PAIRED:($)=>`schema \u6807\u8BC6\u7B26\u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (schema: ${$})`,TABLE_QUOTE_NOT_PAIRED:($)=>`table \u6807\u8BC6\u7B26\u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (table: ${$})`,SELECT_FIELDS_INVALID:"SELECT \u5B57\u6BB5\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u6570\u7EC4",SELECT_RAW_NEED_NON_EMPTY:($)=>`selectRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (expr: ${String($)})`,FROM_RAW_NEED_NON_EMPTY:($)=>`fromRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (tableExpr: ${String($)})`,WHERE_RAW_NEED_NON_EMPTY:($)=>`whereRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (sql: ${String($)})`,WHERE_VALUE_REQUIRED:"where(field, value) \u4E0D\u5141\u8BB8\u7701\u7565 value\u3002\u82E5\u9700\u4F20\u5165\u539F\u59CB WHERE\uFF0C\u8BF7\u4F7F\u7528 whereRaw",JOIN_NEED_STRING:($,J)=>`JOIN \u8868\u540D\u548C\u6761\u4EF6\u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (table: ${String($)}, on: ${String(J)})`,ORDER_BY_NEED_ARRAY:'orderBy \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\uFF0C\u683C\u5F0F\u4E3A "\u5B57\u6BB5#\u65B9\u5411"',ORDER_BY_ITEM_NEED_HASH:($)=>`orderBy \u5B57\u6BB5\u5FC5\u987B\u662F "\u5B57\u6BB5#\u65B9\u5411" \u683C\u5F0F\u7684\u5B57\u7B26\u4E32\uFF08\u4F8B\u5982\uFF1A"name#ASC", "id#DESC"\uFF09 (item: ${String($)})`,ORDER_BY_FIELD_EMPTY:($)=>`orderBy \u4E2D\u5B57\u6BB5\u540D\u4E0D\u80FD\u4E3A\u7A7A (item: ${$})`,ORDER_BY_DIR_INVALID:($)=>`ORDER BY \u65B9\u5411\u5FC5\u987B\u662F ASC \u6216 DESC (direction: ${$})`,LIMIT_MUST_NON_NEGATIVE:($)=>`LIMIT \u6570\u91CF\u5FC5\u987B\u662F\u975E\u8D1F\u6570 (count: ${String($)})`,OFFSET_MUST_NON_NEGATIVE:($)=>`OFFSET \u5FC5\u987B\u662F\u975E\u8D1F\u6570 (offset: ${String($)})`,OFFSET_COUNT_MUST_NON_NEGATIVE:($)=>`OFFSET \u5FC5\u987B\u662F\u975E\u8D1F\u6570 (count: ${String($)})`,INSERT_NEED_TABLE:($)=>`INSERT \u9700\u8981\u8868\u540D (table: ${String($)})`,INSERT_NEED_DATA:($,J)=>`INSERT \u9700\u8981\u6570\u636E (table: ${String($)}, data: ${JSON.stringify(J)})`,INSERT_NEED_AT_LEAST_ONE_FIELD:($)=>`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${$})`,UPDATE_NEED_TABLE:"UPDATE \u9700\u8981\u8868\u540D",UPDATE_NEED_OBJECT:"UPDATE \u9700\u8981\u6570\u636E\u5BF9\u8C61",UPDATE_NEED_AT_LEAST_ONE_FIELD:"\u66F4\u65B0\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5",UPDATE_NEED_WHERE:"\u4E3A\u5B89\u5168\u8D77\u89C1\uFF0CUPDATE \u9700\u8981 WHERE \u6761\u4EF6",DELETE_NEED_TABLE:"DELETE \u9700\u8981\u8868\u540D",DELETE_NEED_WHERE:"\u4E3A\u5B89\u5168\u8D77\u89C1\uFF0CDELETE \u9700\u8981 WHERE \u6761\u4EF6",TO_DELETE_IN_NEED_TABLE:($)=>`toDeleteInSql \u9700\u8981\u975E\u7A7A\u8868\u540D (table: ${String($)})`,TO_DELETE_IN_NEED_ID_FIELD:($)=>`toDeleteInSql \u9700\u8981\u975E\u7A7A idField (idField: ${String($)})`,TO_DELETE_IN_NEED_IDS:"toDeleteInSql \u9700\u8981 ids \u6570\u7EC4",TO_UPDATE_CASE_NEED_TABLE:($)=>`toUpdateCaseByIdSql \u9700\u8981\u975E\u7A7A\u8868\u540D (table: ${String($)})`,TO_UPDATE_CASE_NEED_ID_FIELD:($)=>`toUpdateCaseByIdSql \u9700\u8981\u975E\u7A7A idField (idField: ${String($)})`,TO_UPDATE_CASE_NEED_ROWS:"toUpdateCaseByIdSql \u9700\u8981 rows \u6570\u7EC4",TO_UPDATE_CASE_NEED_FIELDS:"toUpdateCaseByIdSql \u9700\u8981 fields \u6570\u7EC4"};class b${_select=[];_from="";_where=[];_joins=[];_orderBy=[];_groupBy=[];_having=[];_limit=null;_offset=null;_params=[];_quoteIdent;constructor($){if($&&$.quoteIdent)this._quoteIdent=$.quoteIdent;else this._quoteIdent=(J)=>{if(typeof J!=="string")throw Error(b.QUOTE_IDENT_NEED_STRING(J));let Z=J.trim();if(!Z)throw Error(b.IDENT_EMPTY);return`\`${Z.replace(/`/g,"``")}\``}}_isQuotedIdent($){return c0.isQuotedIdentPaired($)}_startsWithQuote($){return c0.startsWithQuote($)}reset(){return this._select=[],this._from="",this._where=[],this._joins=[],this._orderBy=[],this._groupBy=[],this._having=[],this._limit=null,this._offset=null,this._params=[],this}_escapeField($){if(typeof $!=="string")return $;if($=$.trim(),c0.assertPairedQuotedIdentIfStartsWithQuote($,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),$==="*"||this._isQuotedIdent($))return $;try{c0.assertNoExprField($)}catch{throw Error(b.FIELD_EXPR_NOT_ALLOWED($))}if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i),Z=J[0].trim(),X=J[1].trim();return c0.assertSafeAlias(X),`${this._escapeField(Z)} AS ${X}`}if($.includes("."))return $.split(".").map((Z)=>{if(Z=Z.trim(),Z==="*"||this._isQuotedIdent(Z))return Z;return c0.assertPairedQuotedIdentIfStartsWithQuote(Z,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),this._quoteIdent(Z)}).join(".");return this._quoteIdent($)}_validateIdentifierPart($,J){c0.assertSafeIdentifierPart($,J)}_escapeTable($){if(typeof $!=="string")return $;if($=$.trim(),this._startsWithQuote($)&&!this._isQuotedIdent($));if(this._isQuotedIdent($))return $;let J=$.split(/\s+/).filter((G)=>G.length>0);if(J.length===0)throw Error(b.FROM_EMPTY);if(J.length>2)throw Error(b.TABLE_REF_TOO_MANY_PARTS($));let Z=J[0].trim(),X=J.length===2?J[1].trim():null,Y=Z.split(".");if(Y.length>2)throw Error(b.TABLE_REF_SCHEMA_TOO_DEEP($));let H="";if(Y.length===2){let G=Y[0].trim(),U=Y[1].trim(),V=this._isQuotedIdent(G)?G:(()=>{if(this._startsWithQuote(G)&&!this._isQuotedIdent(G))throw Error(b.SCHEMA_QUOTE_NOT_PAIRED(G));return this._validateIdentifierPart(G,"schema"),this._quoteIdent(G)})(),K=this._isQuotedIdent(U)?U:(()=>{if(this._startsWithQuote(U)&&!this._isQuotedIdent(U))throw Error(b.TABLE_QUOTE_NOT_PAIRED(U));return this._validateIdentifierPart(U,"table"),this._quoteIdent(U)})();H=`${V}.${K}`}else{let G=Y[0].trim();if(this._isQuotedIdent(G))H=G;else{if(this._startsWithQuote(G)&&!this._isQuotedIdent(G))throw Error(b.TABLE_QUOTE_NOT_PAIRED(G));this._validateIdentifierPart(G,"table"),H=this._quoteIdent(G)}}if(X)return this._validateIdentifierPart(X,"alias"),`${H} ${X}`;return H}_validateParam($){c0.assertNoUndefinedParam($,"SQL \u53C2\u6570\u503C")}_applyOperator($,J,Z){let X=this._escapeField($);switch(J){case"$ne":case"$not":this._validateParam(Z),this._where.push(`${X} != ?`),this._params.push(Z);break;case"$in":if(!Array.isArray(Z))throw Error(`$in \u64CD\u4F5C\u7B26\u7684\u503C\u5FC5\u987B\u662F\u6570\u7EC4 (operator: ${J})`);if(Z.length===0)throw Error("$in \u64CD\u4F5C\u7B26\u7684\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A\u3002\u63D0\u793A\uFF1A\u7A7A\u6570\u7EC4\u4F1A\u5BFC\u81F4\u67E5\u8BE2\u6C38\u8FDC\u4E0D\u5339\u914D\u4EFB\u4F55\u8BB0\u5F55\uFF0C\u8FD9\u901A\u5E38\u4E0D\u662F\u9884\u671F\u884C\u4E3A\u3002\u8BF7\u68C0\u67E5\u67E5\u8BE2\u6761\u4EF6\u6216\u79FB\u9664\u8BE5\u5B57\u6BB5\u3002");let Y=Z.map(()=>"?").join(",");this._where.push(`${X} IN (${Y})`),this._params.push(...Z);break;case"$nin":case"$notIn":if(!Array.isArray(Z))throw Error(`$nin/$notIn \u64CD\u4F5C\u7B26\u7684\u503C\u5FC5\u987B\u662F\u6570\u7EC4 (operator: ${J})`);if(Z.length===0)throw Error("$nin/$notIn \u64CD\u4F5C\u7B26\u7684\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A\u3002\u63D0\u793A\uFF1A\u7A7A\u6570\u7EC4\u4F1A\u5BFC\u81F4\u67E5\u8BE2\u5339\u914D\u6240\u6709\u8BB0\u5F55\uFF0C\u8FD9\u901A\u5E38\u4E0D\u662F\u9884\u671F\u884C\u4E3A\u3002\u8BF7\u68C0\u67E5\u67E5\u8BE2\u6761\u4EF6\u6216\u79FB\u9664\u8BE5\u5B57\u6BB5\u3002");let H=Z.map(()=>"?").join(",");this._where.push(`${X} NOT IN (${H})`),this._params.push(...Z);break;case"$like":this._validateParam(Z),this._where.push(`${X} LIKE ?`),this._params.push(Z);break;case"$notLike":this._validateParam(Z),this._where.push(`${X} NOT LIKE ?`),this._params.push(Z);break;case"$gt":this._validateParam(Z),this._where.push(`${X} > ?`),this._params.push(Z);break;case"$gte":this._validateParam(Z),this._where.push(`${X} >= ?`),this._params.push(Z);break;case"$lt":this._validateParam(Z),this._where.push(`${X} < ?`),this._params.push(Z);break;case"$lte":this._validateParam(Z),this._where.push(`${X} <= ?`),this._params.push(Z);break;case"$between":if(Array.isArray(Z)&&Z.length===2)this._validateParam(Z[0]),this._validateParam(Z[1]),this._where.push(`${X} BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$notBetween":if(Array.isArray(Z)&&Z.length===2)this._validateParam(Z[0]),this._validateParam(Z[1]),this._where.push(`${X} NOT BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$null":if(Z===!0)this._where.push(`${X} IS NULL`);break;case"$notNull":if(Z===!0)this._where.push(`${X} IS NOT NULL`);break;default:this._validateParam(Z),this._where.push(`${X} = ?`),this._params.push(Z)}}_processWhereConditions($){if(!$||typeof $!=="object")return;Object.entries($).forEach(([J,Z])=>{if(Z===void 0)return;if(J==="$and"){if(Array.isArray(Z))Z.forEach((X)=>this._processWhereConditions(X))}else if(J==="$or"){if(Array.isArray(Z)){let X=[],Y=[];if(Z.forEach((H)=>{let G=new b$({quoteIdent:this._quoteIdent});if(G._processWhereConditions(H),G._where.length>0)X.push(`(${G._where.join(" AND ")})`),Y.push(...G._params)}),X.length>0)this._where.push(`(${X.join(" OR ")})`),this._params.push(...Y)}}else if(J.includes("$")){let X=J.lastIndexOf("$"),Y=J.substring(0,X),H="$"+J.substring(X+1);this._applyOperator(Y,H,Z)}else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))for(let[X,Y]of Object.entries(Z))this._applyOperator(J,X,Y);else{this._validateParam(Z);let X=this._escapeField(J);this._where.push(`${X} = ?`),this._params.push(Z)}})}getWhereConditions(){return{sql:this._where.length>0?this._where.join(" AND "):"",params:[...this._params]}}select($="*"){if(Array.isArray($))this._select=[...this._select,...$.map((J)=>this._escapeField(J))];else if(typeof $==="string")this._select.push(this._escapeField($));else throw Error(b.SELECT_FIELDS_INVALID);return this}selectRaw($){if(typeof $!=="string"||!$.trim())throw Error(b.SELECT_RAW_NEED_NON_EMPTY($));return this._select.push($),this}from($){if(typeof $!=="string"||!$.trim())throw Error(b.FROM_NEED_NON_EMPTY($));return this._from=this._escapeTable($.trim()),this}fromRaw($){if(typeof $!=="string"||!$.trim())throw Error(b.FROM_RAW_NEED_NON_EMPTY($));return this._from=$,this}where($,J){if(typeof $==="object"&&$!==null)return this._processWhereConditions($),this;if(typeof $==="string"){if(J===void 0)throw Error(b.WHERE_VALUE_REQUIRED);this._validateParam(J);let Z=this._escapeField($);return this._where.push(`${Z} = ?`),this._params.push(J),this}return this}whereRaw($,J){if(typeof $!=="string"||!$.trim())throw Error(b.WHERE_RAW_NEED_NON_EMPTY($));if(this._where.push($),J&&J.length>0)this._params.push(...J);return this}leftJoin($,J){if(typeof $!=="string"||typeof J!=="string")throw Error(b.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`LEFT JOIN ${Z} ON ${J}`),this}rightJoin($,J){if(typeof $!=="string"||typeof J!=="string")throw Error(b.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`RIGHT JOIN ${Z} ON ${J}`),this}innerJoin($,J){if(typeof $!=="string"||typeof J!=="string")throw Error(b.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`INNER JOIN ${Z} ON ${J}`),this}orderBy($){if(!Array.isArray($))throw Error(b.ORDER_BY_NEED_ARRAY);return $.forEach((J)=>{if(typeof J!=="string"||!J.includes("#"))throw Error(b.ORDER_BY_ITEM_NEED_HASH(J));let[Z,X]=J.split("#"),Y=Z.trim(),H=X.trim().toUpperCase();if(!Y)throw Error(b.ORDER_BY_FIELD_EMPTY(J));if(!["ASC","DESC"].includes(H))throw Error(b.ORDER_BY_DIR_INVALID(H));let G=this._escapeField(Y);this._orderBy.push(`${G} ${H}`)}),this}groupBy($){if(Array.isArray($)){let J=$.filter((Z)=>typeof Z==="string").map((Z)=>this._escapeField(Z));this._groupBy=[...this._groupBy,...J]}else if(typeof $==="string")this._groupBy.push(this._escapeField($));return this}having($){if(typeof $==="string")this._having.push($);return this}limit($,J){if(typeof $!=="number"||$<0)throw Error(b.LIMIT_MUST_NON_NEGATIVE($));if(this._limit=Math.floor($),J!==void 0&&J!==null){if(typeof J!=="number"||J<0)throw Error(b.OFFSET_MUST_NON_NEGATIVE(J));this._offset=Math.floor(J)}return this}offset($){if(typeof $!=="number"||$<0)throw Error(b.OFFSET_COUNT_MUST_NON_NEGATIVE($));return this._offset=Math.floor($),this}toSelectSql(){let $="SELECT ";if($+=this._select.length>0?this._select.join(", "):"*",!this._from)throw Error(b.FROM_REQUIRED);if($+=` FROM ${this._from}`,this._joins.length>0)$+=" "+this._joins.join(" ");if(this._where.length>0)$+=" WHERE "+this._where.join(" AND ");if(this._groupBy.length>0)$+=" GROUP BY "+this._groupBy.join(", ");if(this._having.length>0)$+=" HAVING "+this._having.join(" AND ");if(this._orderBy.length>0)$+=" ORDER BY "+this._orderBy.join(", ");if(this._limit!==null){if($+=` LIMIT ${this._limit}`,this._offset!==null)$+=` OFFSET ${this._offset}`}return{sql:$,params:[...this._params]}}toInsertSql($,J){if(!$||typeof $!=="string")throw Error(b.INSERT_NEED_TABLE($));if(!J||typeof J!=="object")throw Error(b.INSERT_NEED_DATA($,J));let Z=this._escapeTable($);if(Array.isArray(J)){let X=c0.assertBatchInsertRowsConsistent(J,{table:$}),Y=X.map((K)=>this._escapeField(K)),H=X.map(()=>"?").join(", "),G=J.map(()=>`(${H})`).join(", "),U=`INSERT INTO ${Z} (${Y.join(", ")}) VALUES ${G}`,V=[];for(let K=0;K<J.length;K++){let F=J[K];for(let A of X)V.push(F[A])}return{sql:U,params:V}}else{let X=Object.keys(J);if(X.length===0)throw Error(b.INSERT_NEED_AT_LEAST_ONE_FIELD($));for(let V of X)this._validateParam(J[V]);let Y=X.map((V)=>this._escapeField(V)),H=X.map(()=>"?").join(", "),G=`INSERT INTO ${Z} (${Y.join(", ")}) VALUES (${H})`,U=X.map((V)=>J[V]);return{sql:G,params:U}}}toUpdateSql($,J){if(!$||typeof $!=="string")throw Error(b.UPDATE_NEED_TABLE);if(!J||typeof J!=="object"||Array.isArray(J))throw Error(b.UPDATE_NEED_OBJECT);let Z=Object.keys(J);if(Z.length===0)throw Error(b.UPDATE_NEED_AT_LEAST_ONE_FIELD);let X=this._escapeTable($),Y=Z.map((U)=>`${this._escapeField(U)} = ?`),H=[...Object.values(J),...this._params],G=`UPDATE ${X} SET ${Y.join(", ")}`;if(this._where.length>0)G+=" WHERE "+this._where.join(" AND ");else throw Error(b.UPDATE_NEED_WHERE);return{sql:G,params:H}}toDeleteSql($){if(!$||typeof $!=="string")throw Error(b.DELETE_NEED_TABLE);let Z=`DELETE FROM ${this._escapeTable($)}`;if(this._where.length>0)Z+=" WHERE "+this._where.join(" AND ");else throw Error(b.DELETE_NEED_WHERE);return{sql:Z,params:[...this._params]}}toCountSql(){let $="SELECT COUNT(*) as total";if(!this._from)throw Error(b.COUNT_NEED_FROM);if($+=` FROM ${this._from}`,this._joins.length>0)$+=" "+this._joins.join(" ");if(this._where.length>0)$+=" WHERE "+this._where.join(" AND ");return{sql:$,params:[...this._params]}}static toDeleteInSql($){if(typeof $.table!=="string"||!$.table.trim())throw Error(b.TO_DELETE_IN_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(b.TO_DELETE_IN_NEED_ID_FIELD($.idField));if(!Array.isArray($.ids))throw Error(b.TO_DELETE_IN_NEED_IDS);if($.ids.length===0)return{sql:"",params:[]};let J=$.ids.map(()=>"?").join(",");return{sql:`DELETE FROM ${$.quoteIdent($.table)} WHERE ${$.quoteIdent($.idField)} IN (${J})`,params:[...$.ids]}}static toUpdateCaseByIdSql($){if(typeof $.table!=="string"||!$.table.trim())throw Error(b.TO_UPDATE_CASE_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(b.TO_UPDATE_CASE_NEED_ID_FIELD($.idField));if(!Array.isArray($.rows))throw Error(b.TO_UPDATE_CASE_NEED_ROWS);if($.rows.length===0)return{sql:"",params:[]};if(!Array.isArray($.fields))throw Error(b.TO_UPDATE_CASE_NEED_FIELDS);if($.fields.length===0)return{sql:"",params:[]};let J=$.rows.map((U)=>U.id),Z=J.map(()=>"?").join(","),X=[],Y=[],H=$.quoteIdent($.idField);for(let U of $.fields){let V=[];for(let F of $.rows){if(!(U in F.data))continue;V.push("WHEN ? THEN ?"),Y.push(F.id),Y.push(F.data[U])}if(V.length===0)continue;let K=$.quoteIdent(U);X.push(`${K} = CASE ${H} ${V.join(" ")} ELSE ${K} END`)}X.push(`${$.quoteIdent($.updatedAtField)} = ?`),Y.push($.updatedAtValue);for(let U of J)Y.push(U);let G=`UPDATE ${$.quoteIdent($.table)} SET ${X.join(", ")} WHERE ${H} IN (${Z})`;if($.stateGtZero&&$.stateField)G+=` AND ${$.quoteIdent($.stateField)} > 0`;return{sql:G,params:Y}}}var rQ=3600;class uJ{redis;dialect;sql=null;isTransaction=!1;constructor($){this.redis=$.redis,this.sql=$.sql||null,this.isTransaction=!!$.sql,this.dialect=$.dialect?$.dialect:new vJ}createSqlBuilder(){return new b$({quoteIdent:this.dialect.quoteIdent.bind(this.dialect)})}async getTableColumns($){let J=X0.tableColumns($),Z=await this.redis.getObject(J);if(Z&&Z.length>0)return Z;let X=this.dialect.getTableColumnsQuery($),H=(await this.executeWithConn(X.sql,X.params)).data;if(!H||H.length===0)throw Error(`\u8868 ${$} \u4E0D\u5B58\u5728\u6216\u6CA1\u6709\u5B57\u6BB5`);let G=this.dialect.getTableColumnsFromResult(H);if(await this.redis.setObject(J,G,rQ)===null)P.warn({table:$,cacheKey:J},"\u8868\u5B57\u6BB5\u7F13\u5B58\u5199\u5165 Redis \u5931\u8D25");return G}async prepareQueryOptions($){let J=S$($.where||{},{excludeValues:[null,void 0]});if($.joins&&$.joins.length>0){let Y=($.fields||[]).map((U)=>h.processJoinField(U)),H=h.normalizeTableRef($.table),G=h.getJoinMainQualifier($.table);return{table:H,tableQualifier:G,fields:Y.length>0?Y:["*"],where:h.processJoinWhere(J),joins:$.joins,orderBy:h.processJoinOrderBy($.orderBy||[]),page:$.page||1,limit:$.limit||10}}let X=await h.fieldsToSnake(p($.table),$.fields||[],this.getTableColumns.bind(this));return{table:p($.table),tableQualifier:p($.table),fields:X,where:h.whereKeysToSnake(J),joins:void 0,orderBy:h.orderByToSnake($.orderBy||[]),page:$.page||1,limit:$.limit||10}}applyJoins($,J){if(!J||J.length===0)return;for(let Z of J){let X=h.normalizeTableRef(Z.table);switch(Z.type||"left"){case"inner":$.innerJoin(X,Z.on);break;case"right":$.rightJoin(X,Z.on);break;case"left":default:$.leftJoin(X,Z.on);break}}}async executeWithConn($,J){if(!this.sql)throw Error("\u6570\u636E\u5E93\u8FDE\u63A5\u672A\u521D\u59CB\u5316");if(typeof $!=="string")throw Error(`executeWithConn \u53EA\u63A5\u53D7\u5B57\u7B26\u4E32\u7C7B\u578B\u7684 SQL\uFF0C\u6536\u5230\u7C7B\u578B: ${typeof $}\uFF0C\u503C: ${JSON.stringify($)}`);let Z=Date.now(),X=Array.isArray(J)?J:[];try{let Y;if(X.length>0)Y=await this.sql.unsafe($,X);else Y=await this.sql.unsafe($);let H=Date.now()-Z;return{data:Y,sql:{sql:$,params:X,duration:H}}}catch(Y){let H=Date.now()-Z,G=Error(`SQL\u6267\u884C\u5931\u8D25: ${Y.message}`);throw G.originalError=Y,G.params=X,G.duration=H,G.sqlInfo={sql:$,params:X,duration:H},G}}async unsafe($,J){return await this.executeWithConn($,J)}async tableExists($){let J=p($),Z=this.dialect.tableExistsQuery(J),X=await this.executeWithConn(Z.sql,Z.params);return{data:(X.data?.[0]?.count||0)>0,sql:X.sql}}async getCount($){let{table:J,where:Z,joins:X,tableQualifier:Y}=await this.prepareQueryOptions($),H=this.createSqlBuilder().selectRaw("COUNT(*) as count").from(J).where(h.addDefaultStateFilter(Z,Y,!!X));this.applyJoins(H,X);let{sql:G,params:U}=H.toSelectSql(),V=await this.executeWithConn(G,U);return{data:V.data?.[0]?.count||0,sql:V.sql}}async getOne($){let{table:J,fields:Z,where:X,joins:Y,tableQualifier:H}=await this.prepareQueryOptions($),G=this.createSqlBuilder().select(Z).from(J).where(h.addDefaultStateFilter(X,H,!!Y));this.applyJoins(G,Y);let{sql:U,params:V}=G.toSelectSql(),K=await this.executeWithConn(U,V),A=K.data?.[0]||null;if(!A)return{data:null,sql:K.sql};let j=CZ(A),C=h.deserializeArrayFields(j);if(!C)return{data:null,sql:K.sql};return{data:pJ([C])[0],sql:K.sql}}async getList($){let J=await this.prepareQueryOptions($);if(J.page<1||J.page>1e4)throw Error(`\u9875\u7801\u5FC5\u987B\u5728 1 \u5230 10000 \u4E4B\u95F4 (table: ${$.table}, page: ${J.page}, limit: ${J.limit})`);if(J.limit<1||J.limit>1000)throw Error(`\u6BCF\u9875\u6570\u91CF\u5FC5\u987B\u5728 1 \u5230 1000 \u4E4B\u95F4 (table: ${$.table}, page: ${J.page}, limit: ${J.limit})`);let Z=h.addDefaultStateFilter(J.where,J.tableQualifier,!!J.joins),X=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(J.table).where(Z);this.applyJoins(X,J.joins);let{sql:Y,params:H}=X.toSelectSql(),G=await this.executeWithConn(Y,H),U=G.data?.[0]?.total||0;if(U===0)return{data:{lists:[],total:0,page:J.page,limit:J.limit,pages:0},sql:{count:G.sql}};let V=(J.page-1)*J.limit,K=this.createSqlBuilder().select(J.fields).from(J.table).where(Z).limit(J.limit).offset(V);if(this.applyJoins(K,J.joins),J.orderBy&&J.orderBy.length>0)K.orderBy(J.orderBy);let{sql:F,params:A}=K.toSelectSql(),j=await this.executeWithConn(F,A),C=j.data||[],E=SZ(C).map((T)=>h.deserializeArrayFields(T)).filter((T)=>T!==null);return{data:{lists:pJ(E),total:U,page:J.page,limit:J.limit,pages:Math.ceil(U/J.limit)},sql:{count:G.sql,data:j.sql}}}async getAll($){let X=await this.prepareQueryOptions({...$,page:1,limit:10}),Y=h.addDefaultStateFilter(X.where,X.tableQualifier,!!X.joins),H=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(X.table).where(Y);this.applyJoins(H,X.joins);let{sql:G,params:U}=H.toSelectSql(),V=await this.executeWithConn(G,U),K=V.data?.[0]?.total||0;if(K===0)return{data:{lists:[],total:0},sql:{count:V.sql}};let F=this.createSqlBuilder().select(X.fields).from(X.table).where(Y).limit(1e4);if(this.applyJoins(F,X.joins),X.orderBy&&X.orderBy.length>0)F.orderBy(X.orderBy);let{sql:A,params:j}=F.toSelectSql(),C=await this.executeWithConn(A,j),w=C.data||[];if(w.length>=1000)P.warn({table:$.table,count:w.length,total:K},"getAll \u8FD4\u56DE\u6570\u636E\u8FC7\u591A\uFF0C\u5EFA\u8BAE\u4F7F\u7528 getList \u5206\u9875\u67E5\u8BE2");if(w.length>=1e4)P.warn({table:$.table,limit:1e4,total:K},`getAll \u8FBE\u5230\u6700\u5927\u9650\u5236 ${1e4}\uFF0C\u5B9E\u9645\u603B\u6570 ${K}\uFF0C\u53EA\u8FD4\u56DE\u524D ${1e4} \u6761`);let T=SZ(w).map((L)=>h.deserializeArrayFields(L)).filter((L)=>L!==null);return{data:{lists:pJ(T),total:K},sql:{count:V.sql,data:C.sql}}}async insData($){let{table:J,data:Z}=$,X=p(J),Y=Date.now(),H;try{H=await this.redis.genTimeID()}catch(j){throw Error(`\u751F\u6210 ID \u5931\u8D25\uFF0CRedis \u53EF\u80FD\u4E0D\u53EF\u7528 (table: ${J})`,{cause:j})}let G=h.buildInsertRow({data:Z,id:H,now:Y});c0.assertNoUndefinedInRecord(G,`insData \u63D2\u5165\u6570\u636E (table: ${X})`);let U=this.createSqlBuilder(),{sql:V,params:K}=U.toInsertSql(X,G),F=await this.executeWithConn(V,K);return{data:G.id||F.data?.lastInsertRowid||0,sql:F.sql}}async insBatch($,J){if(J.length===0)return{data:[],sql:{sql:"",params:[],duration:0}};let Z=1000;if(J.length>Z)throw Error(`\u6279\u91CF\u63D2\u5165\u6570\u91CF ${J.length} \u8D85\u8FC7\u6700\u5927\u9650\u5236 ${Z}`);let X=p($),Y=[];for(let A=0;A<J.length;A++)Y.push(await this.redis.genTimeID());let H=Date.now(),G=J.map((A,j)=>{return h.buildInsertRow({data:A,id:Y[j],now:H})}),U=c0.assertBatchInsertRowsConsistent(G,{table:X}),V=this.createSqlBuilder(),{sql:K,params:F}=V.toInsertSql(X,G);try{let A=await this.executeWithConn(K,F);return{data:Y,sql:A.sql}}catch(A){throw P.error({err:A,table:$,snakeTable:X,count:J.length,fields:U},"\u6279\u91CF\u63D2\u5165\u5931\u8D25"),A}}async delForceBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=p($),X=b$.toDeleteInSql({table:Z,idField:"id",ids:J,quoteIdent:this.dialect.quoteIdent.bind(this.dialect)}),Y=await this.executeWithConn(X.sql,X.params);return{data:Y.data?.changes||0,sql:Y.sql}}async updBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=p($),X=Date.now(),Y=[],H=new Set;for(let F of J){let A=h.buildPartialUpdateData({data:F.data,allowState:!0});for(let j of Object.keys(A))H.add(j);Y.push({id:F.id,data:A})}let G=Array.from(H).sort();if(G.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let U=b$.toUpdateCaseByIdSql({table:Z,idField:"id",rows:Y,fields:G,quoteIdent:this.dialect.quoteIdent.bind(this.dialect),updatedAtField:"updated_at",updatedAtValue:X,stateField:"state",stateGtZero:!0}),V=await this.executeWithConn(U.sql,U.params);return{data:V.data?.changes||0,sql:V.sql}}async updData($){let{table:J,data:Z,where:X}=$,Y=S$(X,{excludeValues:[null,void 0]}),H=p(J),G=h.whereKeysToSnake(Y),U=h.buildUpdateRow({data:Z,now:Date.now(),allowState:!0}),V=h.addDefaultStateFilter(G,H,!1),K=this.createSqlBuilder().where(V),{sql:F,params:A}=K.toUpdateSql(H,U),j=await this.executeWithConn(F,A);return{data:j.data?.changes||0,sql:j.sql}}async delData($){let{table:J,where:Z}=$;return await this.updData({table:J,data:{state:0,deleted_at:Date.now()},where:Z})}async delForce($){let{table:J,where:Z}=$,X=p(J),Y=S$(Z,{excludeValues:[null,void 0]}),H=h.whereKeysToSnake(Y),G=this.createSqlBuilder().where(H),{sql:U,params:V}=G.toDeleteSql(X),K=await this.executeWithConn(U,V);return{data:K.data?.changes||0,sql:K.sql}}async disableData($){let{table:J,where:Z}=$;return await this.updData({table:J,data:{state:2},where:Z})}async enableData($){let{table:J,where:Z}=$;return await this.updData({table:J,data:{state:1},where:Z})}async trans($){if(this.isTransaction)return await $(this);return await this.sql.begin(async(J)=>{let Z=new uJ({redis:this.redis,sql:J,dialect:this.dialect});return await $(Z)})}async query($,J){return await this.executeWithConn($,J)}async exists($){let{table:J,where:Z,tableQualifier:X}=await this.prepareQueryOptions({...$,page:1,limit:1}),Y=this.createSqlBuilder().selectRaw("COUNT(1) as cnt").from(J).where(h.addDefaultStateFilter(Z,X,!1)).limit(1),{sql:H,params:G}=Y.toSelectSql(),U=await this.executeWithConn(H,G);return{data:(U.data?.[0]?.cnt||0)>0,sql:U.sql}}async getFieldValue($){let{field:J,...Z}=$;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u540D: ${J}\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF`);let X=await this.getOne({...Z,fields:[J]}),Y=X.data;if(!Y)return{data:null,sql:X.sql};if(J in Y)return{data:Y[J],sql:X.sql};let H=J.replace(/_([a-z])/g,(U,V)=>V.toUpperCase());if(H!==J&&H in Y)return{data:Y[H],sql:X.sql};let G=J.replace(/[A-Z]/g,(U)=>`_${U.toLowerCase()}`);if(G!==J&&G in Y)return{data:Y[G],sql:X.sql};return{data:null,sql:X.sql}}async increment($,J,Z,X=1){let Y=p($),H=p(J);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(Y))throw Error(`\u65E0\u6548\u7684\u8868\u540D: ${Y}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(H))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u540D: ${J}`);if(typeof X!=="number"||isNaN(X))throw Error(`\u81EA\u589E\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57 (table: ${$}, field: ${J}, value: ${X})`);let G=S$(Z,{excludeValues:[null,void 0]}),U=h.whereKeysToSnake(G),V=h.addDefaultStateFilter(U,Y,!1),K=this.createSqlBuilder().where(V),{sql:F,params:A}=K.getWhereConditions(),j=this.dialect.quoteIdent(Y),C=this.dialect.quoteIdent(H),w=F?`UPDATE ${j} SET ${C} = ${C} + ? WHERE ${F}`:`UPDATE ${j} SET ${C} = ${C} + ?`,E=await this.executeWithConn(w,[X,...A]);return{data:E.data?.changes||0,sql:E.sql}}async decrement($,J,Z,X=1){return await this.increment($,J,Z,-X)}}a();var eY={name:"db",enable:!0,deps:["logger","redis"],async handler($){if(!$.redis)throw Error("\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25\uFF1Actx.redis \u672A\u521D\u59CB\u5316\uFF08Redis \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");try{let J=H$.getSql(),Z=$.config&&$.config.db?$.config.db.type:void 0,X=Z==="postgres"?"postgresql":Z,Y=h$(X==="postgresql"||X==="sqlite"?X:"mysql");return new uJ({redis:$.redis,sql:J,dialect:Y})}catch(J){throw P.error({err:J},"\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25"),J}}};var L$=ZG(uW(),1);class bX{config;constructor($={}){this.config={secret:$.secret||"befly-secret",expiresIn:$.expiresIn||"7d",algorithm:$.algorithm||"HS256"}}sign($,J={}){let Z=J.secret||this.config.secret||"befly-secret",X=J.algorithm||this.config.algorithm||"HS256";return L$.createSigner({key:Z,algorithm:X,expiresIn:J.expiresIn||this.config.expiresIn,iss:J.issuer,aud:J.audience,sub:J.subject,jti:J.jwtId,notBefore:typeof J.notBefore==="number"?J.notBefore:void 0})($)}verify($,J={}){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let Z=J.secret||this.config.secret||"befly-secret",X=this.config.algorithm||"HS256",Y=J.algorithms?J.algorithms:[X];return L$.createVerifier({key:Z,algorithms:Y,allowedIss:J.issuer,allowedAud:J.audience,allowedSub:J.subject,ignoreExpiration:J.ignoreExpiration,ignoreNotBefore:J.ignoreNotBefore,cache:!0,cacheTTL:600000})($)}decode($,J=!1){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(J){let Y=L$.createDecoder({complete:!0})($);return{header:Y.header,payload:Y.payload,signature:Y.signature}}return L$.createDecoder()($)}}var mW={name:"jwt",enable:!0,deps:[],handler:($)=>{return new bX($.config?$.config.auth:void 0)}};a();var dW={name:"logger",enable:!0,deps:[],async handler($){if($.config&&$.config.logger)P.configure($.config.logger);return P}};a();a();class cX{client;prefix;slowThresholdMs=500;constructor($=""){let J=H$.getRedis();if(!J)throw Error("Redis \u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 Connect.connectRedis()");this.client=J,this.prefix=$?`${$}:`:""}logSlow($,J,Z,X={}){if(Z<=this.slowThresholdMs)return;P.warn({subsystem:"redis",event:"slow",duration:Z,cmd:$,key:J,extra:X},"\uD83D\uDC0C Redis \u6162\u64CD\u4F5C")}async setObject($,J,Z=null){try{let X=JSON.stringify(J),Y=`${this.prefix}${$}`,H=Date.now();if(Z){let V=await this.client.setex(Y,Z,X),K=Date.now()-H;return this.logSlow("SETEX",Y,K,{ttl:Z}),V}let G=await this.client.set(Y,X),U=Date.now()-H;return this.logSlow("SET",Y,U),G}catch(X){return P.error({err:X},"Redis setObject \u9519\u8BEF"),null}}async getObject($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.get(J),Y=Date.now()-Z;return this.logSlow("GET",J,Y),X?JSON.parse(X):null}catch(J){return P.error({err:J},"Redis getObject \u9519\u8BEF"),null}}async delObject($){try{let J=`${this.prefix}${$}`,Z=Date.now();await this.client.del(J);let X=Date.now()-Z;this.logSlow("DEL",J,X)}catch(J){P.error({err:J},"Redis delObject \u9519\u8BEF")}}async genTimeID(){let $=Date.now(),J=`${this.prefix}time_id:${$}`,Z=Date.now(),X=await this.client.incr(J);if(X===1)await this.client.expire(J,1);let Y=Date.now()-Z;this.logSlow("INCR",J,Y,{expireSeconds:1});let H=100+($%900+X-1)%900;return Number(`${$}${H}`)}async setString($,J,Z=null){try{let X=`${this.prefix}${$}`,Y=Date.now();if(Z){let U=await this.client.setex(X,Z,J),V=Date.now()-Y;return this.logSlow("SETEX",X,V,{ttl:Z}),U}let H=await this.client.set(X,J),G=Date.now()-Y;return this.logSlow("SET",X,G),H}catch(X){return P.error({err:X},"Redis setString \u9519\u8BEF"),null}}async getString($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.get(J),Y=Date.now()-Z;return this.logSlow("GET",J,Y),X}catch(J){return P.error({err:J},"Redis getString \u9519\u8BEF"),null}}async exists($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.exists(J),Y=Date.now()-Z;return this.logSlow("EXISTS",J,Y),X}catch(J){return P.error({err:J},"Redis exists \u9519\u8BEF"),!1}}async incr($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.incr(J),Y=Date.now()-Z;return this.logSlow("INCR",J,Y),X}catch(J){return P.error({err:J},"Redis incr \u9519\u8BEF"),0}}async incrWithExpire($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),Y=await this.client.incr(Z);if(Y===1)await this.client.expire(Z,J);let H=Date.now()-X;return this.logSlow("INCR",Z,H,{expireSeconds:J}),Y}catch(Z){return P.error({err:Z},"Redis incrWithExpire \u9519\u8BEF"),0}}async expire($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),Y=await this.client.expire(Z,J),H=Date.now()-X;return this.logSlow("EXPIRE",Z,H,{seconds:J}),Y}catch(Z){return P.error({err:Z},"Redis expire \u9519\u8BEF"),0}}async ttl($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.ttl(J),Y=Date.now()-Z;return this.logSlow("TTL",J,Y),X}catch(J){return P.error({err:J},"Redis ttl \u9519\u8BEF"),-1}}async ttlBatch($){if($.length===0)return[];try{return await Promise.all($.map((Z)=>this.ttl(Z)))}catch(J){return P.error({err:J},"Redis ttlBatch \u9519\u8BEF"),$.map(()=>-1)}}async sadd($,J){try{if(J.length===0)return 0;let Z=`${this.prefix}${$}`,X=Date.now(),Y=await this.client.sadd(Z,...J),H=Date.now()-X;return this.logSlow("SADD",Z,H,{membersCount:J.length}),Y}catch(Z){return P.error({err:Z},"Redis sadd \u9519\u8BEF"),0}}async sismember($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),Y=await this.client.sismember(Z,J),H=Date.now()-X;return this.logSlow("SISMEMBER",Z,H),Y}catch(Z){return P.error({err:Z},"Redis sismember \u9519\u8BEF"),!1}}async scard($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.scard(J),Y=Date.now()-Z;return this.logSlow("SCARD",J,Y),X}catch(J){return P.error({err:J},"Redis scard \u9519\u8BEF"),0}}async smembers($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.smembers(J),Y=Date.now()-Z;return this.logSlow("SMEMBERS",J,Y),X}catch(J){return P.error({err:J},"Redis smembers \u9519\u8BEF"),[]}}async saddBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>this.sadd(Z.key,Z.members)))).reduce((Z,X)=>Z+X,0)}catch(J){return P.error({err:J},"Redis saddBatch \u9519\u8BEF"),0}}async sismemberBatch($){if($.length===0)return[];try{return await Promise.all($.map((J)=>this.sismember(J.key,J.member)))}catch(J){return P.error({err:J},"Redis sismemberBatch \u9519\u8BEF"),$.map(()=>!1)}}async del($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.del(J),Y=Date.now()-Z;return this.logSlow("DEL",J,Y),X}catch(J){return P.error({err:J},"Redis del \u9519\u8BEF"),0}}async delBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>{let X=`${this.prefix}${Z}`;return this.client.del(X)}))).reduce((Z,X)=>Z+X,0)}catch(J){return P.error({err:J},"Redis delBatch \u9519\u8BEF"),0}}async setBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>this.setObject(Z.key,Z.value,Z.ttl??null)))).filter((Z)=>Z!==null).length}catch(J){return P.error({err:J},"Redis setBatch \u9519\u8BEF"),0}}async getBatch($){if($.length===0)return[];try{return await Promise.all($.map((Z)=>this.getObject(Z)))}catch(J){return P.error({err:J},"Redis getBatch \u9519\u8BEF"),$.map(()=>null)}}async existsBatch($){if($.length===0)return[];try{return await Promise.all($.map((J)=>this.exists(J)))}catch(J){return P.error({err:J},"Redis existsBatch \u9519\u8BEF"),$.map(()=>!1)}}async expireBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>this.expire(Z.key,Z.seconds)))).filter((Z)=>Z>0).length}catch(J){return P.error({err:J},"Redis expireBatch \u9519\u8BEF"),0}}async ping(){try{let $=Date.now(),J=await this.client.ping(),Z=Date.now()-$;return this.logSlow("PING","(no-key)",Z),J}catch($){throw P.error({err:$},"Redis ping \u9519\u8BEF"),$}}}var nW={name:"redis",enable:!0,deps:["logger"],async handler($){let J=$.config&&$.config.redis?$.config.redis:{};try{return H$.getRedis(),new cX(J.prefix)}catch(Z){throw P.error({err:Z},"Redis \u521D\u59CB\u5316\u5931\u8D25"),Z}}};function A8($,J={},Z={}){return{code:0,msg:$,data:J,...Z}}function R8($,J=null,Z={}){return{code:1,msg:$,data:J,...Z}}function M8($,J,Z={}){let{status:X=200,contentType:Y,headers:H={}}=Z,G=Y,U;if(typeof J==="string"){if(U=J,!G)G=J.trim().startsWith("<")?"application/xml":"text/plain"}else U=JSON.stringify(J),G=G||"application/json";let V={...$.corsHeaders,"Content-Type":G,...H};return new Response(U,{status:X,headers:V})}var oW={name:"tool",enable:!0,deps:[],handler:()=>{return{Yes:A8,No:R8,Raw:M8}}};function sW($,J){let Z=J.name;return{source:"core",type:$,sourceName:"\u6838\u5FC3",filePath:`core:${$}:${Z}`,relativePath:Z,fileName:Z,moduleName:Z,addonName:"",fileBaseName:Z,fileDir:"(builtin)",name:Z,enable:J?J.enable:void 0,deps:Array.isArray(J&&J.deps)?J.deps:[],handler:J?J.handler:null}}function lW(){let $=[],J=[dW,nW,eY,iY,oW,tY,mW,aY];for(let Z of J)$.push(sW("plugin",Z));return $}function rW(){let $=[],J=[yY,fY,nY,rY,oY];for(let Z of J)$.push(sW("hook",Z));return $}A$();import{existsSync as I8}from"fs";a();async function iW($,J){try{let X=(await import($))?.default;if(X===null||X===void 0)return J;return X}catch(Z){return P.warn({err:Z,file:$},"importDefault \u5BFC\u5165\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C"),J}}function q8($){let J=$.split("/").filter(Boolean),Z=J.indexOf("@befly-addon");if(Z<0)return null;let X=J[Z+1];if(typeof X!=="string"||X.trim()==="")return null;return X}function P8($){let J=$.split("/").filter(Boolean),Z=J.lastIndexOf("addons");if(Z<0)return null;let X=J[Z+1];if(typeof X!=="string"||X.trim()==="")return null;return X}async function U$($,J,Z,X){if(!I8($))return[];let Y=P$($),H=new Bun.Glob(X),G=[];try{let U=await H.scan({cwd:$,onlyFiles:!0,absolute:!0,followSymlinks:!0});for await(let V of U){if(V.endsWith(".d.ts"))continue;let K=P$(V),F=XJ(K).name,A=dZ(Y,K),j=XJ(A),C=j.dir?n(j.dir,j.name):j.name;if(F.startsWith("_"))continue;if(C.split("/").some((D)=>D.startsWith("_")))continue;let w=await iW(K,{}),E=O$(F),T="",v="";if(J==="core")T="",v=F;else if(J==="app")v=`app_${E}`;else{let D=q8(K)||P8(K);if(!D)throw Error(`scanFiles addon moduleName \u89E3\u6790\u5931\u8D25\uFF1A\u672A\u627E\u5230 @befly-addon/<addon>/ \u6BB5\u843D\uFF1A${K}`);T=D,v=`addon_${O$(T)}_${E}`}let L={source:J,type:Z,sourceName:{core:"\u6838\u5FC3",addon:"\u7EC4\u4EF6",app:"\u9879\u76EE"}[J],filePath:K,relativePath:C,fileName:F,moduleName:v,addonName:T,fileBaseName:XJ(K).base,fileDir:$};if(Z==="table"){L.content=w,G.push(L);continue}if(Z==="api")L.auth=!0,L.rawBody=!1,L.method="POST",L.fields={},L.required=[];if(Z==="plugin"||Z==="hook")L.deps=[],L.name="",L.handler=null;if(W1(w,(D,g)=>{L[g]=D}),Z==="api")L.routePrefix=J==="app"?"/app":`/addon/${T}`,L.routePath=`/api${L.routePrefix}/${C}`;G.push(L)}}catch(U){let V=Error(`scanFiles failed: source=${J} type=${Z} dir=${Y} pattern=${X}`);throw V.cause=U,V}return G}var tW=async()=>{let $=[],J=[],Z=[],X=[],Y=await xY();X.push(...await U$(n(d0,"tables"),"app","table","*.json"));for(let H of Y)X.push(...await U$(n(H.fullPath,"tables"),"addon","table","*.json"));J.push(...lW()),J.push(...await U$(n(d0,"plugins"),"app","plugin","*.{ts,js}"));for(let H of Y)J.push(...await U$(n(H.fullPath,"plugins"),"addon","plugin","*.{ts,js}"));Z.push(...rW()),Z.push(...await U$(n(d0,"hooks"),"app","hook","*.{ts,js}"));for(let H of Y)Z.push(...await U$(n(H.fullPath,"hooks"),"addon","hook","*.{ts,js}"));$.push(...await U$(n(d0,"apis"),"app","api","**/*.{ts,js}"));for(let H of Y)$.push(...await U$(n(H.fullPath,"apis"),"addon","api","**/*.{ts,js}"));return{hooks:Z,plugins:J,apis:$,tables:X,addons:Y}};class B8{apis=new Map;plugins=[];hooks=[];context={};config=null;async start(){try{let $=Bun.nanoseconds();this.config=await O1(),this.context.config=this.config;let{apis:J,tables:Z,plugins:X,hooks:Y,addons:H}=await tW();this.context.addons=H,await g1(J),await ZY(Z),await t1(X),await b1(Y);let G=await i1(H,{disableMenus:this.config.disableMenus||[]});if(await H$.connect({db:this.config.db||{},redis:this.config.redis||{}}),this.plugins=await GY(X,this.context),!this.context.redis)throw Error("\u542F\u52A8\u5931\u8D25\uFF1Actx.redis \u672A\u521D\u59CB\u5316\uFF08Redis \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!this.context.db)throw Error("\u542F\u52A8\u5931\u8D25\uFF1Actx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!this.context.cache)throw Error("\u542F\u52A8\u5931\u8D25\uFF1Actx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");await kJ(this.context,Z),await KY(this.context,J),await FY(this.context,G),await _Y(this.context,{devEmail:this.config.devEmail,devPassword:this.config.devPassword}),await OY(this.context),this.hooks=await WY(Y),this.apis=await HY(J);let U=zY(this.apis,this.hooks,this.context),V=VY(this.config.cors),K=Bun.serve({port:this.config.appPort,hostname:this.config.appHost,development:this.config.nodeEnv==="development",idleTimeout:30,fetch:async(E,T)=>{let v=new URL(E.url);if(v.pathname==="/")return Response.json({code:0,msg:`${this.config.appName} \u63A5\u53E3\u670D\u52A1\u5DF2\u542F\u52A8`});if(v.pathname.startsWith("/api/"))return U(E,T);return V(E)},error:(E)=>{if(P.error({err:E},"\u670D\u52A1\u542F\u52A8\u65F6\u53D1\u751F\u9519\u8BEF"),this.config.nodeEnv==="development")return Response.json({code:1,msg:"\u5185\u90E8\u670D\u52A1\u5668\u9519\u8BEF",error:E.message,stack:E.stack},{status:200});return Response.json({code:1,msg:"\u5185\u90E8\u670D\u52A1\u5668\u9519\u8BEF"},{status:200})}}),F=DY($),A=kY(),j=A.role==="primary"?"\u4E3B\u8FDB\u7A0B":`\u5DE5\u4F5C\u8FDB\u7A0B #${A.instanceId}`,C=A.env==="standalone"?"":` [${A.env}]`;P.info(`${this.config.appName} \u542F\u52A8\u6210\u529F! (${j}${C})`),P.info(`\u670D\u52A1\u5668\u542F\u52A8\u8017\u65F6: ${F}`),P.info(`\u670D\u52A1\u5668\u76D1\u542C\u5730\u5740: ${K.url}`);let w=async(E)=>{P.info(`\u6536\u5230 ${E} \u4FE1\u53F7\uFF0C\u5F00\u59CB\u4F18\u96C5\u5173\u95ED...`);try{await K.stop(),P.info("HTTP \u670D\u52A1\u5668\u5DF2\u505C\u6B62")}catch(T){P.error({err:T},"\u505C\u6B62 HTTP \u670D\u52A1\u5668\u65F6\u51FA\u9519")}try{await H$.disconnect(),P.info("\u6570\u636E\u5E93\u8FDE\u63A5\u5DF2\u5173\u95ED")}catch(T){P.error({err:T},"\u5173\u95ED\u6570\u636E\u5E93\u8FDE\u63A5\u65F6\u51FA\u9519")}P.info("\u670D\u52A1\u5668\u5DF2\u4F18\u96C5\u5173\u95ED"),process.exit(0)};return process.on("SIGTERM",()=>w("SIGTERM")),process.on("SIGINT",()=>w("SIGINT")),K}catch($){P.error({err:$},"\u9879\u76EE\u542F\u52A8\u5931\u8D25"),process.exit(1)}}}export{B8 as Befly};
|