befly 3.14.1 → 3.14.2

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/dist/befly.min.js CHANGED
@@ -1,18 +1,18 @@
1
1
  // @bun
2
- var LW=Object.create;var{getPrototypeOf:SW,defineProperty:dX,getOwnPropertyNames:CW}=Object;var wW=Object.prototype.hasOwnProperty;var EW=($,J,Z)=>{Z=$!=null?LW(SW($)):{};let X=J||!$||!$.__esModule?dX(Z,"default",{value:$,enumerable:!0}):Z;for(let G of CW($))if(!wW.call(X,G))dX(X,G,{get:()=>$[G],enumerable:!0});return X};var s=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var z$=($,J)=>()=>($&&(J=$($=0)),J);var M$=import.meta.require;function AZ($,J="dateTime"){let Z=$.getFullYear(),X=$.getMonth()+1,G=$.getDate(),Y=$.getHours(),H=$.getMinutes(),z=$.getSeconds(),V=X<10?`0${X}`:String(X),O=G<10?`0${G}`:String(G),_=Y<10?`0${Y}`:String(Y),I=H<10?`0${H}`:String(H),B=z<10?`0${z}`:String(z);if(J==="date")return`${Z}-${V}-${O}`;if(J==="time")return`${_}:${I}:${B}`;return`${Z}-${V}-${O} ${_}:${I}:${B}`}function i($){if(typeof $!=="object"||$===null)return!1;let J=Object.getPrototypeOf($);return J===Object.prototype||J===null}function FZ($){if($===null)return"null";if($===void 0)return"undefined";if(Array.isArray($))return"array";let J=typeof $;if(J==="string")return"string";if(J==="number")return"number";if(J==="boolean")return"boolean";if(J==="bigint")return"bigint";if(J==="symbol")return"symbol";if(J==="function")return"function";return"object"}function D$($,J,Z,X){if(typeof $!=="number")return J;if(!Number.isFinite($))return J;let G=Math.floor($);if(G<Z)return J;if(G>X)return X;return G}function sX($,J){if(typeof J!=="function")return;if(!i($))return;for(let Z of Object.keys($))J($[Z],Z)}function NW($){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 vW($){if($.length===0)return $;return $.charAt(0).toUpperCase()+$.slice(1)}function _$($){let J=NW($);if(J.length===0)return"";let Z=J[0];if(!Z)return"";let X=Z.toLowerCase(),G=J.slice(1).map((Y)=>vW(Y.toLowerCase()));return[X].concat(G).join("")}function DW($){return String($).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").trim()}function f($){let J=DW($);if(J.length===0)return"";return J.split(/\s+/).filter((Z)=>Z.length>0).map((Z)=>Z.toLowerCase()).join("_")}function c($,J){if(!i($))return{};let Z=new Set(Array.isArray(J)?J:[]),X={};for(let[G,Y]of Object.entries($)){if(Z.has(G))continue;X[G]=Y}return X}function lX($,J){let Z={};if(!Array.isArray($)||typeof J!=="function")return Z;for(let X of $){let G=J(X);if(typeof G!=="string"||G==="")continue;Z[G]=X}return Z}function rX(){return Date.now().toString(36)+Math.random().toString(36).slice(2,7)}var RZ=($)=>{if(!$||!i($))return $;let J={};for(let[Z,X]of Object.entries($)){let G=_$(Z);J[G]=X}return J},oX=($)=>{if(!$||!i($))return $;let J={};for(let[Z,X]of Object.entries($)){let G=f(Z);J[G]=X}return J},IZ=($)=>{if(!$||!Array.isArray($))return $;return $.map((J)=>RZ(J))};var n0=()=>{};function PZ($){let J=[];for(let G of $.builtinPatterns){let Y=String(G).trim();if(Y.length>0)J.push(Y.toLowerCase())}if(Array.isArray($.userPatterns))for(let G of $.userPatterns){let Y=String(G).trim();if(Y.length>0)J.push(Y.toLowerCase())}let Z=new Set,X=[];for(let G of J){if(!G.includes("*")){Z.add(G);continue}let Y=G.replace(/\*+/g,"").trim();if(!Y)continue;X.push(Y)}return{exactSet:Z,contains:X}}function BZ($,J){let Z=String($).toLowerCase();if(J.exactSet.has(Z))return!0;for(let X of J.contains)if(Z.includes(X))return!0;return!1}function VJ($,J){if($.length<=J)return $;return $.slice(0,J)}function iX($,J){let Z={name:$.name||"Error",message:VJ($.message||"",J.maxStringLen)};if(typeof $.stack==="string")Z.stack=VJ($.stack,J.maxStringLen);return Z}function kW($,J,Z){if(typeof $==="string")return $;if($ instanceof Error)try{return JSON.stringify(iX($,J))}catch{return`${$.name||"Error"}: ${$.message||""}`}if($&&typeof $==="object"){if(Z.has($))return"[Circular]"}try{let X=Z;return JSON.stringify($,(Y,H)=>{if(Y&&BZ(Y,J.sensitiveKeyMatcher))return"[MASKED]";if(H&&typeof H==="object"){if(X.has(H))return"[Circular]";X.add(H)}return H})}catch{try{return String($)}catch{return"[Unserializable]"}}}function qZ($,J,Z){let X=kW($,J,Z);return VJ(X,J.maxStringLen)}function jZ($,J,Z,X,G){if($===null||$===void 0)return $;if(typeof $==="string")return VJ($,J.maxStringLen);if(typeof $==="number"||typeof $==="boolean"||typeof $==="bigint")return $;if($ instanceof Error)return iX($,J);let Y=Array.isArray($),H=i($);if(!Y&&!H)return qZ($,J,G);if(G.has($))return"[Circular]";if(X>=J.sanitizeDepth)return qZ($,J,G);if(Z.nodes>=J.sanitizeNodes)return qZ($,J,G);if(G.add($),Z.nodes=Z.nodes+1,Y){let I=$,B=[],S=I.length>J.maxArrayItems?J.maxArrayItems:I.length;for(let C=0;C<S;C++)B[C]=jZ(I[C],J,Z,X+1,G);return B}let z=$,V={},O=Object.entries(z),_=O.length>J.sanitizeObjectKeys?J.sanitizeObjectKeys:O.length;for(let I=0;I<_;I++){let B=O[I];if(!B)continue;let S=B[0],C=B[1];if(BZ(S,J.sensitiveKeyMatcher)){V[S]="[MASKED]";continue}V[S]=jZ(C,J,Z,X+1,G)}return V}function LZ($,J){let Z=new WeakSet,X={nodes:0},G={};for(let[Y,H]of Object.entries($)){if(BZ(Y,J.sensitiveKeyMatcher)){G[Y]="[MASKED]";continue}G[Y]=jZ(H,J,X,0,Z)}return G}var tX=z$(()=>{n0()});import{AsyncLocalStorage as xW}from"async_hooks";function aX($,J){return SZ.run($,J)}function eX(){let $=SZ.getStore();if(!$)return null;return $}function $G($,J,Z,X){let G=SZ.getStore();if(!G)return;G.userId=$===void 0?null:$,G.roleCode=J===void 0?null:J,G.nickname=Z===void 0?null:Z,G.roleType=X===void 0?null:X}var SZ;var OJ=z$(()=>{SZ=new xW});import{createWriteStream as yW,existsSync as fW,mkdirSync as gW}from"fs";import{stat as hW}from"fs/promises";import{hostname as bW}from"os";import{isAbsolute as cW,join as pW,resolve as uW}from"path";function _J($){try{process.stderr.write(`${$}
3
- `)}catch{}}function dW($,J){let Z=[],X=0;while($.length>0){let G=$[0],Y=Buffer.byteLength(G);if(Z.length>0&&X+Y>J)break;Z.push(G),X=X+Y,$.shift()}return{chunk:Z.join(""),bytes:X}}class EZ{pending;pendingBytes;scheduledTimer;flushing;maxBufferBytes;flushDelayMs;maxBatchBytes;writeChunk;onShutdown;constructor($){this.pending=[],this.pendingBytes=0,this.scheduledTimer=null,this.flushing=!1,this.maxBufferBytes=$.maxBufferBytes,this.flushDelayMs=$.flushDelayMs,this.maxBatchBytes=$.maxBatchBytes,this.writeChunk=$.writeChunk,this.onShutdown=$.onShutdown?$.onShutdown:null}scheduleFlush(){if(this.scheduledTimer)return;this.scheduledTimer=setTimeout(()=>{this.scheduledTimer=null,this.flush()},this.flushDelayMs)}cancelScheduledFlush(){if(!this.scheduledTimer)return;clearTimeout(this.scheduledTimer),this.scheduledTimer=null}enqueue($){let J=Buffer.byteLength($);if(this.pendingBytes+J>this.maxBufferBytes)return;this.pending.push($),this.pendingBytes=this.pendingBytes+J,this.scheduleFlush()}async flushNow(){this.cancelScheduledFlush(),await this.flush()}async shutdown(){if(this.cancelScheduledFlush(),await this.flush(),this.onShutdown)await this.onShutdown()}async flush(){if(this.flushing)return;this.flushing=!0;try{while(this.pending.length>0){let J=dW(this.pending,this.maxBatchBytes).chunk,Z=Buffer.byteLength(J);if(this.pendingBytes=this.pendingBytes-Z,!await this.writeChunk(J,Z)){this.pending=[],this.pendingBytes=0;break}}}finally{if(this.flushing=!1,this.pending.length>0)this.scheduleFlush()}}}function sW($){let J=()=>{return $==="stderr"?process.stderr:process.stdout},Z=new EZ({maxBufferBytes:10485760,flushDelayMs:10,maxBatchBytes:65536,writeChunk:async(X)=>{try{let G=J();if(!G.write(X))await new Promise((H)=>{G.once("drain",()=>H())});return!0}catch(G){return _J(`[Logger] stream sink error: ${G?.message||G}`),!1}}});return{enqueue(X){Z.enqueue(X)},async flushNow(){await Z.flushNow()},async shutdown(){await Z.shutdown()}}}class CZ{prefix;maxFileBytes;buffer;stream;streamDate;streamIndex;streamSizeBytes;disabled;constructor($){this.prefix=$.prefix,this.maxFileBytes=$.maxFileBytes,this.stream=null,this.streamDate="",this.streamIndex=0,this.streamSizeBytes=0,this.disabled=!1,this.buffer=new EZ({maxBufferBytes:10485760,flushDelayMs:10,maxBatchBytes:65536,writeChunk:async(J,Z)=>{if(this.disabled)return!1;try{if(await this.ensureStreamReady(Z),!this.stream)return!1;if(!this.stream.write(J))await new Promise((G)=>{this.stream.once("drain",()=>G())});return this.streamSizeBytes=this.streamSizeBytes+Z,!0}catch(X){return _J(`[Logger] file sink flush error (${this.prefix}): ${X?.message||X}`),this.disabled=!0,await this.closeStream(),!1}},onShutdown:async()=>{await this.closeStream()}})}enqueue($){if(this.disabled)return;this.buffer.enqueue($)}async flushNow(){await this.buffer.flushNow()}async shutdown(){await this.buffer.shutdown()}async closeStream(){if(!this.stream)return;let $=this.stream;this.stream=null,await new Promise((J)=>{try{$.end(()=>J())}catch{J()}})}openStream($){try{this.stream=yW($,{flags:"a"}),this.stream.on("error",(J)=>{_J(`[Logger] file sink error (${this.prefix}): ${J?.message||J}`),this.disabled=!0,this.closeStream()})}catch(J){_J(`[Logger] createWriteStream failed (${this.prefix}): ${J?.message||J}`),this.disabled=!0,this.stream=null}}getFilePath($,J){let Z=J>0?`.${J}`:"",X=`${this.prefix}.${$}${Z}.log`;return pW(YG(),X)}async ensureStreamReady($){let J=AZ(new Date,"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 G=await hW(Z);X=typeof G.size==="number"?G.size:0}catch{X=0}if(this.streamDate=J,this.streamIndex=0,this.streamSizeBytes=X,this.openStream(Z),!this.stream)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);if(this.streamDate=J,this.streamSizeBytes=0,this.openStream(Z),!this.stream)return}}}async function oW(){if(L$)return;let $=[];if(X$)$.push({flush:()=>X$?X$.flushNow():Promise.resolve()});if(G$)$.push({flush:()=>G$?G$.flushNow():Promise.resolve()});if(Y$)$.push({flush:()=>Y$?Y$.flushNow():Promise.resolve()});for(let J of $)try{await J.flush()}catch{}}async function GG(){if(L$)return;let $=A$,J=F$,Z=X$,X=G$,G=Y$,Y=[];if(Z)Y.push({shutdown:()=>Z.shutdown()});if(X)Y.push({shutdown:()=>X.shutdown()});if(G)Y.push({shutdown:()=>G.shutdown()});for(let H of Y)try{await H.shutdown()}catch{}if(X$===Z)X$=null;if(G$===X)G$=null;if(Y$===G)Y$=null;if(A$===$)A$=null;if(F$===J)F$=null}function YG(){let $=m0.dir||"./logs";if(cW($))return $;return uW(nW,$)}function lW(){let $=YG();try{if(!fW($))gW($,{recursive:!0})}catch(J){throw Error(`\u521B\u5EFA logs \u76EE\u5F55\u5931\u8D25: ${$}. ${J?.message||J}`)}}function rW($){GG(),m0=Object.assign({debug:0,dir:"./logs",console:1,maxSize:20},$);{let J=m0.maxSize,Z=typeof J==="number"&&Number.isFinite(J)?J:20;if(Z<10)Z=10;if(Z>100)Z=100;m0.maxSize=Z}A$=null,F$=null,X$=null,G$=null,Y$=null,wZ={maxStringLen:D$(m0.maxStringLen,100,20,200000),maxArrayItems:D$(m0.maxArrayItems,100,10,5000),sanitizeDepth:D$(m0.sanitizeDepth,3,1,10),sanitizeNodes:D$(m0.sanitizeNodes,500,50,20000),sanitizeObjectKeys:D$(m0.sanitizeObjectKeys,100,10,5000),sensitiveKeyMatcher:PZ({builtinPatterns:XG,userPatterns:m0.excludeFields})}}function iW($){L$=$}function t$($){if(L$)return L$;if($==="app"){if(A$)return A$}else if(F$)return F$;lW();let J=typeof m0.maxSize==="number"?m0.maxSize:20,Z=Math.floor(J*1024*1024);if($==="app"){if(!X$)X$=new CZ({prefix:"app",maxFileBytes:Z});if(m0.console===1&&!Y$)Y$=sW("stdout");return A$=ZG({fileSink:X$,consoleSink:m0.console===1?Y$:null}),A$}if(!G$)G$=new CZ({prefix:"error",maxFileBytes:Z});return F$=ZG({fileSink:G$,consoleSink:null}),F$}function tW($,J){let Z=Date.now(),X={level:$,time:Z,timeFormat:AZ(new Date(Z)),pid:process.pid,hostname:mW};if(J&&i(J)){let G=Object.assign({},J,X);if(J.msg!==void 0)G.msg=J.msg;else if(G.msg===void 0)G.msg="";return`${JG(G)}
4
- `}if(X.msg===void 0)X.msg="";return`${JG(X)}
5
- `}function JG($){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 ZG($){let{fileSink:J,consoleSink:Z}=$,X=(G,Y)=>{if(G==="debug"&&m0.debug!==1)return;let H=LZ(Y,wZ),z=tW(G,H);if(J.enqueue(z),Z)Z.enqueue(z)};return{info(G){X("info",G)},warn(G){X("warn",G)},error(G){X("error",G)},debug(G){X("debug",G)}}}function aW(){let $=eX();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 eW($,J){let Z={};for(let[G,Y]of Object.entries($))Z[G]=Y;let X=["requestId","method","route","ip","now","durationSinceNowMs","userId","roleCode","nickname","roleType"];for(let G of X)if(Z[G]===void 0)Z[G]=J[G];return Z}function KJ($){if(i($))return $;if($ instanceof Error)return{err:$,msg:$.message||$.name||"Error"};if($===void 0)return{msg:""};if($===null)return{msg:"null"};if(typeof $==="object")return{value:$};try{return{msg:String($)}}catch{return{msg:"[Unserializable]"}}}function MJ($){let J=aW();if(!J)return $;return eW($,J)}class WG{maybeSanitizeForMock($){if(!L$)return $;return LZ($,wZ)}info($){let J=MJ(KJ($)),Z=this.maybeSanitizeForMock(J);return t$("app").info(Z)}warn($){let J=MJ(KJ($)),Z=this.maybeSanitizeForMock(J);return t$("app").warn(Z)}error($){let J=MJ(KJ($)),Z=this.maybeSanitizeForMock(J),X=t$("app").error(Z);if(L$)return X;return t$("error").error(Z),X}debug($){if(m0.debug!==1)return;let J=MJ(KJ($)),Z=this.maybeSanitizeForMock(J);return t$("app").debug(Z)}async flush(){await oW()}configure($){rW($)}setMock($){iW($)}async shutdown(){await GG()}}var nW,XG,wZ,mW,A$=null,F$=null,L$=null,X$=null,G$=null,Y$=null,m0,j;var a=z$(()=>{tX();n0();OJ();nW=process.cwd(),XG=["*password*","pass","pwd","*token*","access_token","refresh_token","accessToken","refreshToken","authorization","cookie","set-cookie","*secret*","apiKey","api_key","privateKey","private_key"],wZ={maxStringLen:100,maxArrayItems:100,sanitizeDepth:3,sanitizeNodes:500,sanitizeObjectKeys:100,sensitiveKeyMatcher:PZ({builtinPatterns:XG,userPatterns:[]})},mW=(()=>{try{return bW()}catch{return"unknown"}})(),m0={debug:0,dir:"./logs",console:1,maxSize:20};j=new WG});import{isAbsolute as $H}from"path";import{pathToFileURL as JH}from"url";function ZH($){return/^[a-zA-Z]:[\\/]/.test($)}function XH($){if($H($)||ZH($))return JH($).href;return $}async function R$($,J){try{let G=($.endsWith(".json")?await import(XH($),{with:{type:"json"}}):await import($))?.default;if(G===null||G===void 0)return J;let Y=FZ(J),H=FZ(G);if(Y!==H)return j.warn({file:$,msg:"importDefault \u5BFC\u5165\u7C7B\u578B\u4E0E\u9ED8\u8BA4\u503C\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C",expectedType:Y,actualType:H}),J;return G}catch(Z){return j.warn({err:Z,file:$,msg:"importDefault \u5BFC\u5165\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C"}),J}}var AJ=z$(()=>{a();n0()});function e$($=""){if(!$)return $;return $.replace(/\\/g,"/").replace(YH,(J)=>J.toUpperCase())}function UH(){if(typeof process<"u"&&typeof process.cwd==="function")return process.cwd().replace(/\\/g,"/");return"/"}function NZ($,J){let Z="",X=0,G=-1,Y=0,H=null;for(let z=0;z<=$.length;++z){if(z<$.length)H=$[z];else if(H==="/")break;else H="/";if(H==="/"){if(G===z-1||Y===1);else if(Y===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("/");G=z,Y=0;continue}else if(Z.length>0){Z="",X=0,G=z,Y=0;continue}}if(J)Z+=Z.length>0?"/..":"..",X=2}else{if(Z.length>0)Z+=`/${$.slice(G+1,z)}`;else Z=$.slice(G+1,z);X=z-G-1}G=z,Y=0}else if(H==="."&&Y!==-1)++Y;else Y=-1}return Z}var YH,WH,HH,MG,KG,QH,zH,S$=function($){if($.length===0)return".";$=e$($);let J=$.match(WH),Z=k$($),X=$[$.length-1]==="/";if($=NZ($,!Z),$.length===0){if(Z)return"/";return X?"./":"."}if(X)$+="/";if(MG.test($))$+="/";if(J){if(!Z)return`//./${$}`;return`//${$}`}return Z&&!k$($)?`/${$}`:$},m=function(...$){let J="";for(let Z of $){if(!Z)continue;if(J.length>0){let X=J[J.length-1]==="/",G=Z[0]==="/";if(X&&G)J+=Z.slice(1);else J+=X||G?Z:`/${Z}`}else J+=Z}return S$(J)},a$=function(...$){$=$.map((X)=>e$(X));let J="",Z=!1;for(let X=$.length-1;X>=-1&&!Z;X--){let G=X>=0?$[X]:UH();if(!G||G.length===0)continue;J=`${G}/${J}`,Z=k$(G)}if(J=NZ(J,!Z),Z&&!k$(J))return`/${J}`;return J.length>0?J:"."},k$=function($){return HH.test($)},_G=function($){if($==="..")return"";let J=QH.exec(e$($));return J&&J[1]||""},vZ=function($,J){let Z=a$($).replace(KG,"$1").split("/"),X=a$(J).replace(KG,"$1").split("/");if(X[0][1]===":"&&Z[0][1]===":"&&Z[0]!==X[0])return X.join("/");let G=[...Z];for(let Y of G){if(X[0]!==Y)break;Z.shift(),X.shift()}return[...Z.map(()=>".."),...X].join("/")},FJ=function($){let J=e$($).replace(/\/$/,"").split("/").slice(0,-1);if(J.length===1&&MG.test(J[0]))J[0]+="/";return J.join("/")||(k$($)?"/":".")},AG=function($,J){let Z=e$($).split("/"),X="";for(let G=Z.length-1;G>=0;G--){let Y=Z[G];if(Y){X=Y;break}}return J&&X.endsWith(J)?X.slice(0,-J.length):X},$J=function($){let J=zH.exec($)?.[0]?.replace(/\\/g,"/")||"",Z=AG($),X=_G(Z);return{root:J,dir:FJ($),base:Z,ext:X,name:Z.slice(0,Z.length-X.length)}};var FG=z$(()=>{YH=/^[A-Za-z]:\//;WH=/^[/\\]{2}/,HH=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,MG=/^[A-Za-z]:$/,KG=/^\/([A-Za-z]:)?$/,QH=/.(\.[^./]+|\.)$/,zH=/^[/\\]|^[a-zA-Z]:[/\\]/});var q$=z$(()=>{FG()});import{statSync as VH}from"fs";var RJ=($,J)=>{if(J.isDirectory())return!0;if(!J.isSymbolicLink())return!1;try{return VH(m($,J.name)).isDirectory()}catch{return!1}};var DZ=z$(()=>{q$()});import{existsSync as x$}from"fs";import{readdir as OH}from"fs/promises";function KH($){if(!$||typeof $!=="object")return null;if(typeof $.title!=="string"||!$.title)return null;let J=typeof $.order==="number"&&Number.isFinite($.order)&&Number.isInteger($.order)&&$.order>=0?$.order:void 0;return{title:$.title,order:J}}async function RG($,J,Z=""){if(!x$($))return[];let X=[],G=await OH($,{withFileTypes:!0});for(let Y of G){if(!RJ($,Y)||Y.name==="components")continue;let H=m($,Y.name),z=m(H,"meta.json"),V=m(H,"index.vue"),O=null;if(!x$(z))continue;if(!x$(V)){j.warn({path:H,msg:"\u76EE\u5F55\u5B58\u5728 meta.json \u4F46\u7F3A\u5C11 index.vue\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}let _=await R$(z,{});if(O=KH(_),!O?.title){j.warn({path:z,msg:"meta.json \u7F3A\u5C11\u6709\u6548\u7684 title\uFF08\u4EE5\u53CA\u53EF\u9009 order:number\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}if(!O?.title)continue;let I=String(Y.name).replace(/_\d+$/,""),B;if(I==="index")B=Z;else B=Z?`${Z}/${I}`:`/${I}`;let S=J?B?`${J}${B}`:J:B||"/",C={name:O.title,path:S,sort:O.order??999999},T=await RG(H,J,B);if(T.length>0)C.children=T;X.push(C)}return X.sort((Y,H)=>(Y.sort??999999)-(H.sort??999999)),X}function IG($){let J=$.split("/").filter((Z)=>Boolean(Z));if(J.length<=1)return"";return`/${J.slice(0,-1).join("/")}`}async function qG($){let J=[];for(let X of $){let G=m(X.fullPath,"adminViews"),Y=m(X.fullPath,"views","admin"),H=x$(G)?G:x$(Y)?Y:null;if(!H)continue;try{let z=`/${X.source}/${X.name}`,V=await RG(H,z);if(V.length>0)for(let O of V)J.push(O)}catch(z){j.warn({err:z,addon:X.name,addonSource:X.source,dir:H,msg:"\u626B\u63CF addon views \u76EE\u5F55\u5931\u8D25"})}}let Z=m(process.cwd(),"menus.json");if(x$(Z)){let X=await R$(Z,[]);if(Array.isArray(X)&&X.length>0)for(let G of X)J.push(G)}return J}var kZ=z$(()=>{q$();a();AJ();DZ()});var p$=s((m5,E1)=>{var w1={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=w1;c$.wrap=function($,J,Z){if($ instanceof c$)return $;return new c$(J,Z,{originalError:$})};E1.exports={TokenError:c$,TOKEN_ERROR_CODES:w1}});var iZ=s((d5,T1)=>{var{TokenError:W$}=p$();function L9({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("."),G=Z.lastIndexOf(".");if(X===-1||X>=G)throw new W$(W$.codes.malformed,"The token is malformed.");let Y=!1;try{let H=JSON.parse(Buffer.from(Z.slice(0,X),"base64").toString("utf-8"));if(J&&H.typ!==J)throw new W$(W$.codes.invalidType,`The type must be "${J}".`,{header:H});Y=!0;let z=Buffer.from(Z.slice(X+1,G),"base64").toString("utf-8");if(z=JSON.parse(z),!z||typeof z!=="object")throw new W$(W$.codes.invalidPayload,"The payload must be an object",{payload:z});return $?{header:H,payload:z,signature:Z.slice(G+1),input:Z.slice(0,G)}:z}catch(H){throw W$.wrap(H,W$.codes.malformed,`The token ${Y?"payload":"header"} is not a valid base64url serialized JSON.`)}}T1.exports=function(J={}){let Z=J.complete||!1,X=J.checkTyp;return L9.bind(null,{complete:Z,checkTyp:X})}});var v1=s((s5,N1)=>{function H$($){if(typeof $!=="function")throw Error("obliterator/iterator: expecting a function!");this.next=$}if(typeof Symbol<"u")H$.prototype[Symbol.iterator]=function(){return this};H$.of=function(){var $=arguments,J=$.length,Z=0;return new H$(function(){if(Z>=J)return{done:!0};return{done:!1,value:$[Z++]}})};H$.empty=function(){var $=new H$(function(){return{done:!0}});return $};H$.fromSequence=function($){var J=0,Z=$.length;return new H$(function(){if(J>=Z)return{done:!0};return{done:!1,value:$[J++]}})};H$.is=function($){if($ instanceof H$)return!0;return typeof $==="object"&&$!==null&&typeof $.next==="function"};N1.exports=H$});var D1=s((S9)=>{S9.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<"u";S9.SYMBOL_SUPPORT=typeof Symbol<"u"});var tZ=s((l5,x1)=>{var k1=D1(),E9=k1.ARRAY_BUFFER_SUPPORT,T9=k1.SYMBOL_SUPPORT;x1.exports=function(J,Z){var X,G,Y,H,z;if(!J)throw Error("obliterator/forEach: invalid iterable.");if(typeof Z!=="function")throw Error("obliterator/forEach: expecting a callback.");if(Array.isArray(J)||E9&&ArrayBuffer.isView(J)||typeof J==="string"||J.toString()==="[object Arguments]"){for(Y=0,H=J.length;Y<H;Y++)Z(J[Y],Y);return}if(typeof J.forEach==="function"){J.forEach(Z);return}if(T9&&Symbol.iterator in J&&typeof J.next!=="function")J=J[Symbol.iterator]();if(typeof J.next==="function"){X=J,Y=0;while(z=X.next(),z.done!==!0)Z(z.value,Y),Y++;return}for(G in J)if(J.hasOwnProperty(G))Z(J[G],G);return}});var aZ=s((g9)=>{var N9=Math.pow(2,8)-1,v9=Math.pow(2,16)-1,D9=Math.pow(2,32)-1,k9=Math.pow(2,7)-1,x9=Math.pow(2,15)-1,y9=Math.pow(2,31)-1;g9.getPointerArray=function($){var J=$-1;if(J<=N9)return Uint8Array;if(J<=v9)return Uint16Array;if(J<=D9)return Uint32Array;throw Error("mnemonist: Pointer Array of size > 4294967295 is not supported.")};g9.getSignedPointerArray=function($){var J=$-1;if(J<=k9)return Int8Array;if(J<=x9)return Int16Array;if(J<=y9)return Int32Array;return Float64Array};g9.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 f9={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};g9.getMinimalRepresentation=function($,J){var Z=null,X=0,G,Y,H,z,V;for(z=0,V=$.length;z<V;z++)if(H=J?J($[z]):$[z],Y=g9.getNumberType(H),G=f9[Y.name],G>X)X=G,Z=Y;return Z};g9.isTypedArray=function($){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView($)};g9.concat=function(){var $=0,J,Z,X;for(J=0,X=arguments.length;J<X;J++)$+=arguments[J].length;var G=new arguments[0].constructor($);for(J=0,Z=0;J<X;J++)G.set(arguments[J],Z),Z+=arguments[J].length;return G};g9.indices=function($){var J=g9.getPointerArray($),Z=new J($);for(var X=0;X<$;X++)Z[X]=X;return Z}});var b1=s((s9)=>{var g1=tZ(),h1=aZ();function n9($){return Array.isArray($)||h1.isTypedArray($)}function eZ($){if(typeof $.length==="number")return $.length;if(typeof $.size==="number")return $.size;return}function m9($){var J=eZ($),Z=typeof J==="number"?Array(J):[],X=0;return g1($,function(G){Z[X++]=G}),Z}function d9($){var J=eZ($),Z=typeof J==="number"?h1.getPointerArray(J):Array,X=typeof J==="number"?Array(J):[],G=typeof J==="number"?new Z(J):[],Y=0;return g1($,function(H){X[Y]=H,G[Y]=Y++}),[X,G]}s9.isArrayLike=n9;s9.guessLength=eZ;s9.toArray=m9;s9.toArrayWithIndices=d9});var JX=s((t5,c1)=>{var $X=v1(),t9=tZ(),a9=aZ(),e9=b1();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=a9.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,G=this.items[$];if(typeof G<"u")return this.splayOnTop(G),Z=this.V[G],this.V[G]=J,{evicted:!1,key:$,value:Z};if(this.size<this.capacity)G=this.size++;else G=this.tail,this.tail=this.backward[G],Z=this.V[G],X=this.K[G],delete this.items[X];if(this.items[$]=G,this.K[G]=$,this.V[G]=J,this.forward[G]=this.head,this.backward[this.head]=G,this.head=G,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,G=this.head,Y=this.K,H=this.V,z=this.forward;while(Z<X)$.call(J,H[G],Y[G],this),G=z[G],Z++};p0.prototype.keys=function(){var $=0,J=this.size,Z=this.head,X=this.K,G=this.forward;return new $X(function(){if($>=J)return{done:!0};var Y=X[Z];if($++,$<J)Z=G[Z];return{done:!1,value:Y}})};p0.prototype.values=function(){var $=0,J=this.size,Z=this.head,X=this.V,G=this.forward;return new $X(function(){if($>=J)return{done:!0};var Y=X[Z];if($++,$<J)Z=G[Z];return{done:!1,value:Y}})};p0.prototype.entries=function(){var $=0,J=this.size,Z=this.head,X=this.K,G=this.V,Y=this.forward;return new $X(function(){if($>=J)return{done:!0};var H=X[Z],z=G[Z];if($++,$<J)Z=Y[Z];return{done:!1,value:[H,z]}})};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=e9.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 G=new p0(J,Z,X);return t9($,function(Y,H){G.set(H,Y)}),G};c1.exports=p0});var XX=s((p1,ZX)=>{(function($,J){function Z(q,W){if(!q)throw Error(W||"Assertion failed")}function X(q,W){q.super_=W;var U=function(){};U.prototype=W.prototype,q.prototype=new U,q.prototype.constructor=q}function G(q,W,U){if(G.isBN(q))return q;if(this.negative=0,this.words=null,this.length=0,this.red=null,q!==null){if(W==="le"||W==="be")U=W,W=10;this._init(q||0,W||10,U||"be")}}if(typeof $==="object")$.exports=G;else J.BN=G;G.BN=G,G.wordSize=26;var Y;try{if(typeof window<"u"&&typeof window.Buffer<"u")Y=window.Buffer;else Y=M$("buffer").Buffer}catch(q){}G.isBN=function(W){if(W instanceof G)return!0;return W!==null&&typeof W==="object"&&W.constructor.wordSize===G.wordSize&&Array.isArray(W.words)},G.max=function(W,U){if(W.cmp(U)>0)return W;return U},G.min=function(W,U){if(W.cmp(U)<0)return W;return U},G.prototype._init=function(W,U,K){if(typeof W==="number")return this._initNumber(W,U,K);if(typeof W==="object")return this._initArray(W,U,K);if(U==="hex")U=16;Z(U===(U|0)&&U>=2&&U<=36),W=W.toString().replace(/\s+/g,"");var M=0;if(W[0]==="-")M++,this.negative=1;if(M<W.length){if(U===16)this._parseHex(W,M,K);else if(this._parseBase(W,U,M),K==="le")this._initArray(this.toArray(),U,K)}},G.prototype._initNumber=function(W,U,K){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(K!=="le")return;this._initArray(this.toArray(),U,K)},G.prototype._initArray=function(W,U,K){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 M=0;M<this.length;M++)this.words[M]=0;var R,P,L=0;if(K==="be"){for(M=W.length-1,R=0;M>=0;M-=3)if(P=W[M]|W[M-1]<<8|W[M-2]<<16,this.words[R]|=P<<L&67108863,this.words[R+1]=P>>>26-L&67108863,L+=24,L>=26)L-=26,R++}else if(K==="le"){for(M=0,R=0;M<W.length;M+=3)if(P=W[M]|W[M+1]<<8|W[M+2]<<16,this.words[R]|=P<<L&67108863,this.words[R+1]=P>>>26-L&67108863,L+=24,L>=26)L-=26,R++}return this.strip()};function H(q,W){var U=q.charCodeAt(W);if(U>=65&&U<=70)return U-55;else if(U>=97&&U<=102)return U-87;else return U-48&15}function z(q,W,U){var K=H(q,U);if(U-1>=W)K|=H(q,U-1)<<4;return K}G.prototype._parseHex=function(W,U,K){this.length=Math.ceil((W.length-U)/6),this.words=Array(this.length);for(var M=0;M<this.length;M++)this.words[M]=0;var R=0,P=0,L;if(K==="be")for(M=W.length-1;M>=U;M-=2)if(L=z(W,U,M)<<R,this.words[P]|=L&67108863,R>=18)R-=18,P+=1,this.words[P]|=L>>>26;else R+=8;else{var A=W.length-U;for(M=A%2===0?U+1:U;M<W.length;M+=2)if(L=z(W,U,M)<<R,this.words[P]|=L&67108863,R>=18)R-=18,P+=1,this.words[P]|=L>>>26;else R+=8}this.strip()};function V(q,W,U,K){var M=0,R=Math.min(q.length,U);for(var P=W;P<R;P++){var L=q.charCodeAt(P)-48;if(M*=K,L>=49)M+=L-49+10;else if(L>=17)M+=L-17+10;else M+=L}return M}G.prototype._parseBase=function(W,U,K){this.words=[0],this.length=1;for(var M=0,R=1;R<=67108863;R*=U)M++;M--,R=R/U|0;var P=W.length-K,L=P%M,A=Math.min(P,P-L)+K,Q=0;for(var F=K;F<A;F+=M)if(Q=V(W,F,F+M,U),this.imuln(R),this.words[0]+Q<67108864)this.words[0]+=Q;else this._iaddn(Q);if(L!==0){var k=1;Q=V(W,F,W.length,U);for(F=0;F<L;F++)k*=U;if(this.imuln(k),this.words[0]+Q<67108864)this.words[0]+=Q;else this._iaddn(Q)}this.strip()},G.prototype.copy=function(W){W.words=Array(this.length);for(var U=0;U<this.length;U++)W.words[U]=this.words[U];W.length=this.length,W.negative=this.negative,W.red=this.red},G.prototype.clone=function(){var W=new G(null);return this.copy(W),W},G.prototype._expand=function(W){while(this.length<W)this.words[this.length++]=0;return this},G.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},G.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},G.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var O=["","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"],_=[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],I=[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(G.prototype.toString=function(W,U){W=W||10,U=U|0||1;var K;if(W===16||W==="hex"){K="";var M=0,R=0;for(var P=0;P<this.length;P++){var L=this.words[P],A=((L<<M|R)&16777215).toString(16);if(R=L>>>24-M&16777215,M+=2,M>=26)M-=26,P--;if(R!==0||P!==this.length-1)K=O[6-A.length]+A+K;else K=A+K}if(R!==0)K=R.toString(16)+K;while(K.length%U!==0)K="0"+K;if(this.negative!==0)K="-"+K;return K}if(W===(W|0)&&W>=2&&W<=36){var Q=_[W],F=I[W];K="";var k=this.clone();k.negative=0;while(!k.isZero()){var x=k.modn(F).toString(W);if(k=k.idivn(F),!k.isZero())K=O[Q-x.length]+x+K;else K=x+K}if(this.isZero())K="0"+K;while(K.length%U!==0)K="0"+K;if(this.negative!==0)K="-"+K;return K}Z(!1,"Base should be between 2 and 36")},G.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},G.prototype.toJSON=function(){return this.toString(16)},G.prototype.toBuffer=function(W,U){return Z(typeof Y<"u"),this.toArrayLike(Y,W,U)},G.prototype.toArray=function(W,U){return this.toArrayLike(Array,W,U)},G.prototype.toArrayLike=function(W,U,K){var M=this.byteLength(),R=K||Math.max(1,M);Z(M<=R,"byte array longer than desired length"),Z(R>0,"Requested array length <= 0"),this.strip();var P=U==="le",L=new W(R),A,Q,F=this.clone();if(!P){for(Q=0;Q<R-M;Q++)L[Q]=0;for(Q=0;!F.isZero();Q++)A=F.andln(255),F.iushrn(8),L[R-Q-1]=A}else{for(Q=0;!F.isZero();Q++)A=F.andln(255),F.iushrn(8),L[Q]=A;for(;Q<R;Q++)L[Q]=0}return L},Math.clz32)G.prototype._countBits=function(W){return 32-Math.clz32(W)};else G.prototype._countBits=function(W){var U=W,K=0;if(U>=4096)K+=13,U>>>=13;if(U>=64)K+=7,U>>>=7;if(U>=8)K+=4,U>>>=4;if(U>=2)K+=2,U>>>=2;return K+U};G.prototype._zeroBits=function(W){if(W===0)return 26;var U=W,K=0;if((U&8191)===0)K+=13,U>>>=13;if((U&127)===0)K+=7,U>>>=7;if((U&15)===0)K+=4,U>>>=4;if((U&3)===0)K+=2,U>>>=2;if((U&1)===0)K++;return K},G.prototype.bitLength=function(){var W=this.words[this.length-1],U=this._countBits(W);return(this.length-1)*26+U};function B(q){var W=Array(q.bitLength());for(var U=0;U<W.length;U++){var K=U/26|0,M=U%26;W[U]=(q.words[K]&1<<M)>>>M}return W}G.prototype.zeroBits=function(){if(this.isZero())return 0;var W=0;for(var U=0;U<this.length;U++){var K=this._zeroBits(this.words[U]);if(W+=K,K!==26)break}return W},G.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},G.prototype.toTwos=function(W){if(this.negative!==0)return this.abs().inotn(W).iaddn(1);return this.clone()},G.prototype.fromTwos=function(W){if(this.testn(W-1))return this.notn(W).iaddn(1).ineg();return this.clone()},G.prototype.isNeg=function(){return this.negative!==0},G.prototype.neg=function(){return this.clone().ineg()},G.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},G.prototype.iuor=function(W){while(this.length<W.length)this.words[this.length++]=0;for(var U=0;U<W.length;U++)this.words[U]=this.words[U]|W.words[U];return this.strip()},G.prototype.ior=function(W){return Z((this.negative|W.negative)===0),this.iuor(W)},G.prototype.or=function(W){if(this.length>W.length)return this.clone().ior(W);return W.clone().ior(this)},G.prototype.uor=function(W){if(this.length>W.length)return this.clone().iuor(W);return W.clone().iuor(this)},G.prototype.iuand=function(W){var U;if(this.length>W.length)U=W;else U=this;for(var K=0;K<U.length;K++)this.words[K]=this.words[K]&W.words[K];return this.length=U.length,this.strip()},G.prototype.iand=function(W){return Z((this.negative|W.negative)===0),this.iuand(W)},G.prototype.and=function(W){if(this.length>W.length)return this.clone().iand(W);return W.clone().iand(this)},G.prototype.uand=function(W){if(this.length>W.length)return this.clone().iuand(W);return W.clone().iuand(this)},G.prototype.iuxor=function(W){var U,K;if(this.length>W.length)U=this,K=W;else U=W,K=this;for(var M=0;M<K.length;M++)this.words[M]=U.words[M]^K.words[M];if(this!==U)for(;M<U.length;M++)this.words[M]=U.words[M];return this.length=U.length,this.strip()},G.prototype.ixor=function(W){return Z((this.negative|W.negative)===0),this.iuxor(W)},G.prototype.xor=function(W){if(this.length>W.length)return this.clone().ixor(W);return W.clone().ixor(this)},G.prototype.uxor=function(W){if(this.length>W.length)return this.clone().iuxor(W);return W.clone().iuxor(this)},G.prototype.inotn=function(W){Z(typeof W==="number"&&W>=0);var U=Math.ceil(W/26)|0,K=W%26;if(this._expand(U),K>0)U--;for(var M=0;M<U;M++)this.words[M]=~this.words[M]&67108863;if(K>0)this.words[M]=~this.words[M]&67108863>>26-K;return this.strip()},G.prototype.notn=function(W){return this.clone().inotn(W)},G.prototype.setn=function(W,U){Z(typeof W==="number"&&W>=0);var K=W/26|0,M=W%26;if(this._expand(K+1),U)this.words[K]=this.words[K]|1<<M;else this.words[K]=this.words[K]&~(1<<M);return this.strip()},G.prototype.iadd=function(W){var U;if(this.negative!==0&&W.negative===0)return this.negative=0,U=this.isub(W),this.negative^=1,this._normSign();else if(this.negative===0&&W.negative!==0)return W.negative=0,U=this.isub(W),W.negative=1,U._normSign();var K,M;if(this.length>W.length)K=this,M=W;else K=W,M=this;var R=0;for(var P=0;P<M.length;P++)U=(K.words[P]|0)+(M.words[P]|0)+R,this.words[P]=U&67108863,R=U>>>26;for(;R!==0&&P<K.length;P++)U=(K.words[P]|0)+R,this.words[P]=U&67108863,R=U>>>26;if(this.length=K.length,R!==0)this.words[this.length]=R,this.length++;else if(K!==this)for(;P<K.length;P++)this.words[P]=K.words[P];return this},G.prototype.add=function(W){var U;if(W.negative!==0&&this.negative===0)return W.negative=0,U=this.sub(W),W.negative^=1,U;else if(W.negative===0&&this.negative!==0)return this.negative=0,U=W.sub(this),this.negative=1,U;if(this.length>W.length)return this.clone().iadd(W);return W.clone().iadd(this)},G.prototype.isub=function(W){if(W.negative!==0){W.negative=0;var U=this.iadd(W);return W.negative=1,U._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(W),this.negative=1,this._normSign();var K=this.cmp(W);if(K===0)return this.negative=0,this.length=1,this.words[0]=0,this;var M,R;if(K>0)M=this,R=W;else M=W,R=this;var P=0;for(var L=0;L<R.length;L++)U=(M.words[L]|0)-(R.words[L]|0)+P,P=U>>26,this.words[L]=U&67108863;for(;P!==0&&L<M.length;L++)U=(M.words[L]|0)+P,P=U>>26,this.words[L]=U&67108863;if(P===0&&L<M.length&&M!==this)for(;L<M.length;L++)this.words[L]=M.words[L];if(this.length=Math.max(this.length,L),M!==this)this.negative=1;return this.strip()},G.prototype.sub=function(W){return this.clone().isub(W)};function S(q,W,U){U.negative=W.negative^q.negative;var K=q.length+W.length|0;U.length=K,K=K-1|0;var M=q.words[0]|0,R=W.words[0]|0,P=M*R,L=P&67108863,A=P/67108864|0;U.words[0]=L;for(var Q=1;Q<K;Q++){var F=A>>>26,k=A&67108863,x=Math.min(Q,W.length-1);for(var y=Math.max(0,Q-q.length+1);y<=x;y++){var u=Q-y|0;M=q.words[u]|0,R=W.words[y]|0,P=M*R+k,F+=P/67108864|0,k=P&67108863}U.words[Q]=k|0,A=F|0}if(A!==0)U.words[Q]=A|0;else U.length--;return U.strip()}var C=function(W,U,K){var M=W.words,R=U.words,P=K.words,L=0,A,Q,F,k=M[0]|0,x=k&8191,y=k>>>13,u=M[1]|0,l=u&8191,e=u>>>13,K$=M[2]|0,$0=K$&8191,Z0=K$>>>13,EX=M[3]|0,H0=EX&8191,Q0=EX>>>13,TX=M[4]|0,z0=TX&8191,U0=TX>>>13,NX=M[5]|0,V0=NX&8191,O0=NX>>>13,vX=M[6]|0,K0=vX&8191,M0=vX>>>13,DX=M[7]|0,_0=DX&8191,A0=DX>>>13,kX=M[8]|0,F0=kX&8191,R0=kX>>>13,xX=M[9]|0,I0=xX&8191,q0=xX>>>13,yX=R[0]|0,j0=yX&8191,P0=yX>>>13,fX=R[1]|0,B0=fX&8191,L0=fX>>>13,gX=R[2]|0,S0=gX&8191,C0=gX>>>13,hX=R[3]|0,w0=hX&8191,E0=hX>>>13,bX=R[4]|0,T0=bX&8191,N0=bX>>>13,cX=R[5]|0,v0=cX&8191,D0=cX>>>13,pX=R[6]|0,k0=pX&8191,x0=pX>>>13,uX=R[7]|0,y0=uX&8191,f0=uX>>>13,nX=R[8]|0,g0=nX&8191,h0=nX>>>13,mX=R[9]|0,b0=mX&8191,c0=mX>>>13;K.negative=W.negative^U.negative,K.length=19,A=Math.imul(x,j0),Q=Math.imul(x,P0),Q=Q+Math.imul(y,j0)|0,F=Math.imul(y,P0);var tJ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(tJ>>>26)|0,tJ&=67108863,A=Math.imul(l,j0),Q=Math.imul(l,P0),Q=Q+Math.imul(e,j0)|0,F=Math.imul(e,P0),A=A+Math.imul(x,B0)|0,Q=Q+Math.imul(x,L0)|0,Q=Q+Math.imul(y,B0)|0,F=F+Math.imul(y,L0)|0;var aJ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(aJ>>>26)|0,aJ&=67108863,A=Math.imul($0,j0),Q=Math.imul($0,P0),Q=Q+Math.imul(Z0,j0)|0,F=Math.imul(Z0,P0),A=A+Math.imul(l,B0)|0,Q=Q+Math.imul(l,L0)|0,Q=Q+Math.imul(e,B0)|0,F=F+Math.imul(e,L0)|0,A=A+Math.imul(x,S0)|0,Q=Q+Math.imul(x,C0)|0,Q=Q+Math.imul(y,S0)|0,F=F+Math.imul(y,C0)|0;var eJ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(eJ>>>26)|0,eJ&=67108863,A=Math.imul(H0,j0),Q=Math.imul(H0,P0),Q=Q+Math.imul(Q0,j0)|0,F=Math.imul(Q0,P0),A=A+Math.imul($0,B0)|0,Q=Q+Math.imul($0,L0)|0,Q=Q+Math.imul(Z0,B0)|0,F=F+Math.imul(Z0,L0)|0,A=A+Math.imul(l,S0)|0,Q=Q+Math.imul(l,C0)|0,Q=Q+Math.imul(e,S0)|0,F=F+Math.imul(e,C0)|0,A=A+Math.imul(x,w0)|0,Q=Q+Math.imul(x,E0)|0,Q=Q+Math.imul(y,w0)|0,F=F+Math.imul(y,E0)|0;var $Z=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+($Z>>>26)|0,$Z&=67108863,A=Math.imul(z0,j0),Q=Math.imul(z0,P0),Q=Q+Math.imul(U0,j0)|0,F=Math.imul(U0,P0),A=A+Math.imul(H0,B0)|0,Q=Q+Math.imul(H0,L0)|0,Q=Q+Math.imul(Q0,B0)|0,F=F+Math.imul(Q0,L0)|0,A=A+Math.imul($0,S0)|0,Q=Q+Math.imul($0,C0)|0,Q=Q+Math.imul(Z0,S0)|0,F=F+Math.imul(Z0,C0)|0,A=A+Math.imul(l,w0)|0,Q=Q+Math.imul(l,E0)|0,Q=Q+Math.imul(e,w0)|0,F=F+Math.imul(e,E0)|0,A=A+Math.imul(x,T0)|0,Q=Q+Math.imul(x,N0)|0,Q=Q+Math.imul(y,T0)|0,F=F+Math.imul(y,N0)|0;var JZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(JZ>>>26)|0,JZ&=67108863,A=Math.imul(V0,j0),Q=Math.imul(V0,P0),Q=Q+Math.imul(O0,j0)|0,F=Math.imul(O0,P0),A=A+Math.imul(z0,B0)|0,Q=Q+Math.imul(z0,L0)|0,Q=Q+Math.imul(U0,B0)|0,F=F+Math.imul(U0,L0)|0,A=A+Math.imul(H0,S0)|0,Q=Q+Math.imul(H0,C0)|0,Q=Q+Math.imul(Q0,S0)|0,F=F+Math.imul(Q0,C0)|0,A=A+Math.imul($0,w0)|0,Q=Q+Math.imul($0,E0)|0,Q=Q+Math.imul(Z0,w0)|0,F=F+Math.imul(Z0,E0)|0,A=A+Math.imul(l,T0)|0,Q=Q+Math.imul(l,N0)|0,Q=Q+Math.imul(e,T0)|0,F=F+Math.imul(e,N0)|0,A=A+Math.imul(x,v0)|0,Q=Q+Math.imul(x,D0)|0,Q=Q+Math.imul(y,v0)|0,F=F+Math.imul(y,D0)|0;var ZZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(ZZ>>>26)|0,ZZ&=67108863,A=Math.imul(K0,j0),Q=Math.imul(K0,P0),Q=Q+Math.imul(M0,j0)|0,F=Math.imul(M0,P0),A=A+Math.imul(V0,B0)|0,Q=Q+Math.imul(V0,L0)|0,Q=Q+Math.imul(O0,B0)|0,F=F+Math.imul(O0,L0)|0,A=A+Math.imul(z0,S0)|0,Q=Q+Math.imul(z0,C0)|0,Q=Q+Math.imul(U0,S0)|0,F=F+Math.imul(U0,C0)|0,A=A+Math.imul(H0,w0)|0,Q=Q+Math.imul(H0,E0)|0,Q=Q+Math.imul(Q0,w0)|0,F=F+Math.imul(Q0,E0)|0,A=A+Math.imul($0,T0)|0,Q=Q+Math.imul($0,N0)|0,Q=Q+Math.imul(Z0,T0)|0,F=F+Math.imul(Z0,N0)|0,A=A+Math.imul(l,v0)|0,Q=Q+Math.imul(l,D0)|0,Q=Q+Math.imul(e,v0)|0,F=F+Math.imul(e,D0)|0,A=A+Math.imul(x,k0)|0,Q=Q+Math.imul(x,x0)|0,Q=Q+Math.imul(y,k0)|0,F=F+Math.imul(y,x0)|0;var XZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(XZ>>>26)|0,XZ&=67108863,A=Math.imul(_0,j0),Q=Math.imul(_0,P0),Q=Q+Math.imul(A0,j0)|0,F=Math.imul(A0,P0),A=A+Math.imul(K0,B0)|0,Q=Q+Math.imul(K0,L0)|0,Q=Q+Math.imul(M0,B0)|0,F=F+Math.imul(M0,L0)|0,A=A+Math.imul(V0,S0)|0,Q=Q+Math.imul(V0,C0)|0,Q=Q+Math.imul(O0,S0)|0,F=F+Math.imul(O0,C0)|0,A=A+Math.imul(z0,w0)|0,Q=Q+Math.imul(z0,E0)|0,Q=Q+Math.imul(U0,w0)|0,F=F+Math.imul(U0,E0)|0,A=A+Math.imul(H0,T0)|0,Q=Q+Math.imul(H0,N0)|0,Q=Q+Math.imul(Q0,T0)|0,F=F+Math.imul(Q0,N0)|0,A=A+Math.imul($0,v0)|0,Q=Q+Math.imul($0,D0)|0,Q=Q+Math.imul(Z0,v0)|0,F=F+Math.imul(Z0,D0)|0,A=A+Math.imul(l,k0)|0,Q=Q+Math.imul(l,x0)|0,Q=Q+Math.imul(e,k0)|0,F=F+Math.imul(e,x0)|0,A=A+Math.imul(x,y0)|0,Q=Q+Math.imul(x,f0)|0,Q=Q+Math.imul(y,y0)|0,F=F+Math.imul(y,f0)|0;var GZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(GZ>>>26)|0,GZ&=67108863,A=Math.imul(F0,j0),Q=Math.imul(F0,P0),Q=Q+Math.imul(R0,j0)|0,F=Math.imul(R0,P0),A=A+Math.imul(_0,B0)|0,Q=Q+Math.imul(_0,L0)|0,Q=Q+Math.imul(A0,B0)|0,F=F+Math.imul(A0,L0)|0,A=A+Math.imul(K0,S0)|0,Q=Q+Math.imul(K0,C0)|0,Q=Q+Math.imul(M0,S0)|0,F=F+Math.imul(M0,C0)|0,A=A+Math.imul(V0,w0)|0,Q=Q+Math.imul(V0,E0)|0,Q=Q+Math.imul(O0,w0)|0,F=F+Math.imul(O0,E0)|0,A=A+Math.imul(z0,T0)|0,Q=Q+Math.imul(z0,N0)|0,Q=Q+Math.imul(U0,T0)|0,F=F+Math.imul(U0,N0)|0,A=A+Math.imul(H0,v0)|0,Q=Q+Math.imul(H0,D0)|0,Q=Q+Math.imul(Q0,v0)|0,F=F+Math.imul(Q0,D0)|0,A=A+Math.imul($0,k0)|0,Q=Q+Math.imul($0,x0)|0,Q=Q+Math.imul(Z0,k0)|0,F=F+Math.imul(Z0,x0)|0,A=A+Math.imul(l,y0)|0,Q=Q+Math.imul(l,f0)|0,Q=Q+Math.imul(e,y0)|0,F=F+Math.imul(e,f0)|0,A=A+Math.imul(x,g0)|0,Q=Q+Math.imul(x,h0)|0,Q=Q+Math.imul(y,g0)|0,F=F+Math.imul(y,h0)|0;var YZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(YZ>>>26)|0,YZ&=67108863,A=Math.imul(I0,j0),Q=Math.imul(I0,P0),Q=Q+Math.imul(q0,j0)|0,F=Math.imul(q0,P0),A=A+Math.imul(F0,B0)|0,Q=Q+Math.imul(F0,L0)|0,Q=Q+Math.imul(R0,B0)|0,F=F+Math.imul(R0,L0)|0,A=A+Math.imul(_0,S0)|0,Q=Q+Math.imul(_0,C0)|0,Q=Q+Math.imul(A0,S0)|0,F=F+Math.imul(A0,C0)|0,A=A+Math.imul(K0,w0)|0,Q=Q+Math.imul(K0,E0)|0,Q=Q+Math.imul(M0,w0)|0,F=F+Math.imul(M0,E0)|0,A=A+Math.imul(V0,T0)|0,Q=Q+Math.imul(V0,N0)|0,Q=Q+Math.imul(O0,T0)|0,F=F+Math.imul(O0,N0)|0,A=A+Math.imul(z0,v0)|0,Q=Q+Math.imul(z0,D0)|0,Q=Q+Math.imul(U0,v0)|0,F=F+Math.imul(U0,D0)|0,A=A+Math.imul(H0,k0)|0,Q=Q+Math.imul(H0,x0)|0,Q=Q+Math.imul(Q0,k0)|0,F=F+Math.imul(Q0,x0)|0,A=A+Math.imul($0,y0)|0,Q=Q+Math.imul($0,f0)|0,Q=Q+Math.imul(Z0,y0)|0,F=F+Math.imul(Z0,f0)|0,A=A+Math.imul(l,g0)|0,Q=Q+Math.imul(l,h0)|0,Q=Q+Math.imul(e,g0)|0,F=F+Math.imul(e,h0)|0,A=A+Math.imul(x,b0)|0,Q=Q+Math.imul(x,c0)|0,Q=Q+Math.imul(y,b0)|0,F=F+Math.imul(y,c0)|0;var WZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(WZ>>>26)|0,WZ&=67108863,A=Math.imul(I0,B0),Q=Math.imul(I0,L0),Q=Q+Math.imul(q0,B0)|0,F=Math.imul(q0,L0),A=A+Math.imul(F0,S0)|0,Q=Q+Math.imul(F0,C0)|0,Q=Q+Math.imul(R0,S0)|0,F=F+Math.imul(R0,C0)|0,A=A+Math.imul(_0,w0)|0,Q=Q+Math.imul(_0,E0)|0,Q=Q+Math.imul(A0,w0)|0,F=F+Math.imul(A0,E0)|0,A=A+Math.imul(K0,T0)|0,Q=Q+Math.imul(K0,N0)|0,Q=Q+Math.imul(M0,T0)|0,F=F+Math.imul(M0,N0)|0,A=A+Math.imul(V0,v0)|0,Q=Q+Math.imul(V0,D0)|0,Q=Q+Math.imul(O0,v0)|0,F=F+Math.imul(O0,D0)|0,A=A+Math.imul(z0,k0)|0,Q=Q+Math.imul(z0,x0)|0,Q=Q+Math.imul(U0,k0)|0,F=F+Math.imul(U0,x0)|0,A=A+Math.imul(H0,y0)|0,Q=Q+Math.imul(H0,f0)|0,Q=Q+Math.imul(Q0,y0)|0,F=F+Math.imul(Q0,f0)|0,A=A+Math.imul($0,g0)|0,Q=Q+Math.imul($0,h0)|0,Q=Q+Math.imul(Z0,g0)|0,F=F+Math.imul(Z0,h0)|0,A=A+Math.imul(l,b0)|0,Q=Q+Math.imul(l,c0)|0,Q=Q+Math.imul(e,b0)|0,F=F+Math.imul(e,c0)|0;var HZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(HZ>>>26)|0,HZ&=67108863,A=Math.imul(I0,S0),Q=Math.imul(I0,C0),Q=Q+Math.imul(q0,S0)|0,F=Math.imul(q0,C0),A=A+Math.imul(F0,w0)|0,Q=Q+Math.imul(F0,E0)|0,Q=Q+Math.imul(R0,w0)|0,F=F+Math.imul(R0,E0)|0,A=A+Math.imul(_0,T0)|0,Q=Q+Math.imul(_0,N0)|0,Q=Q+Math.imul(A0,T0)|0,F=F+Math.imul(A0,N0)|0,A=A+Math.imul(K0,v0)|0,Q=Q+Math.imul(K0,D0)|0,Q=Q+Math.imul(M0,v0)|0,F=F+Math.imul(M0,D0)|0,A=A+Math.imul(V0,k0)|0,Q=Q+Math.imul(V0,x0)|0,Q=Q+Math.imul(O0,k0)|0,F=F+Math.imul(O0,x0)|0,A=A+Math.imul(z0,y0)|0,Q=Q+Math.imul(z0,f0)|0,Q=Q+Math.imul(U0,y0)|0,F=F+Math.imul(U0,f0)|0,A=A+Math.imul(H0,g0)|0,Q=Q+Math.imul(H0,h0)|0,Q=Q+Math.imul(Q0,g0)|0,F=F+Math.imul(Q0,h0)|0,A=A+Math.imul($0,b0)|0,Q=Q+Math.imul($0,c0)|0,Q=Q+Math.imul(Z0,b0)|0,F=F+Math.imul(Z0,c0)|0;var QZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(QZ>>>26)|0,QZ&=67108863,A=Math.imul(I0,w0),Q=Math.imul(I0,E0),Q=Q+Math.imul(q0,w0)|0,F=Math.imul(q0,E0),A=A+Math.imul(F0,T0)|0,Q=Q+Math.imul(F0,N0)|0,Q=Q+Math.imul(R0,T0)|0,F=F+Math.imul(R0,N0)|0,A=A+Math.imul(_0,v0)|0,Q=Q+Math.imul(_0,D0)|0,Q=Q+Math.imul(A0,v0)|0,F=F+Math.imul(A0,D0)|0,A=A+Math.imul(K0,k0)|0,Q=Q+Math.imul(K0,x0)|0,Q=Q+Math.imul(M0,k0)|0,F=F+Math.imul(M0,x0)|0,A=A+Math.imul(V0,y0)|0,Q=Q+Math.imul(V0,f0)|0,Q=Q+Math.imul(O0,y0)|0,F=F+Math.imul(O0,f0)|0,A=A+Math.imul(z0,g0)|0,Q=Q+Math.imul(z0,h0)|0,Q=Q+Math.imul(U0,g0)|0,F=F+Math.imul(U0,h0)|0,A=A+Math.imul(H0,b0)|0,Q=Q+Math.imul(H0,c0)|0,Q=Q+Math.imul(Q0,b0)|0,F=F+Math.imul(Q0,c0)|0;var zZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,A=Math.imul(I0,T0),Q=Math.imul(I0,N0),Q=Q+Math.imul(q0,T0)|0,F=Math.imul(q0,N0),A=A+Math.imul(F0,v0)|0,Q=Q+Math.imul(F0,D0)|0,Q=Q+Math.imul(R0,v0)|0,F=F+Math.imul(R0,D0)|0,A=A+Math.imul(_0,k0)|0,Q=Q+Math.imul(_0,x0)|0,Q=Q+Math.imul(A0,k0)|0,F=F+Math.imul(A0,x0)|0,A=A+Math.imul(K0,y0)|0,Q=Q+Math.imul(K0,f0)|0,Q=Q+Math.imul(M0,y0)|0,F=F+Math.imul(M0,f0)|0,A=A+Math.imul(V0,g0)|0,Q=Q+Math.imul(V0,h0)|0,Q=Q+Math.imul(O0,g0)|0,F=F+Math.imul(O0,h0)|0,A=A+Math.imul(z0,b0)|0,Q=Q+Math.imul(z0,c0)|0,Q=Q+Math.imul(U0,b0)|0,F=F+Math.imul(U0,c0)|0;var UZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(UZ>>>26)|0,UZ&=67108863,A=Math.imul(I0,v0),Q=Math.imul(I0,D0),Q=Q+Math.imul(q0,v0)|0,F=Math.imul(q0,D0),A=A+Math.imul(F0,k0)|0,Q=Q+Math.imul(F0,x0)|0,Q=Q+Math.imul(R0,k0)|0,F=F+Math.imul(R0,x0)|0,A=A+Math.imul(_0,y0)|0,Q=Q+Math.imul(_0,f0)|0,Q=Q+Math.imul(A0,y0)|0,F=F+Math.imul(A0,f0)|0,A=A+Math.imul(K0,g0)|0,Q=Q+Math.imul(K0,h0)|0,Q=Q+Math.imul(M0,g0)|0,F=F+Math.imul(M0,h0)|0,A=A+Math.imul(V0,b0)|0,Q=Q+Math.imul(V0,c0)|0,Q=Q+Math.imul(O0,b0)|0,F=F+Math.imul(O0,c0)|0;var VZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(VZ>>>26)|0,VZ&=67108863,A=Math.imul(I0,k0),Q=Math.imul(I0,x0),Q=Q+Math.imul(q0,k0)|0,F=Math.imul(q0,x0),A=A+Math.imul(F0,y0)|0,Q=Q+Math.imul(F0,f0)|0,Q=Q+Math.imul(R0,y0)|0,F=F+Math.imul(R0,f0)|0,A=A+Math.imul(_0,g0)|0,Q=Q+Math.imul(_0,h0)|0,Q=Q+Math.imul(A0,g0)|0,F=F+Math.imul(A0,h0)|0,A=A+Math.imul(K0,b0)|0,Q=Q+Math.imul(K0,c0)|0,Q=Q+Math.imul(M0,b0)|0,F=F+Math.imul(M0,c0)|0;var OZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(OZ>>>26)|0,OZ&=67108863,A=Math.imul(I0,y0),Q=Math.imul(I0,f0),Q=Q+Math.imul(q0,y0)|0,F=Math.imul(q0,f0),A=A+Math.imul(F0,g0)|0,Q=Q+Math.imul(F0,h0)|0,Q=Q+Math.imul(R0,g0)|0,F=F+Math.imul(R0,h0)|0,A=A+Math.imul(_0,b0)|0,Q=Q+Math.imul(_0,c0)|0,Q=Q+Math.imul(A0,b0)|0,F=F+Math.imul(A0,c0)|0;var KZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(KZ>>>26)|0,KZ&=67108863,A=Math.imul(I0,g0),Q=Math.imul(I0,h0),Q=Q+Math.imul(q0,g0)|0,F=Math.imul(q0,h0),A=A+Math.imul(F0,b0)|0,Q=Q+Math.imul(F0,c0)|0,Q=Q+Math.imul(R0,b0)|0,F=F+Math.imul(R0,c0)|0;var MZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(MZ>>>26)|0,MZ&=67108863,A=Math.imul(I0,b0),Q=Math.imul(I0,c0),Q=Q+Math.imul(q0,b0)|0,F=Math.imul(q0,c0);var _Z=(L+A|0)+((Q&8191)<<13)|0;if(L=(F+(Q>>>13)|0)+(_Z>>>26)|0,_Z&=67108863,P[0]=tJ,P[1]=aJ,P[2]=eJ,P[3]=$Z,P[4]=JZ,P[5]=ZZ,P[6]=XZ,P[7]=GZ,P[8]=YZ,P[9]=WZ,P[10]=HZ,P[11]=QZ,P[12]=zZ,P[13]=UZ,P[14]=VZ,P[15]=OZ,P[16]=KZ,P[17]=MZ,P[18]=_Z,L!==0)P[19]=L,K.length++;return K};if(!Math.imul)C=S;function T(q,W,U){U.negative=W.negative^q.negative,U.length=q.length+W.length;var K=0,M=0;for(var R=0;R<U.length-1;R++){var P=M;M=0;var L=K&67108863,A=Math.min(R,W.length-1);for(var Q=Math.max(0,R-q.length+1);Q<=A;Q++){var F=R-Q,k=q.words[F]|0,x=W.words[Q]|0,y=k*x,u=y&67108863;P=P+(y/67108864|0)|0,u=u+L|0,L=u&67108863,P=P+(u>>>26)|0,M+=P>>>26,P&=67108863}U.words[R]=L,K=P,P=M}if(K!==0)U.words[R]=K;else U.length--;return U.strip()}function E(q,W,U){var K=new D;return K.mulp(q,W,U)}G.prototype.mulTo=function(W,U){var K,M=this.length+W.length;if(this.length===10&&W.length===10)K=C(this,W,U);else if(M<63)K=S(this,W,U);else if(M<1024)K=T(this,W,U);else K=E(this,W,U);return K};function D(q,W){this.x=q,this.y=W}D.prototype.makeRBT=function(W){var U=Array(W),K=G.prototype._countBits(W)-1;for(var M=0;M<W;M++)U[M]=this.revBin(M,K,W);return U},D.prototype.revBin=function(W,U,K){if(W===0||W===K-1)return W;var M=0;for(var R=0;R<U;R++)M|=(W&1)<<U-R-1,W>>=1;return M},D.prototype.permute=function(W,U,K,M,R,P){for(var L=0;L<P;L++)M[L]=U[W[L]],R[L]=K[W[L]]},D.prototype.transform=function(W,U,K,M,R,P){this.permute(P,W,U,K,M,R);for(var L=1;L<R;L<<=1){var A=L<<1,Q=Math.cos(2*Math.PI/A),F=Math.sin(2*Math.PI/A);for(var k=0;k<R;k+=A){var x=Q,y=F;for(var u=0;u<L;u++){var l=K[k+u],e=M[k+u],K$=K[k+u+L],$0=M[k+u+L],Z0=x*K$-y*$0;if($0=x*$0+y*K$,K$=Z0,K[k+u]=l+K$,M[k+u]=e+$0,K[k+u+L]=l-K$,M[k+u+L]=e-$0,u!==A)Z0=Q*x-F*y,y=Q*y+F*x,x=Z0}}}},D.prototype.guessLen13b=function(W,U){var K=Math.max(U,W)|1,M=K&1,R=0;for(K=K/2|0;K;K=K>>>1)R++;return 1<<R+1+M},D.prototype.conjugate=function(W,U,K){if(K<=1)return;for(var M=0;M<K/2;M++){var R=W[M];W[M]=W[K-M-1],W[K-M-1]=R,R=U[M],U[M]=-U[K-M-1],U[K-M-1]=-R}},D.prototype.normalize13b=function(W,U){var K=0;for(var M=0;M<U/2;M++){var R=Math.round(W[2*M+1]/U)*8192+Math.round(W[2*M]/U)+K;if(W[M]=R&67108863,R<67108864)K=0;else K=R/67108864|0}return W},D.prototype.convert13b=function(W,U,K,M){var R=0;for(var P=0;P<U;P++)R=R+(W[P]|0),K[2*P]=R&8191,R=R>>>13,K[2*P+1]=R&8191,R=R>>>13;for(P=2*U;P<M;++P)K[P]=0;Z(R===0),Z((R&-8192)===0)},D.prototype.stub=function(W){var U=Array(W);for(var K=0;K<W;K++)U[K]=0;return U},D.prototype.mulp=function(W,U,K){var M=2*this.guessLen13b(W.length,U.length),R=this.makeRBT(M),P=this.stub(M),L=Array(M),A=Array(M),Q=Array(M),F=Array(M),k=Array(M),x=Array(M),y=K.words;y.length=M,this.convert13b(W.words,W.length,L,M),this.convert13b(U.words,U.length,F,M),this.transform(L,P,A,Q,M,R),this.transform(F,P,k,x,M,R);for(var u=0;u<M;u++){var l=A[u]*k[u]-Q[u]*x[u];Q[u]=A[u]*x[u]+Q[u]*k[u],A[u]=l}return this.conjugate(A,Q,M),this.transform(A,Q,y,P,M,R),this.conjugate(y,P,M),this.normalize13b(y,M),K.negative=W.negative^U.negative,K.length=W.length+U.length,K.strip()},G.prototype.mul=function(W){var U=new G(null);return U.words=Array(this.length+W.length),this.mulTo(W,U)},G.prototype.mulf=function(W){var U=new G(null);return U.words=Array(this.length+W.length),E(this,W,U)},G.prototype.imul=function(W){return this.clone().mulTo(W,this)},G.prototype.imuln=function(W){Z(typeof W==="number"),Z(W<67108864);var U=0;for(var K=0;K<this.length;K++){var M=(this.words[K]|0)*W,R=(M&67108863)+(U&67108863);U>>=26,U+=M/67108864|0,U+=R>>>26,this.words[K]=R&67108863}if(U!==0)this.words[K]=U,this.length++;return this.length=W===0?1:this.length,this},G.prototype.muln=function(W){return this.clone().imuln(W)},G.prototype.sqr=function(){return this.mul(this)},G.prototype.isqr=function(){return this.imul(this.clone())},G.prototype.pow=function(W){var U=B(W);if(U.length===0)return new G(1);var K=this;for(var M=0;M<U.length;M++,K=K.sqr())if(U[M]!==0)break;if(++M<U.length)for(var R=K.sqr();M<U.length;M++,R=R.sqr()){if(U[M]===0)continue;K=K.mul(R)}return K},G.prototype.iushln=function(W){Z(typeof W==="number"&&W>=0);var U=W%26,K=(W-U)/26,M=67108863>>>26-U<<26-U,R;if(U!==0){var P=0;for(R=0;R<this.length;R++){var L=this.words[R]&M,A=(this.words[R]|0)-L<<U;this.words[R]=A|P,P=L>>>26-U}if(P)this.words[R]=P,this.length++}if(K!==0){for(R=this.length-1;R>=0;R--)this.words[R+K]=this.words[R];for(R=0;R<K;R++)this.words[R]=0;this.length+=K}return this.strip()},G.prototype.ishln=function(W){return Z(this.negative===0),this.iushln(W)},G.prototype.iushrn=function(W,U,K){Z(typeof W==="number"&&W>=0);var M;if(U)M=(U-U%26)/26;else M=0;var R=W%26,P=Math.min((W-R)/26,this.length),L=67108863^67108863>>>R<<R,A=K;if(M-=P,M=Math.max(0,M),A){for(var Q=0;Q<P;Q++)A.words[Q]=this.words[Q];A.length=P}if(P===0);else if(this.length>P){this.length-=P;for(Q=0;Q<this.length;Q++)this.words[Q]=this.words[Q+P]}else this.words[0]=0,this.length=1;var F=0;for(Q=this.length-1;Q>=0&&(F!==0||Q>=M);Q--){var k=this.words[Q]|0;this.words[Q]=F<<26-R|k>>>R,F=k&L}if(A&&F!==0)A.words[A.length++]=F;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},G.prototype.ishrn=function(W,U,K){return Z(this.negative===0),this.iushrn(W,U,K)},G.prototype.shln=function(W){return this.clone().ishln(W)},G.prototype.ushln=function(W){return this.clone().iushln(W)},G.prototype.shrn=function(W){return this.clone().ishrn(W)},G.prototype.ushrn=function(W){return this.clone().iushrn(W)},G.prototype.testn=function(W){Z(typeof W==="number"&&W>=0);var U=W%26,K=(W-U)/26,M=1<<U;if(this.length<=K)return!1;var R=this.words[K];return!!(R&M)},G.prototype.imaskn=function(W){Z(typeof W==="number"&&W>=0);var U=W%26,K=(W-U)/26;if(Z(this.negative===0,"imaskn works only with positive numbers"),this.length<=K)return this;if(U!==0)K++;if(this.length=Math.min(K,this.length),U!==0){var M=67108863^67108863>>>U<<U;this.words[this.length-1]&=M}return this.strip()},G.prototype.maskn=function(W){return this.clone().imaskn(W)},G.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)},G.prototype._iaddn=function(W){this.words[0]+=W;for(var U=0;U<this.length&&this.words[U]>=67108864;U++)if(this.words[U]-=67108864,U===this.length-1)this.words[U+1]=1;else this.words[U+1]++;return this.length=Math.max(this.length,U+1),this},G.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 U=0;U<this.length&&this.words[U]<0;U++)this.words[U]+=67108864,this.words[U+1]-=1;return this.strip()},G.prototype.addn=function(W){return this.clone().iaddn(W)},G.prototype.subn=function(W){return this.clone().isubn(W)},G.prototype.iabs=function(){return this.negative=0,this},G.prototype.abs=function(){return this.clone().iabs()},G.prototype._ishlnsubmul=function(W,U,K){var M=W.length+K,R;this._expand(M);var P,L=0;for(R=0;R<W.length;R++){P=(this.words[R+K]|0)+L;var A=(W.words[R]|0)*U;P-=A&67108863,L=(P>>26)-(A/67108864|0),this.words[R+K]=P&67108863}for(;R<this.length-K;R++)P=(this.words[R+K]|0)+L,L=P>>26,this.words[R+K]=P&67108863;if(L===0)return this.strip();Z(L===-1),L=0;for(R=0;R<this.length;R++)P=-(this.words[R]|0)+L,L=P>>26,this.words[R]=P&67108863;return this.negative=1,this.strip()},G.prototype._wordDiv=function(W,U){var K=this.length-W.length,M=this.clone(),R=W,P=R.words[R.length-1]|0,L=this._countBits(P);if(K=26-L,K!==0)R=R.ushln(K),M.iushln(K),P=R.words[R.length-1]|0;var A=M.length-R.length,Q;if(U!=="mod"){Q=new G(null),Q.length=A+1,Q.words=Array(Q.length);for(var F=0;F<Q.length;F++)Q.words[F]=0}var k=M.clone()._ishlnsubmul(R,1,A);if(k.negative===0){if(M=k,Q)Q.words[A]=1}for(var x=A-1;x>=0;x--){var y=(M.words[R.length+x]|0)*67108864+(M.words[R.length+x-1]|0);y=Math.min(y/P|0,67108863),M._ishlnsubmul(R,y,x);while(M.negative!==0)if(y--,M.negative=0,M._ishlnsubmul(R,1,x),!M.isZero())M.negative^=1;if(Q)Q.words[x]=y}if(Q)Q.strip();if(M.strip(),U!=="div"&&K!==0)M.iushrn(K);return{div:Q||null,mod:M}},G.prototype.divmod=function(W,U,K){if(Z(!W.isZero()),this.isZero())return{div:new G(0),mod:new G(0)};var M,R,P;if(this.negative!==0&&W.negative===0){if(P=this.neg().divmod(W,U),U!=="mod")M=P.div.neg();if(U!=="div"){if(R=P.mod.neg(),K&&R.negative!==0)R.iadd(W)}return{div:M,mod:R}}if(this.negative===0&&W.negative!==0){if(P=this.divmod(W.neg(),U),U!=="mod")M=P.div.neg();return{div:M,mod:P.mod}}if((this.negative&W.negative)!==0){if(P=this.neg().divmod(W.neg(),U),U!=="div"){if(R=P.mod.neg(),K&&R.negative!==0)R.isub(W)}return{div:P.div,mod:R}}if(W.length>this.length||this.cmp(W)<0)return{div:new G(0),mod:this};if(W.length===1){if(U==="div")return{div:this.divn(W.words[0]),mod:null};if(U==="mod")return{div:null,mod:new G(this.modn(W.words[0]))};return{div:this.divn(W.words[0]),mod:new G(this.modn(W.words[0]))}}return this._wordDiv(W,U)},G.prototype.div=function(W){return this.divmod(W,"div",!1).div},G.prototype.mod=function(W){return this.divmod(W,"mod",!1).mod},G.prototype.umod=function(W){return this.divmod(W,"mod",!0).mod},G.prototype.divRound=function(W){var U=this.divmod(W);if(U.mod.isZero())return U.div;var K=U.div.negative!==0?U.mod.isub(W):U.mod,M=W.ushrn(1),R=W.andln(1),P=K.cmp(M);if(P<0||R===1&&P===0)return U.div;return U.div.negative!==0?U.div.isubn(1):U.div.iaddn(1)},G.prototype.modn=function(W){Z(W<=67108863);var U=67108864%W,K=0;for(var M=this.length-1;M>=0;M--)K=(U*K+(this.words[M]|0))%W;return K},G.prototype.idivn=function(W){Z(W<=67108863);var U=0;for(var K=this.length-1;K>=0;K--){var M=(this.words[K]|0)+U*67108864;this.words[K]=M/W|0,U=M%W}return this.strip()},G.prototype.divn=function(W){return this.clone().idivn(W)},G.prototype.egcd=function(W){Z(W.negative===0),Z(!W.isZero());var U=this,K=W.clone();if(U.negative!==0)U=U.umod(W);else U=U.clone();var M=new G(1),R=new G(0),P=new G(0),L=new G(1),A=0;while(U.isEven()&&K.isEven())U.iushrn(1),K.iushrn(1),++A;var Q=K.clone(),F=U.clone();while(!U.isZero()){for(var k=0,x=1;(U.words[0]&x)===0&&k<26;++k,x<<=1);if(k>0){U.iushrn(k);while(k-- >0){if(M.isOdd()||R.isOdd())M.iadd(Q),R.isub(F);M.iushrn(1),R.iushrn(1)}}for(var y=0,u=1;(K.words[0]&u)===0&&y<26;++y,u<<=1);if(y>0){K.iushrn(y);while(y-- >0){if(P.isOdd()||L.isOdd())P.iadd(Q),L.isub(F);P.iushrn(1),L.iushrn(1)}}if(U.cmp(K)>=0)U.isub(K),M.isub(P),R.isub(L);else K.isub(U),P.isub(M),L.isub(R)}return{a:P,b:L,gcd:K.iushln(A)}},G.prototype._invmp=function(W){Z(W.negative===0),Z(!W.isZero());var U=this,K=W.clone();if(U.negative!==0)U=U.umod(W);else U=U.clone();var M=new G(1),R=new G(0),P=K.clone();while(U.cmpn(1)>0&&K.cmpn(1)>0){for(var L=0,A=1;(U.words[0]&A)===0&&L<26;++L,A<<=1);if(L>0){U.iushrn(L);while(L-- >0){if(M.isOdd())M.iadd(P);M.iushrn(1)}}for(var Q=0,F=1;(K.words[0]&F)===0&&Q<26;++Q,F<<=1);if(Q>0){K.iushrn(Q);while(Q-- >0){if(R.isOdd())R.iadd(P);R.iushrn(1)}}if(U.cmp(K)>=0)U.isub(K),M.isub(R);else K.isub(U),R.isub(M)}var k;if(U.cmpn(1)===0)k=M;else k=R;if(k.cmpn(0)<0)k.iadd(W);return k},G.prototype.gcd=function(W){if(this.isZero())return W.abs();if(W.isZero())return this.abs();var U=this.clone(),K=W.clone();U.negative=0,K.negative=0;for(var M=0;U.isEven()&&K.isEven();M++)U.iushrn(1),K.iushrn(1);do{while(U.isEven())U.iushrn(1);while(K.isEven())K.iushrn(1);var R=U.cmp(K);if(R<0){var P=U;U=K,K=P}else if(R===0||K.cmpn(1)===0)break;U.isub(K)}while(!0);return K.iushln(M)},G.prototype.invm=function(W){return this.egcd(W).a.umod(W)},G.prototype.isEven=function(){return(this.words[0]&1)===0},G.prototype.isOdd=function(){return(this.words[0]&1)===1},G.prototype.andln=function(W){return this.words[0]&W},G.prototype.bincn=function(W){Z(typeof W==="number");var U=W%26,K=(W-U)/26,M=1<<U;if(this.length<=K)return this._expand(K+1),this.words[K]|=M,this;var R=M;for(var P=K;R!==0&&P<this.length;P++){var L=this.words[P]|0;L+=R,R=L>>>26,L&=67108863,this.words[P]=L}if(R!==0)this.words[P]=R,this.length++;return this},G.prototype.isZero=function(){return this.length===1&&this.words[0]===0},G.prototype.cmpn=function(W){var U=W<0;if(this.negative!==0&&!U)return-1;if(this.negative===0&&U)return 1;this.strip();var K;if(this.length>1)K=1;else{if(U)W=-W;Z(W<=67108863,"Number is too big");var M=this.words[0]|0;K=M===W?0:M<W?-1:1}if(this.negative!==0)return-K|0;return K},G.prototype.cmp=function(W){if(this.negative!==0&&W.negative===0)return-1;if(this.negative===0&&W.negative!==0)return 1;var U=this.ucmp(W);if(this.negative!==0)return-U|0;return U},G.prototype.ucmp=function(W){if(this.length>W.length)return 1;if(this.length<W.length)return-1;var U=0;for(var K=this.length-1;K>=0;K--){var M=this.words[K]|0,R=W.words[K]|0;if(M===R)continue;if(M<R)U=-1;else if(M>R)U=1;break}return U},G.prototype.gtn=function(W){return this.cmpn(W)===1},G.prototype.gt=function(W){return this.cmp(W)===1},G.prototype.gten=function(W){return this.cmpn(W)>=0},G.prototype.gte=function(W){return this.cmp(W)>=0},G.prototype.ltn=function(W){return this.cmpn(W)===-1},G.prototype.lt=function(W){return this.cmp(W)===-1},G.prototype.lten=function(W){return this.cmpn(W)<=0},G.prototype.lte=function(W){return this.cmp(W)<=0},G.prototype.eqn=function(W){return this.cmpn(W)===0},G.prototype.eq=function(W){return this.cmp(W)===0},G.red=function(W){return new o(W)},G.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)},G.prototype.fromRed=function(){return Z(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},G.prototype._forceRed=function(W){return this.red=W,this},G.prototype.forceRed=function(W){return Z(!this.red,"Already a number in reduction context"),this._forceRed(W)},G.prototype.redAdd=function(W){return Z(this.red,"redAdd works only with red numbers"),this.red.add(this,W)},G.prototype.redIAdd=function(W){return Z(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,W)},G.prototype.redSub=function(W){return Z(this.red,"redSub works only with red numbers"),this.red.sub(this,W)},G.prototype.redISub=function(W){return Z(this.red,"redISub works only with red numbers"),this.red.isub(this,W)},G.prototype.redShl=function(W){return Z(this.red,"redShl works only with red numbers"),this.red.shl(this,W)},G.prototype.redMul=function(W){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,W),this.red.mul(this,W)},G.prototype.redIMul=function(W){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,W),this.red.imul(this,W)},G.prototype.redSqr=function(){return Z(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},G.prototype.redISqr=function(){return Z(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},G.prototype.redSqrt=function(){return Z(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},G.prototype.redInvm=function(){return Z(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},G.prototype.redNeg=function(){return Z(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},G.prototype.redPow=function(W){return Z(this.red&&!W.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,W)};var w={k256:null,p224:null,p192:null,p25519:null};function N(q,W){this.name=q,this.p=new G(W,16),this.n=this.p.bitLength(),this.k=new G(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}N.prototype._tmp=function(){var W=new G(null);return W.words=Array(Math.ceil(this.n/13)),W},N.prototype.ireduce=function(W){var U=W,K;do this.split(U,this.tmp),U=this.imulK(U),U=U.iadd(this.tmp),K=U.bitLength();while(K>this.n);var M=K<this.n?-1:U.ucmp(this.p);if(M===0)U.words[0]=0,U.length=1;else if(M>0)U.isub(this.p);else if(U.strip!==void 0)U.strip();else U._strip();return U},N.prototype.split=function(W,U){W.iushrn(this.n,0,U)},N.prototype.imulK=function(W){return W.imul(this.k)};function p(){N.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}X(p,N),p.prototype.split=function(W,U){var K=4194303,M=Math.min(W.length,9);for(var R=0;R<M;R++)U.words[R]=W.words[R];if(U.length=M,W.length<=9){W.words[0]=0,W.length=1;return}var P=W.words[9];U.words[U.length++]=P&K;for(R=10;R<W.length;R++){var L=W.words[R]|0;W.words[R-10]=(L&K)<<4|P>>>22,P=L}if(P>>>=22,W.words[R-10]=P,P===0&&W.length>10)W.length-=10;else W.length-=9},p.prototype.imulK=function(W){W.words[W.length]=0,W.words[W.length+1]=0,W.length+=2;var U=0;for(var K=0;K<W.length;K++){var M=W.words[K]|0;U+=M*977,W.words[K]=U&67108863,U=M*64+(U/67108864|0)}if(W.words[W.length-1]===0){if(W.length--,W.words[W.length-1]===0)W.length--}return W};function v(){N.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}X(v,N);function b(){N.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}X(b,N);function r(){N.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}X(r,N),r.prototype.imulK=function(W){var U=0;for(var K=0;K<W.length;K++){var M=(W.words[K]|0)*19+U,R=M&67108863;M>>>=26,W.words[K]=R,U=M}if(U!==0)W.words[W.length++]=U;return W},G._prime=function(W){if(w[W])return w[W];var U;if(W==="k256")U=new p;else if(W==="p224")U=new v;else if(W==="p192")U=new b;else if(W==="p25519")U=new r;else throw Error("Unknown prime "+W);return w[W]=U,U};function o(q){if(typeof q==="string"){var W=G._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}o.prototype._verify1=function(W){Z(W.negative===0,"red works only with positives"),Z(W.red,"red works only with red numbers")},o.prototype._verify2=function(W,U){Z((W.negative|U.negative)===0,"red works only with positives"),Z(W.red&&W.red===U.red,"red works only with red numbers")},o.prototype.imod=function(W){if(this.prime)return this.prime.ireduce(W)._forceRed(this);return W.umod(this.m)._forceRed(this)},o.prototype.neg=function(W){if(W.isZero())return W.clone();return this.m.sub(W)._forceRed(this)},o.prototype.add=function(W,U){this._verify2(W,U);var K=W.add(U);if(K.cmp(this.m)>=0)K.isub(this.m);return K._forceRed(this)},o.prototype.iadd=function(W,U){this._verify2(W,U);var K=W.iadd(U);if(K.cmp(this.m)>=0)K.isub(this.m);return K},o.prototype.sub=function(W,U){this._verify2(W,U);var K=W.sub(U);if(K.cmpn(0)<0)K.iadd(this.m);return K._forceRed(this)},o.prototype.isub=function(W,U){this._verify2(W,U);var K=W.isub(U);if(K.cmpn(0)<0)K.iadd(this.m);return K},o.prototype.shl=function(W,U){return this._verify1(W),this.imod(W.ushln(U))},o.prototype.imul=function(W,U){return this._verify2(W,U),this.imod(W.imul(U))},o.prototype.mul=function(W,U){return this._verify2(W,U),this.imod(W.mul(U))},o.prototype.isqr=function(W){return this.imul(W,W.clone())},o.prototype.sqr=function(W){return this.mul(W,W)},o.prototype.sqrt=function(W){if(W.isZero())return W.clone();var U=this.m.andln(3);if(Z(U%2===1),U===3){var K=this.m.add(new G(1)).iushrn(2);return this.pow(W,K)}var M=this.m.subn(1),R=0;while(!M.isZero()&&M.andln(1)===0)R++,M.iushrn(1);Z(!M.isZero());var P=new G(1).toRed(this),L=P.redNeg(),A=this.m.subn(1).iushrn(1),Q=this.m.bitLength();Q=new G(2*Q*Q).toRed(this);while(this.pow(Q,A).cmp(L)!==0)Q.redIAdd(L);var F=this.pow(Q,M),k=this.pow(W,M.addn(1).iushrn(1)),x=this.pow(W,M),y=R;while(x.cmp(P)!==0){var u=x;for(var l=0;u.cmp(P)!==0;l++)u=u.redSqr();Z(l<y);var e=this.pow(F,new G(1).iushln(y-l-1));k=k.redMul(e),F=e.redSqr(),x=x.redMul(F),y=l}return k},o.prototype.invm=function(W){var U=W._invmp(this.m);if(U.negative!==0)return U.negative=0,this.imod(U).redNeg();else return this.imod(U)},o.prototype.pow=function(W,U){if(U.isZero())return new G(1).toRed(this);if(U.cmpn(1)===0)return W.clone();var K=4,M=Array(1<<K);M[0]=new G(1).toRed(this),M[1]=W;for(var R=2;R<M.length;R++)M[R]=this.mul(M[R-1],W);var P=M[0],L=0,A=0,Q=U.bitLength()%26;if(Q===0)Q=26;for(R=U.length-1;R>=0;R--){var F=U.words[R];for(var k=Q-1;k>=0;k--){var x=F>>k&1;if(P!==M[0])P=this.sqr(P);if(x===0&&L===0){A=0;continue}if(L<<=1,L|=x,A++,A!==K&&(R!==0||k!==0))continue;P=this.mul(P,M[L]),A=0,L=0}Q=26}return P},o.prototype.convertTo=function(W){var U=W.umod(this.m);return U===W?U.clone():U},o.prototype.convertFrom=function(W){var U=W.clone();return U.red=null,U},G.mont=function(W){return new u0(W)};function u0(q){if(o.call(this,q),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new G(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,o),u0.prototype.convertTo=function(W){return this.imod(W.ushln(this.shift))},u0.prototype.convertFrom=function(W){var U=this.imod(W.mul(this.rinv));return U.red=null,U},u0.prototype.imul=function(W,U){if(W.isZero()||U.isZero())return W.words[0]=0,W.length=1,W;var K=W.imul(U),M=K.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),R=K.isub(M).iushrn(this.shift),P=R;if(R.cmp(this.m)>=0)P=R.isub(this.m);else if(R.cmpn(0)<0)P=R.iadd(this.m);return P._forceRed(this)},u0.prototype.mul=function(W,U){if(W.isZero()||U.isZero())return new G(0)._forceRed(this);var K=W.mul(U),M=K.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),R=K.isub(M).iushrn(this.shift),P=R;if(R.cmp(this.m)>=0)P=R.isub(this.m);else if(R.cmpn(0)<0)P=R.iadd(this.m);return P._forceRed(this)},u0.prototype.invm=function(W){var U=this.imod(W._invmp(this.m).mul(this.r2));return U._forceRed(this)}})(typeof ZX>"u"||ZX,p1)});var u1=s((a5,GX)=>{if(typeof Object.create==="function")GX.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 GX.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 B$=s((e5,YX)=>{try{if(yJ=M$("util"),typeof yJ.inherits!=="function")throw"";YX.exports=yJ.inherits}catch($){YX.exports=u1()}var yJ});var gJ=s(($U,n1)=>{var fJ=M$("buffer"),u$=fJ.Buffer,t0={},a0;for(a0 in fJ){if(!fJ.hasOwnProperty(a0))continue;if(a0==="SlowBuffer"||a0==="Buffer")continue;t0[a0]=fJ[a0]}var n$=t0.Buffer={};for(a0 in u$){if(!u$.hasOwnProperty(a0))continue;if(a0==="allocUnsafe"||a0==="allocUnsafeSlow")continue;n$[a0]=u$[a0]}t0.Buffer.prototype=u$.prototype;if(!n$.from||n$.from===Uint8Array.from)n$.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(!n$.alloc)n$.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(!t0.kStringMaxLength)try{t0.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch($){}if(!t0.constants){if(t0.constants={MAX_LENGTH:t0.kMaxLength},t0.kStringMaxLength)t0.constants.MAX_STRING_LENGTH=t0.kStringMaxLength}n1.exports=t0});var hJ=s((JQ)=>{var $Q=B$();function e0($){this._reporterState={obj:null,path:[],options:$||{},errors:[]}}JQ.Reporter=e0;e0.prototype.isError=function(J){return J instanceof m$};e0.prototype.save=function(){let J=this._reporterState;return{obj:J.obj,pathLen:J.path.length}};e0.prototype.restore=function(J){let Z=this._reporterState;Z.obj=J.obj,Z.path=Z.path.slice(0,J.pathLen)};e0.prototype.enterKey=function(J){return this._reporterState.path.push(J)};e0.prototype.exitKey=function(J){let Z=this._reporterState;Z.path=Z.path.slice(0,J-1)};e0.prototype.leaveKey=function(J,Z,X){let G=this._reporterState;if(this.exitKey(J),G.obj!==null)G.obj[Z]=X};e0.prototype.path=function(){return this._reporterState.path.join("/")};e0.prototype.enterObject=function(){let J=this._reporterState,Z=J.obj;return J.obj={},Z};e0.prototype.leaveObject=function(J){let Z=this._reporterState,X=Z.obj;return Z.obj=J,X};e0.prototype.error=function(J){let Z,X=this._reporterState,G=J instanceof m$;if(G)Z=J;else Z=new m$(X.path.map(function(Y){return"["+JSON.stringify(Y)+"]"}).join(""),J.message||J,J.stack);if(!X.options.partial)throw Z;if(!G)X.errors.push(Z);return Z};e0.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 m$($,J){this.path=$,this.rethrow(J)}$Q(m$,Error);m$.prototype.rethrow=function(J){if(this.message=J+" at: "+(this.path||"(shallow)"),Error.captureStackTrace)Error.captureStackTrace(this,m$);if(!this.stack)try{throw Error(this.message)}catch(Z){this.stack=Z.stack}return this}});var o$=s((GQ)=>{var XQ=B$(),bJ=hJ().Reporter,d$=gJ().Buffer;function $$($,J){if(bJ.call(this,J),!d$.isBuffer($)){this.error("Input not Buffer");return}this.base=$,this.offset=0,this.length=$.length}XQ($$,bJ);GQ.DecoderBuffer=$$;$$.isDecoderBuffer=function(J){if(J instanceof $$)return!0;return typeof J==="object"&&d$.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"};$$.prototype.save=function(){return{offset:this.offset,reporter:bJ.prototype.save.call(this)}};$$.prototype.restore=function(J){let Z=new $$(this.base);return Z.offset=J.offset,Z.length=this.offset,this.offset=J.offset,bJ.prototype.restore.call(this,J.reporter),Z};$$.prototype.isEmpty=function(){return this.offset===this.length};$$.prototype.readUInt8=function(J){if(this.offset+1<=this.length)return this.base.readUInt8(this.offset++,!0);else return this.error(J||"DecoderBuffer overrun")};$$.prototype.skip=function(J,Z){if(!(this.offset+J<=this.length))return this.error(Z||"DecoderBuffer overrun");let X=new $$(this.base);return X._reporterState=this._reporterState,X.offset=this.offset,X.length=this.offset+J,this.offset+=J,X};$$.prototype.raw=function(J){return this.base.slice(J?J.offset:this.offset,this.length)};function s$($,J){if(Array.isArray($))this.length=0,this.value=$.map(function(Z){if(!s$.isEncoderBuffer(Z))Z=new s$(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=d$.byteLength($);else if(d$.isBuffer($))this.value=$,this.length=$.length;else return J.error("Unsupported type: "+typeof $)}GQ.EncoderBuffer=s$;s$.isEncoderBuffer=function(J){if(J instanceof s$)return!0;return typeof J==="object"&&J.constructor.name==="EncoderBuffer"&&typeof J.length==="number"&&typeof J.join==="function"};s$.prototype.join=function(J,Z){if(!J)J=d$.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(d$.isBuffer(this.value))this.value.copy(J,Z);Z+=this.length}return J}});var s1=s((XU,d1)=>{d1.exports=m1;function m1($,J){if(!$)throw Error(J||"Assertion failed")}m1.equal=function(J,Z,X){if(J!=Z)throw Error(X||"Assertion failed: "+J+" != "+Z)}});var cJ=s((GU,l1)=>{var HQ=hJ().Reporter,QQ=o$().EncoderBuffer,zQ=o$().DecoderBuffer,o0=s1(),o1=["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"],UQ=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(o1),VQ=["_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()}l1.exports=t;var OQ=["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={};OQ.forEach(function(G){Z[G]=J[G]});let X=new this.constructor(Z.parent);return X._baseState=Z,X};t.prototype._wrap=function(){let J=this._baseState;UQ.forEach(function(Z){this[Z]=function(){let G=new this.constructor(this);return J.children.push(G),G[Z].apply(G,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(G){return G instanceof this.constructor},this);if(J=J.filter(function(G){return!(G instanceof this.constructor)},this),X.length!==0)o0(Z.children===null),Z.children=X,X.forEach(function(G){G._baseState.parent=this},this);if(J.length!==0)o0(Z.args===null),Z.args=J,Z.reverseArgs=J.map(function(G){if(typeof G!=="object"||G.constructor!==Object)return G;let Y={};return Object.keys(G).forEach(function(H){if(H==(H|0))H|=0;let z=G[H];Y[z]=H}),Y})};VQ.forEach(function($){t.prototype[$]=function(){let Z=this._baseState;throw Error($+" not implemented for encoding: "+Z.enc)}});o1.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 G=X.default,Y=!0,H=null;if(X.key!==null)H=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 O=J.save();try{if(X.choice===null)this._decodeGeneric(X.tag,J,Z);else this._decodeChoice(J,Z);Y=!0}catch(_){Y=!1}J.restore(O)}else if(Y=this._peekTag(J,V,X.any),J.isError(Y))return Y}let z;if(X.obj&&Y)z=J.enterObject();if(Y){if(X.explicit!==null){let O=this._decodeTag(J,X.explicit);if(J.isError(O))return O;J=O}let V=J.offset;if(X.use===null&&X.choice===null){let O;if(X.any)O=J.save();let _=this._decodeTag(J,X.implicit!==null?X.implicit:X.tag,X.any);if(J.isError(_))return _;if(X.any)G=J.raw(O);else J=_}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)G=this._decodeGeneric(X.tag,J,Z);else G=this._decodeChoice(J,Z);if(J.isError(G))return G;if(!X.any&&X.choice===null&&X.children!==null)X.children.forEach(function(_){_._decode(J,Z)});if(X.contains&&(X.tag==="octstr"||X.tag==="bitstr")){let O=new zQ(G);G=this._getUse(X.contains,J._reporterState.obj)._decode(O,Z)}}if(X.obj&&Y)G=J.leaveObject(z);if(X.key!==null&&(G!==null||Y===!0))J.leaveKey(H,X.key,G);else if(H!==null)J.exitKey(H);return G};t.prototype._decodeGeneric=function(J,Z,X){let G=this._baseState;if(J==="seq"||J==="set")return null;if(J==="seqof"||J==="setof")return this._decodeList(Z,J,G.args[0],X);else if(/str$/.test(J))return this._decodeStr(Z,J,X);else if(J==="objid"&&G.args)return this._decodeObjid(Z,G.args[0],G.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,G.args&&G.args[0],X);if(G.use!==null)return this._getUse(G.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,G=null,Y=!1;if(Object.keys(X.choice).some(function(H){let z=J.save(),V=X.choice[H];try{let O=V._decode(J,Z);if(J.isError(O))return!1;G={type:H,value:O},Y=!0}catch(O){return J.restore(z),!1}return!0},this),!Y)return J.error("Choice not matched");return G};t.prototype._createEncoderBuffer=function(J){return new QQ(J,this.reporter)};t.prototype._encode=function(J,Z,X){let G=this._baseState;if(G.default!==null&&G.default===J)return;let Y=this._encodeValue(J,Z,X);if(Y===void 0)return;if(this._skipDefault(Y,Z,X))return;return Y};t.prototype._encodeValue=function(J,Z,X){let G=this._baseState;if(G.parent===null)return G.children[0]._encode(J,Z||new HQ);let Y=null;if(this.reporter=Z,G.optional&&J===void 0)if(G.default!==null)J=G.default;else return;let H=null,z=!1;if(G.any)Y=this._createEncoderBuffer(J);else if(G.choice)Y=this._encodeChoice(J,Z);else if(G.contains)H=this._getUse(G.contains,X)._encode(J,Z),z=!0;else if(G.children)H=G.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 O=Z.enterKey(V._baseState.key);if(typeof J!=="object")return Z.error("Child expected, but input is not object");let _=V._encode(J[V._baseState.key],Z,J);return Z.leaveKey(O),_},this).filter(function(V){return V}),H=this._createEncoderBuffer(H);else if(G.tag==="seqof"||G.tag==="setof"){if(!(G.args&&G.args.length===1))return Z.error("Too many args for : "+G.tag);if(!Array.isArray(J))return Z.error("seqof/setof, but data is not Array");let V=this.clone();V._baseState.implicit=null,H=this._createEncoderBuffer(J.map(function(O){let _=this._baseState;return this._getUse(_.args[0],J)._encode(O,Z)},V))}else if(G.use!==null)Y=this._getUse(G.use,X)._encode(J,Z);else H=this._encodePrimitive(G.tag,J),z=!0;if(!G.any&&G.choice===null){let V=G.implicit!==null?G.implicit:G.tag,O=G.implicit===null?"universal":"context";if(V===null){if(G.use===null)Z.error("Tag could be omitted only for .use()")}else if(G.use===null)Y=this._encodeComposite(V,z,O,H)}if(G.explicit!==null)Y=this._encodeComposite(G.explicit,!1,"context",Y);return Y};t.prototype._encodeChoice=function(J,Z){let X=this._baseState,G=X.choice[J.type];if(!G)o0(!1,J.type+" not found in "+JSON.stringify(Object.keys(X.choice)));return G._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 pJ=s((KQ)=>{function r1($){let J={};return Object.keys($).forEach(function(Z){if((Z|0)==Z)Z=Z|0;let X=$[Z];J[X]=Z}),J}KQ.tagClass={0:"universal",1:"application",2:"context",3:"private"};KQ.tagClassByName=r1(KQ.tagClass);KQ.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"};KQ.tagByName=r1(KQ.tag)});var HX=s((WU,$Y)=>{var AQ=B$(),V$=gJ().Buffer,a1=cJ(),WX=pJ();function e1($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new Z$,this.tree._init($.body)}$Y.exports=e1;e1.prototype.encode=function(J,Z){return this.tree._encode(J,Z).join()};function Z$($){a1.call(this,"der",$)}AQ(Z$,a1);Z$.prototype._encodeComposite=function(J,Z,X,G){let Y=FQ(J,Z,X,this.reporter);if(G.length<128){let V=V$.alloc(2);return V[0]=Y,V[1]=G.length,this._createEncoderBuffer([V,G])}let H=1;for(let V=G.length;V>=256;V>>=8)H++;let z=V$.alloc(2+H);z[0]=Y,z[1]=128|H;for(let V=1+H,O=G.length;O>0;V--,O>>=8)z[V]=O&255;return this._createEncoderBuffer([z,G])};Z$.prototype._encodeStr=function(J,Z){if(Z==="bitstr")return this._createEncoderBuffer([J.unused|0,J.data]);else if(Z==="bmpstr"){let X=V$.alloc(J.length*2);for(let G=0;G<J.length;G++)X.writeUInt16BE(J.charCodeAt(G),G*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")};Z$.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 z=0;z<J.length;z++)J[z]|=0}else if(Array.isArray(J)){J=J.slice();for(let z=0;z<J.length;z++)J[z]|=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 G=0;for(let z=0;z<J.length;z++){let V=J[z];for(G++;V>=128;V>>=7)G++}let Y=V$.alloc(G),H=Y.length-1;for(let z=J.length-1;z>=0;z--){let V=J[z];Y[H--]=V&127;while((V>>=7)>0)Y[H--]=128|V&127}return this._createEncoderBuffer(Y)};function J$($){if($<10)return"0"+$;else return $}Z$.prototype._encodeTime=function(J,Z){let X,G=new Date(J);if(Z==="gentime")X=[J$(G.getUTCFullYear()),J$(G.getUTCMonth()+1),J$(G.getUTCDate()),J$(G.getUTCHours()),J$(G.getUTCMinutes()),J$(G.getUTCSeconds()),"Z"].join("");else if(Z==="utctime")X=[J$(G.getUTCFullYear()%100),J$(G.getUTCMonth()+1),J$(G.getUTCDate()),J$(G.getUTCHours()),J$(G.getUTCMinutes()),J$(G.getUTCSeconds()),"Z"].join("");else this.reporter.error("Encoding "+Z+" time is not supported yet");return this._encodeStr(X,"octstr")};Z$.prototype._encodeNull=function(){return this._createEncoderBuffer("")};Z$.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"&&!V$.isBuffer(J)){let Y=J.toArray();if(!J.sign&&Y[0]&128)Y.unshift(0);J=V$.from(Y)}if(V$.isBuffer(J)){let Y=J.length;if(J.length===0)Y++;let H=V$.alloc(Y);if(J.copy(H),J.length===0)H[0]=0;return this._createEncoderBuffer(H)}if(J<128)return this._createEncoderBuffer(J);if(J<256)return this._createEncoderBuffer([0,J]);let X=1;for(let Y=J;Y>=256;Y>>=8)X++;let G=Array(X);for(let Y=G.length-1;Y>=0;Y--)G[Y]=J&255,J>>=8;if(G[0]&128)G.unshift(0);return this._createEncoderBuffer(V$.from(G))};Z$.prototype._encodeBool=function(J){return this._createEncoderBuffer(J?255:0)};Z$.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getEncoder("der").tree};Z$.prototype._skipDefault=function(J,Z,X){let G=this._baseState,Y;if(G.default===null)return!1;let H=J.join();if(G.defaultBuffer===void 0)G.defaultBuffer=this._encodeValue(G.default,Z,X).join();if(H.length!==G.defaultBuffer.length)return!1;for(Y=0;Y<H.length;Y++)if(H[Y]!==G.defaultBuffer[Y])return!1;return!0};function FQ($,J,Z,X){let G;if($==="seqof")$="seq";else if($==="setof")$="set";if(WX.tagByName.hasOwnProperty($))G=WX.tagByName[$];else if(typeof $==="number"&&($|0)===$)G=$;else return X.error("Unknown tag: "+$);if(G>=31)return X.error("Multi-octet tag encoding unsupported");if(!J)G|=32;return G|=WX.tagClassByName[Z||"universal"]<<6,G}});var ZY=s((HU,JY)=>{var RQ=B$(),QX=HX();function zX($){QX.call(this,$),this.enc="pem"}RQ(zX,QX);JY.exports=zX;zX.prototype.encode=function(J,Z){let G=QX.prototype.encode.call(this,J).toString("base64"),Y=["-----BEGIN "+Z.label+"-----"];for(let H=0;H<G.length;H+=64)Y.push(G.slice(H,H+64));return Y.push("-----END "+Z.label+"-----"),Y.join(`
6
- `)}});var UX=s((GY)=>{var XY=GY;XY.der=HX();XY.pem=ZY()});var OX=s((zU,UY)=>{var IQ=B$(),qQ=XX(),YY=o$().DecoderBuffer,HY=cJ(),WY=pJ();function QY($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new r0,this.tree._init($.body)}UY.exports=QY;QY.prototype.decode=function(J,Z){if(!YY.isDecoderBuffer(J))J=new YY(J,Z);return this.tree._decode(J,Z)};function r0($){HY.call(this,"der",$)}IQ(r0,HY);r0.prototype._peekTag=function(J,Z,X){if(J.isEmpty())return!1;let G=J.save(),Y=VX(J,'Failed to peek tag: "'+Z+'"');if(J.isError(Y))return Y;return J.restore(G),Y.tag===Z||Y.tagStr===Z||Y.tagStr+"of"===Z||X};r0.prototype._decodeTag=function(J,Z,X){let G=VX(J,'Failed to decode tag of "'+Z+'"');if(J.isError(G))return G;let Y=zY(J,G.primitive,'Failed to get length of "'+Z+'"');if(J.isError(Y))return Y;if(!X&&G.tag!==Z&&G.tagStr!==Z&&G.tagStr+"of"!==Z)return J.error('Failed to match tag: "'+Z+'"');if(G.primitive||Y!==null)return J.skip(Y,'Failed to match body of: "'+Z+'"');let H=J.save(),z=this._skipUntilEnd(J,'Failed to skip indefinite length body: "'+this.tag+'"');if(J.isError(z))return z;return Y=J.offset-H.offset,J.restore(H),J.skip(Y,'Failed to match body of: "'+Z+'"')};r0.prototype._skipUntilEnd=function(J,Z){for(;;){let X=VX(J,Z);if(J.isError(X))return X;let G=zY(J,X.primitive,Z);if(J.isError(G))return G;let Y;if(X.primitive||G!==null)Y=J.skip(G);else Y=this._skipUntilEnd(J,Z);if(J.isError(Y))return Y;if(X.tagStr==="end")break}};r0.prototype._decodeList=function(J,Z,X,G){let Y=[];while(!J.isEmpty()){let H=this._peekTag(J,"end");if(J.isError(H))return H;let z=X.decode(J,"der",G);if(J.isError(z)&&H)break;Y.push(z)}return Y};r0.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 G="";for(let Y=0;Y<X.length/2;Y++)G+=String.fromCharCode(X.readUInt16BE(Y*2));return G}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")};r0.prototype._decodeObjid=function(J,Z,X){let G,Y=[],H=0,z=0;while(!J.isEmpty())if(z=J.readUInt8(),H<<=7,H|=z&127,(z&128)===0)Y.push(H),H=0;if(z&128)Y.push(H);let V=Y[0]/40|0,O=Y[0]%40;if(X)G=Y;else G=[V,O].concat(Y.slice(1));if(Z){let _=Z[G.join(" ")];if(_===void 0)_=Z[G.join(".")];if(_!==void 0)G=_}return G};r0.prototype._decodeTime=function(J,Z){let X=J.raw().toString(),G,Y,H,z,V,O;if(Z==="gentime")G=X.slice(0,4)|0,Y=X.slice(4,6)|0,H=X.slice(6,8)|0,z=X.slice(8,10)|0,V=X.slice(10,12)|0,O=X.slice(12,14)|0;else if(Z==="utctime")if(G=X.slice(0,2)|0,Y=X.slice(2,4)|0,H=X.slice(4,6)|0,z=X.slice(6,8)|0,V=X.slice(8,10)|0,O=X.slice(10,12)|0,G<70)G=2000+G;else G=1900+G;else return J.error("Decoding "+Z+" time is not supported yet");return Date.UTC(G,Y-1,H,z,V,O,0)};r0.prototype._decodeNull=function(){return null};r0.prototype._decodeBool=function(J){let Z=J.readUInt8();if(J.isError(Z))return Z;else return Z!==0};r0.prototype._decodeInt=function(J,Z){let X=J.raw(),G=new qQ(X);if(Z)G=Z[G.toString(10)]||G;return G};r0.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getDecoder("der").tree};function VX($,J){let Z=$.readUInt8(J);if($.isError(Z))return Z;let X=WY.tagClass[Z>>6],G=(Z&32)===0;if((Z&31)===31){let H=Z;Z=0;while((H&128)===128){if(H=$.readUInt8(J),$.isError(H))return H;Z<<=7,Z|=H&127}}else Z&=31;let Y=WY.tag[Z];return{cls:X,primitive:G,tag:Z,tagStr:Y}}function zY($,J,Z){let X=$.readUInt8(Z);if($.isError(X))return X;if(!J&&X===128)return null;if((X&128)===0)return X;let G=X&127;if(G>4)return $.error("length octect is too long");X=0;for(let Y=0;Y<G;Y++){X<<=8;let H=$.readUInt8(Z);if($.isError(H))return H;X|=H}return X}});var OY=s((UU,VY)=>{var jQ=B$(),PQ=gJ().Buffer,KX=OX();function MX($){KX.call(this,$),this.enc="pem"}jQ(MX,KX);VY.exports=MX;MX.prototype.decode=function(J,Z){let X=J.toString().split(/[\r\n]+/g),G=Z.label.toUpperCase(),Y=/^-----(BEGIN|END) ([^-]+)-----$/,H=-1,z=-1;for(let _=0;_<X.length;_++){let I=X[_].match(Y);if(I===null)continue;if(I[2]!==G)continue;if(H===-1){if(I[1]!=="BEGIN")break;H=_}else{if(I[1]!=="END")break;z=_;break}}if(H===-1||z===-1)throw Error("PEM section not found for: "+G);let V=X.slice(H+1,z).join("");V.replace(/[^a-z0-9+/=]+/gi,"");let O=PQ.from(V,"base64");return KX.prototype.decode.call(this,O,Z)}});var _X=s((MY)=>{var KY=MY;KY.der=OX();KY.pem=OY()});var AY=s((_Y)=>{var BQ=UX(),LQ=_X(),SQ=B$(),CQ=_Y;CQ.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(G){this._initNamed(G,Z)}return SQ(X,J),X.prototype._initNamed=function(Y,H){J.call(this,Y,H)},new X(this)};l$.prototype._getDecoder=function(J){if(J=J||"der",!this.decoders.hasOwnProperty(J))this.decoders[J]=this._createNamed(LQ[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(BQ[J]);return this.encoders[J]};l$.prototype.encode=function(J,Z,X){return this._getEncoder(Z).encode(J,X)}});var RY=s((FY)=>{var uJ=FY;uJ.Reporter=hJ().Reporter;uJ.DecoderBuffer=o$().DecoderBuffer;uJ.EncoderBuffer=o$().EncoderBuffer;uJ.Node=cJ()});var jY=s((qY)=>{var IY=qY;IY._reverse=function(J){let Z={};return Object.keys(J).forEach(function(X){if((X|0)==X)X=X|0;let G=J[X];Z[G]=X}),Z};IY.der=pJ()});var BY=s((PY)=>{var r$=PY;r$.bignum=XX();r$.define=AY().define;r$.base=RY();r$.constants=jY();r$.decoders=_X();r$.encoders=UX()});var CY=s((AX,SY)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var nJ=M$("buffer"),Q$=nJ.Buffer;function LY($,J){for(var Z in $)J[Z]=$[Z]}if(Q$.from&&Q$.alloc&&Q$.allocUnsafe&&Q$.allocUnsafeSlow)SY.exports=nJ;else LY(nJ,AX),AX.Buffer=N$;function N$($,J,Z){return Q$($,J,Z)}N$.prototype=Object.create(Q$.prototype);LY(Q$,N$);N$.from=function($,J,Z){if(typeof $==="number")throw TypeError("Argument must not be a number");return Q$($,J,Z)};N$.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};N$.allocUnsafe=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return Q$($)};N$.allocUnsafeSlow=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return nJ.SlowBuffer($)}});var EY=s((AU,wY)=>{function FX($){var J=($/8|0)+($%8===0?0:1);return J}var wQ={ES256:FX(256),ES384:FX(384),ES512:FX(521)};function EQ($){var J=wQ[$];if(J)return J;throw Error('Unknown algorithm "'+$+'"')}wY.exports=EQ});var yY=s((FU,xY)=>{var mJ=CY().Buffer,NY=EY(),dJ=128,vY=0,TQ=32,NQ=16,vQ=2,DY=NQ|TQ|vY<<6,sJ=vQ|vY<<6;function DQ($){return $.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function kY($){if(mJ.isBuffer($))return $;else if(typeof $==="string")return mJ.from($,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function kQ($,J){$=kY($);var Z=NY(J),X=Z+1,G=$.length,Y=0;if($[Y++]!==DY)throw Error('Could not find expected "seq"');var H=$[Y++];if(H===(dJ|1))H=$[Y++];if(G-Y<H)throw Error('"seq" specified length of "'+H+'", only "'+(G-Y)+'" remaining');if($[Y++]!==sJ)throw Error('Could not find expected "int" for "r"');var z=$[Y++];if(G-Y-2<z)throw Error('"r" specified length of "'+z+'", only "'+(G-Y-2)+'" available');if(X<z)throw Error('"r" specified length of "'+z+'", max of "'+X+'" is acceptable');var V=Y;if(Y+=z,$[Y++]!==sJ)throw Error('Could not find expected "int" for "s"');var O=$[Y++];if(G-Y!==O)throw Error('"s" specified length of "'+O+'", expected "'+(G-Y)+'"');if(X<O)throw Error('"s" specified length of "'+O+'", max of "'+X+'" is acceptable');var _=Y;if(Y+=O,Y!==G)throw Error('Expected to consume entire buffer, but "'+(G-Y)+'" bytes remain');var I=Z-z,B=Z-O,S=mJ.allocUnsafe(I+z+B+O);for(Y=0;Y<I;++Y)S[Y]=0;$.copy(S,Y,V+Math.max(-I,0),V+z),Y=Z;for(var C=Y;Y<C+B;++Y)S[Y]=0;return $.copy(S,Y,_+Math.max(-B,0),_+O),S=S.toString("base64"),S=DQ(S),S}function TY($,J,Z){var X=0;while(J+X<Z&&$[J+X]===0)++X;var G=$[J+X]>=dJ;if(G)--X;return X}function xQ($,J){$=kY($);var Z=NY(J),X=$.length;if(X!==Z*2)throw TypeError('"'+J+'" signatures must be "'+Z*2+'" bytes, saw "'+X+'"');var G=TY($,0,Z),Y=TY($,Z,$.length),H=Z-G,z=Z-Y,V=2+H+1+1+z,O=V<dJ,_=mJ.allocUnsafe((O?2:3)+V),I=0;if(_[I++]=DY,O)_[I++]=V;else _[I++]=dJ|1,_[I++]=V&255;if(_[I++]=sJ,_[I++]=H,G<0)_[I++]=0,I+=$.copy(_,I,0,Z);else I+=$.copy(_,I,G,Z);if(_[I++]=sJ,_[I++]=z,Y<0)_[I++]=0,$.copy(_,I,Z);else $.copy(_,I,Z+Y);return _}xY.exports={derToJose:kQ,joseToDer:xQ}});var jX=s((RU,rY)=>{var qX=BY(),{createHmac:hY,createVerify:yQ,createSign:fQ,timingSafeEqual:gQ,createPublicKey:hQ,constants:{RSA_PKCS1_PSS_PADDING:bY,RSA_PSS_SALTLEN_DIGEST:cY,RSA_PKCS1_PADDING:pY,RSA_PSS_SALTLEN_MAX_SIGN:bQ,RSA_PSS_SALTLEN_AUTO:cQ},sign:fY,verify:gY}=M$("crypto"),{joseToDer:pQ,derToJose:uQ}=yY(),uY=JX(),{TokenError:J0}=p$(),nY=/[=+/]/g,nQ={"=":"","+":"-","/":"_"},mY=/^-----BEGIN(?: (RSA|EC|ENCRYPTED))? PRIVATE KEY-----/,dY=/^-----BEGIN(?: (RSA))? PUBLIC KEY-----/,oJ=new uY(1000),RX=new uY(1000),sY=["HS256","HS384","HS512"],mQ=["ES256","ES384","ES512"],IX=["RS256","RS384","RS512","PS256","PS384","PS512"],dQ=["EdDSA"],oY={"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"]}},sQ=qX.define("PrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),oQ=qX.define("PublicKey",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),lQ=qX.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 lY($){return nQ[$]}function HJ($,J,Z,X){return $.set(J,[Z,X]),Z||X}function rQ($){if($.match(dY)||$.includes("-----BEGIN CERTIFICATE-----"))throw new J0(J0.codes.invalidKey,"Public keys are not supported for signing.");let J=$.trim().match(mY);if(!J)return"HS256";let Z,X,G;switch(J[1]){case"RSA":return"RS256";case"EC":Z=lQ.decode($,"pem",{label:"EC PRIVATE KEY"}),G=Z.parameters.value.join(".");break;case"ENCRYPTED":return"ENCRYPTED";default:switch(Z=sQ.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":G=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 Y=oY[G];if(!Y)throw new J0(J0.codes.invalidKey,`Unsupported EC private key with curve ${G}.`);return`ES${Y.bits}`}function iQ($){let J=$.match(dY);if($.match(mY))throw new J0(J0.codes.invalidKey,"Private keys are not supported for verifying.");else if(J&&J[1]==="RSA")return IX;else if(!J&&!$.includes("-----BEGIN CERTIFICATE-----"))return sY;if($.includes("-----BEGIN CERTIFICATE-----"))$=hQ($).export({type:"spki",format:"pem"});let Z=oQ.decode($,"pem",{label:"PUBLIC KEY"}),X=Z.algorithm.algorithm.join("."),G;switch(X){case"1.2.840.113549.1.1.1":return IX;case"1.2.840.10045.2.1":G=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 Y=oY[G];if(!Y)throw new J0(J0.codes.invalidKey,`Unsupported EC public key with curve ${G}.`);return[`ES${Y.bits}`]}function tQ($,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]=oJ.get($)||[];if(Z)return Z;else if(X)throw X;try{let G=rQ($);if(G==="ENCRYPTED")return HJ(oJ,$,J);return HJ(oJ,$,G)}catch(G){throw HJ(oJ,$,null,J0.wrap(G,J0.codes.invalidKey,"Unsupported PEM private key."))}}function aQ($){if(!$)return"none";let[J,Z]=RX.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 HJ(RX,$,iQ($))}catch(X){throw HJ(RX,$,null,J0.wrap(X,J0.codes.invalidKey,"Unsupported PEM public key."))}}function eQ($,J,Z){try{let X=$.slice(0,2),G=`sha${$.slice(2)}`,Y,H;switch(X){case"HS":Y=hY(G,J).update(Z).digest("base64");break;case"ES":Y=uQ(fY(G,Buffer.from(Z,"utf-8"),J),$).toString("base64");break;case"RS":case"PS":if(H={key:J,padding:pY,saltLength:bQ},X==="PS")H.padding=bY,H.saltLength=cY;Y=fQ(G).update(Z).sign(H).toString("base64");break;case"Ed":Y=fY(void 0,Buffer.from(Z,"utf-8"),J).toString("base64")}return Y.replace(nY,lY)}catch(X){throw new J0(J0.codes.signError,"Cannot create the signature.",{originalError:X})}}function $z($,J,Z,X){try{let G=$.slice(0,2),Y=`SHA${$.slice(2)}`;if(X=Buffer.from(X,"base64"),G==="HS")try{return gQ(hY(Y,J).update(Z).digest(),X)}catch{return!1}else if(G==="Ed")if(typeof gY==="function")return gY(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 H={key:J,padding:pY,saltLength:cQ};if(G==="PS")H.padding=bY,H.saltLength=cY;else if(G==="ES")X=pQ(X,$);return yQ("RSA-"+Y).update(Z).verify(H,X)}catch(G){throw new J0(J0.codes.verifyError,"Cannot verify the signature.",{originalError:G})}}rY.exports={base64UrlMatcher:nY,base64UrlReplacer:lY,hsAlgorithms:sY,rsaAlgorithms:IX,esAlgorithms:mQ,edAlgorithms:dQ,detectPrivateKeyAlgorithm:tQ,detectPublicKeyAlgorithms:aQ,createSignature:eQ,verifySignature:$z}});var PX=s((IU,tY)=>{var{createHash:iY}=M$("crypto"),Jz=/"alg"\s*:\s*"[HERP]S(256|384)"/m,Zz=/"alg"\s*:\s*"EdDSA"/m,Xz=/"crv"\s*:\s*"Ed448"/m;function Gz($,J,Z){let X=$(J,Z);if(X&&typeof X.then==="function")X.then((G)=>{process.nextTick(()=>Z(null,G))}).catch(Z)}function Yz($){if(typeof $==="function")return[$];let J,Z,X=new Promise((G,Y)=>{J=G,Z=Y});return[function(G,Y){if(G)return Z(G);return J(Y)},X]}function Wz($){let J=$.split(".",1)[0],Z=Buffer.from(J,"base64").toString("utf-8"),X=null;if(Z.match(Zz)&&Z.match(Xz))X=iY("shake256",{outputLength:114});else{let G=Z.match(Jz);X=iY(`sha${G?G[1]:"512"}`)}return X.update($).digest("hex")}tY.exports={getAsyncKey:Gz,ensurePromiseCallback:Yz,hashToken:Wz}});var GW=s((qU,XW)=>{var{createPublicKey:Hz,createSecretKey:Qz}=M$("crypto"),zz=JX(),{hsAlgorithms:eY,verifySignature:Uz,detectPublicKeyAlgorithms:$W}=jX(),Vz=iZ(),{TokenError:n}=p$(),{getAsyncKey:Oz,ensurePromiseCallback:Kz,hashToken:Mz}=PX();function _z($,J){return $===J}function JW($,J){for(let Z of $)if(J.includes(Z))return;throw new n(n.codes.invalidKey,`Invalid public key provided for algorithms ${$.join(", ")}.`)}function ZW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J?Qz($):Hz($)}function QJ($){if(!Array.isArray($))$=[$];return $.filter((J)=>J).map((J)=>{if(J&&typeof J.test==="function")return J;return{test:_z.bind(null,J)}})}function Az($){let J=parseInt($===!0?1000:$,10);return J>0?new zz(J):null}function i$({cache:$,token:J,cacheTTL:Z,payload:X,ignoreExpiration:G,ignoreNotBefore:Y,maxAge:H,clockTimestamp:z=Date.now(),clockTolerance:V,errorCacheTTL:O,cacheKeyBuilder:_},I){if(!$)return I;let B=[I,0,0];if(I instanceof n){let T=typeof O==="function"?O(I):O;return B[2]=z+V+T,$.set(_(J),B),I}if(X&&typeof X.iat==="number"){if(B[1]=!Y&&typeof X.nbf==="number"?X.nbf*1000-V:0,!G){if(typeof X.exp==="number")B[2]=X.exp*1000+V;else if(H)B[2]=X.iat*1000+H+V}}let C=z+V+Z;return B[2]=B[2]===0?C:Math.min(B[2],C),$.set(_(J),B),I}function Fz($,J,Z){if($ instanceof n){if(!J)throw $;J($)}else{if(!J)return $;J(null,$)}return Z}function Rz($,J,Z,X,G){if(!G.includes(J.alg))throw new n(n.codes.invalidAlgorithm,"The token algorithm is invalid.");if(Z&&!Uz(J.alg,X,$,Z))throw new n(n.codes.invalidSignature,"The token signature is invalid.")}function Iz($,J,Z,X,G){let Y=Z?`The ${J} claim must be a ${G} or an array of ${G}s.`:`The ${J} claim must be a ${G}.`;if(X&&!Z)throw new n(n.codes.invalidClaimValue,Y);if($.map((H)=>typeof H).some((H)=>H!==G))throw new n(n.codes.invalidClaimType,Y)}function qz($,J,Z,X){let G=X?`None of ${J} claim values are allowed.`:`The ${J} claim value is not allowed.`;if(!$.some((Y)=>Z.some((H)=>H.test(Y))))throw new n(n.codes.invalidClaimValue,G)}function jz($,J,Z,X,G,Y){let H=$*1000+(J||0);if(!(X?Z>=H:Z<=H))throw new n(n.codes[G],`The token ${Y} at ${new Date(H).toISOString()}.`)}function aY($,{input:J,header:Z,payload:X,signature:G},{validators:Y,allowedAlgorithms:H,checkTyp:z,clockTimestamp:V,requiredClaims:O}){let _=$ instanceof Buffer?$.length:!!$;if(_&&!G)throw new n(n.codes.missingSignature,"The token signature is missing.");else if(!_&&G)throw new n(n.codes.missingKey,"The key option is missing.");if(Rz(J,Z,G,$,H),z&&(typeof Z.typ!=="string"||z!==Z.typ.toLowerCase().replace(/^application\//,"")))throw new n(n.codes.invalidType,"Invalid typ.");if(O){for(let B of O)if(!(B in X))throw new n(n.codes.missingRequiredClaim,`The ${B} claim is required.`)}let I=V||Date.now();for(let{type:B,claim:S,allowed:C,array:T,modifier:E,greater:D,errorCode:w,errorVerb:N}of Y){let p=X[S],v=Array.isArray(p),b=v?p:[p];if(!(S in X))continue;if(Iz(b,S,T,v,B==="date"?"number":"string"),B==="date")jz(p,E,I,D,w,N);else qz(b,S,C,v)}}function Pz({key:$,allowedAlgorithms:J,complete:Z,cacheTTL:X,checkTyp:G,clockTimestamp:Y,clockTolerance:H,ignoreExpiration:z,ignoreNotBefore:V,maxAge:O,isAsync:_,validators:I,decode:B,cache:S,requiredClaims:C,errorCacheTTL:T,cacheKeyBuilder:E},D,w){let[N,p]=_?Kz(w):[];if(S){let[U,K,M]=S.get(E(D))||[void 0,0,0],R=Y||Date.now();if(typeof U<"u"&&(K===0||R<K&&U.code==="FAST_JWT_INACTIVE"||R>=K&&U.code!=="FAST_JWT_INACTIVE")&&(M===0||R<=M))return Fz(U,N,p)}let v;try{v=B(D)}catch(U){if(N)return N(U),p;throw U}let{header:b,payload:r,signature:o,input:u0}=v,q={cache:S,token:D,cacheTTL:X,errorCacheTTL:T,ignoreExpiration:z,ignoreNotBefore:V,maxAge:O,clockTimestamp:Y,clockTolerance:H,payload:r,cacheKeyBuilder:E},W={validators:I,allowedAlgorithms:J,checkTyp:G,clockTimestamp:Y,clockTolerance:H,requiredClaims:C};if(!N)try{return aY($,v,W),i$(q,Z?{header:b,payload:r,signature:o,input:u0}:r)}catch(U){throw i$(q,U)}return Oz($,{header:b,payload:r,signature:o},(U,K)=>{if(U)return N(i$(q,n.wrap(U,n.codes.keyFetchingError,"Cannot fetch key.")));if(typeof K==="string")K=Buffer.from(K,"utf-8");else if(!(K instanceof Buffer))return N(i$(q,new n(n.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a public key.")));try{let M=$W(K);if(W.allowedAlgorithms.length)JW(J,M);else W.allowedAlgorithms=M;K=ZW(K,M[0]===eY[0]),aY(K,v,W)}catch(M){return N(i$(q,M))}N(null,i$(q,Z?{header:b,payload:r,signature:o,input:D}:r))}),p}XW.exports=function(J){let{key:Z,algorithms:X,complete:G,cache:Y,cacheTTL:H,errorCacheTTL:z,checkTyp:V,clockTimestamp:O,clockTolerance:_,ignoreExpiration:I,ignoreNotBefore:B,maxAge:S,allowedJti:C,allowedAud:T,allowedIss:E,allowedSub:D,allowedNonce:w,requiredClaims:N,cacheKeyBuilder:p}={cacheTTL:600000,clockTolerance:0,errorCacheTTL:-1,cacheKeyBuilder:Mz,...J};if(!Array.isArray(X))X=[];let v=typeof Z;if(v!=="string"&&v!=="object"&&v!=="function")throw new n(n.codes.INVALID_OPTION,"The key option must be a string, a buffer or a function returning the algorithm secret or public key.");if(Z&&v!=="function"){let q=$W(Z);if(X.length)JW(X,q);else X=q;Z=ZW(Z,q[0]===eY[0])}if(O&&(typeof O!=="number"||O<0))throw new n(n.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(_&&(typeof _!=="number"||_<0))throw new n(n.codes.invalidOption,"The clockTolerance option must be a positive number.");if(H&&(typeof H!=="number"||H<0))throw new n(n.codes.invalidOption,"The cacheTTL option must be a positive number.");if(z&&typeof z!=="function"&&typeof z!=="number"||z<-1)throw new n(n.codes.invalidOption,"The errorCacheTTL option must be a number greater than -1 or a function.");if(N&&!Array.isArray(N))throw new n(n.codes.invalidOption,"The requiredClaims option must be an array.");let b=[];if(!B)b.push({type:"date",claim:"nbf",errorCode:"inactive",errorVerb:"will be active",greater:!0,modifier:-_});if(!I)b.push({type:"date",claim:"exp",errorCode:"expired",errorVerb:"has expired",modifier:+_});if(typeof S==="number")b.push({type:"date",claim:"iat",errorCode:"expired",errorVerb:"has expired",modifier:S});if(C)b.push({type:"string",claim:"jti",allowed:QJ(C)});if(T)b.push({type:"string",claim:"aud",allowed:QJ(T),array:!0});if(E)b.push({type:"string",claim:"iss",allowed:QJ(E)});if(D)b.push({type:"string",claim:"sub",allowed:QJ(D)});if(w)b.push({type:"string",claim:"nonce",allowed:QJ(w)});let r=V?V.toLowerCase().replace(/^application\//,""):null,o={key:Z,allowedAlgorithms:X,complete:G,cacheTTL:H,errorCacheTTL:z,checkTyp:r,clockTimestamp:O,clockTolerance:_,ignoreExpiration:I,ignoreNotBefore:B,maxAge:S,isAsync:v==="function",validators:b,decode:Vz({complete:!0}),cache:Az(Y),requiredClaims:N,cacheKeyBuilder:p},u0=Pz.bind(null,o);return u0.cache=o.cache,u0}});var YW=s((Cz)=>{var Bz=/^(-?(?:\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?)?)?$/,lJ=1000,rJ=lJ*60,iJ=rJ*60,UJ=iJ*24,BX=UJ*365.25;function Lz($){var J,Z=$.toLowerCase().match(Bz);if(Z!=null&&(J=parseFloat(Z[1]))){if(Z[3]!=null)return J*lJ;if(Z[4]!=null)return J*rJ;if(Z[5]!=null)return J*iJ;if(Z[6]!=null)return J*UJ;if(Z[7]!=null)return J*UJ*7;if(Z[8]!=null)return J*BX;return J}}function zJ($,J,Z,X){var G=($|0)===$?$:~~($+0.5);return J+G+(X?" "+Z+(G!=1?"s":""):Z[0])}function Sz($,J){var Z=$<0?"-":"",X=$<0?-$:$;if(X<lJ)return $+(J?" ms":"ms");if(X<rJ)return zJ(X/lJ,Z,"second",J);if(X<iJ)return zJ(X/rJ,Z,"minute",J);if(X<UJ)return zJ(X/iJ,Z,"hour",J);if(X<BX)return zJ(X/UJ,Z,"day",J);return zJ(X/BX,Z,"year",J)}Cz.format=Sz;Cz.parse=Lz});var KW=s((PU,OW)=>{var{base64UrlMatcher:LX,base64UrlReplacer:SX,hsAlgorithms:Tz,esAlgorithms:Nz,rsaAlgorithms:vz,edAlgorithms:Dz,detectPrivateKeyAlgorithm:QW,createSignature:WW}=jX(),{TokenError:d}=p$(),{getAsyncKey:kz,ensurePromiseCallback:xz}=PX(),{createPrivateKey:yz,createSecretKey:fz}=M$("crypto"),{parse:HW}=YW(),zW=new Set([...Tz,...Nz,...vz,...Dz,"none"]),gz=Array.from(zW).join(", ");function UW($,J){let Z=$.slice(0,2),X=J.slice(0,2),G=!0;if(Z==="RS"||Z==="PS")G=X==="RS"||Z==="RS"&&J==="ENCRYPTED";else if(Z==="ES"||Z==="Ed")G=Z===X||Z==="ES"&&J==="ENCRYPTED";if(!G)throw new d(d.codes.invalidKey,`Invalid private key provided for algorithm ${$}.`)}function VW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J[0]==="H"?fz($):yz($)}function hz({key:$,algorithm:J,noTimestamp:Z,mutatePayload:X,clockTimestamp:G,expiresIn:Y,notBefore:H,kid:z,typ:V,isAsync:O,additionalHeader:_,fixedPayload:I},B,S){let[C,T]=O?xz(S):[];if(typeof B!=="object")throw new d(d.codes.invalidType,"The payload must be an object.");if(B.exp&&(!Number.isInteger(B.exp)||B.exp<0))throw new d(d.codes.invalidClaimValue,"The exp claim must be a positive integer.");let E={alg:J,typ:V||"JWT",kid:z,..._},D="",w=B.iat*1000||G||Date.now(),N={...B,...I,iat:Z?void 0:Math.floor(w/1000),exp:B.exp?B.exp:Y?Math.floor((w+Y)/1000):void 0,nbf:B.nbf?B.nbf:H?Math.floor((w+H)/1000):void 0};if(X)Object.assign(B,N);if(D=Buffer.from(JSON.stringify(N),"utf-8").toString("base64").replace(LX,SX),!C){let v=Buffer.from(JSON.stringify(E),"utf-8").toString("base64").replace(LX,SX)+"."+D,b=J==="none"?"":WW(J,$,v);return v+"."+b}return kz($,{header:E,payload:B},(p,v)=>{if(p){let r=d.wrap(p,d.codes.keyFetchingError,"Cannot fetch key.");return C(r)}if(typeof v==="string")v=Buffer.from(v,"utf-8");else if(!(v instanceof Buffer))return C(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 b;try{let r=QW(v,J);if(J)UW(J,r);else E.alg=J=r;v=VW(v,J);let u0=Buffer.from(JSON.stringify(E),"utf-8").toString("base64").replace(LX,SX)+"."+D;b=u0+"."+WW(J,v,u0)}catch(r){return C(r)}C(null,b)}),T}OW.exports=function(J){let{key:Z,algorithm:X,noTimestamp:G,mutatePayload:Y,clockTimestamp:H,expiresIn:z,notBefore:V,jti:O,aud:_,iss:I,sub:B,nonce:S,kid:C,typ:T,header:E}={clockTimestamp:0,...J};if(X&&!zW.has(X))throw new d(d.codes.invalidOption,`The algorithm option must be one of the following values: ${gz}.`);let D=typeof Z,w=D==="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||D!=="string"&&!(Z instanceof Buffer)&&D!=="function"&&!w)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(w&&!X)throw new d(d.codes.invalidAlgorithm,"When using password protected key you must provide the algorithm option.");if(Z&&D!=="function"){let v=QW(w?Z.key:Z,X);if(X)UW(X,v);else X=v;Z=VW(Z,X)}if(z){if(typeof z==="string")z=HW(z);if(typeof z!=="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=HW(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(H&&(typeof H!=="number"||H<0))throw new d(d.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(O&&typeof O!=="string")throw new d(d.codes.invalidOption,"The jti option must be a string.");if(_&&typeof _!=="string"&&!Array.isArray(_))throw new d(d.codes.invalidOption,"The aud option must be a string or an array of strings.");if(I&&typeof I!=="string")throw new d(d.codes.invalidOption,"The iss option must be a string.");if(B&&typeof B!=="string")throw new d(d.codes.invalidOption,"The sub option must be a string.");if(S&&typeof S!=="string")throw new d(d.codes.invalidOption,"The nonce option must be a string.");if(C&&typeof C!=="string")throw new d(d.codes.invalidOption,"The kid option must be a string.");if(E&&typeof E!=="object")throw new d(d.codes.invalidOption,"The header option must be a object.");let p=Object.entries({jti:O,aud:_,iss:I,sub:B,nonce:S}).reduce((v,[b,r])=>{if(r!==void 0)v[b]=r;return v},{});return hz.bind(null,{key:Z,algorithm:X,noTimestamp:G,mutatePayload:Y,clockTimestamp:H,expiresIn:z,notBefore:V,kid:C,typ:T,isAsync:D==="function",additionalHeader:E,fixedPayload:p})}});var _W=s((BU,MW)=>{var{TokenError:bz,TOKEN_ERROR_CODES:cz}=p$(),pz=iZ(),uz=GW(),nz=KW();MW.exports={TokenError:bz,TOKEN_ERROR_CODES:cz,createDecoder:pz,createVerifier:uz,createSigner:nz}});AJ();import{join as TZ}from"path";n0();function I$($){if(Array.isArray($)){let J=[];for(let Z of $)J.push(I$(Z));return J}if(i($)){let J={};for(let Z of Object.keys($))J[Z]=I$($[Z]);return J}return $}function HG($,J){if(J===void 0)return $;if(Array.isArray($)&&Array.isArray(J)){for(let Z of J)$.push(I$(Z));return $}if(i($)&&i(J)){for(let Z of Object.keys(J)){let X=J[Z];if(X===void 0)continue;let G=$[Z];if(Array.isArray(G)&&Array.isArray(X)){let Y=[];for(let H of G)Y.push(I$(H));for(let H of X)Y.push(I$(H));$[Z]=Y;continue}if(i(G)&&i(X)){$[Z]=HG(I$(G),X);continue}$[Z]=I$(X)}return $}return I$(J)}function QG(...$){let J={};for(let Z of $){if(Z===void 0)continue;J=HG(J,Z)}return J}var GH={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:20,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:{}};async function zG($){if($!=="development"&&$!=="production")throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1ANODE_ENV \u53EA\u80FD\u662F 'development' \u6216 'production'\uFF0C\u5F53\u524D\u503C=${String($)}`);let J=TZ(process.cwd(),"configs"),Z=await R$(TZ(J,"befly.common.json"),{}),X=await R$(TZ(J,`befly.${$}.json`),{}),G=QG(GH,Z,X);G.nodeEnv=$;let Y=G?.redis?.prefix;if(typeof Y==="string"){if(Y.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=${Y}`)}return G}a();n0();async function UG($){let J=!1;for(let Z of $)try{if(typeof Z?.name!=="string"||Z.name.trim()===""){j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 name \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32"})),J=!0;continue}if(typeof Z?.handler!=="function"){j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}if(typeof Z?.path!=="string"||Z.path.trim()==="")j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;else{let X=Z.path.trim();if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(X))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 path \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/"))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u5FC5\u987B\u4EE5 /api/ \u5F00\u5934"})),J=!0;if(X.includes(" "))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C"})),J=!0;if(X.includes("/api//"))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u51FA\u73B0 /api//\uFF08\u91CD\u590D\u659C\u6760\uFF09"})),J=!0}if(typeof Z?.routePrefix!=="string"||Z.routePrefix.trim()==="")j.warn(Object.assign({},c(Z,["handler"]),{msg:"\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()))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\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")j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 auth \u5C5E\u6027\u5FC5\u987B\u662F\u5E03\u5C14\u503C (true=\u9700\u767B\u5F55, false=\u516C\u5F00)"})),J=!0;if(Z.fields&&!i(Z.fields))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 fields \u5C5E\u6027\u5FC5\u987B\u662F\u5BF9\u8C61"})),J=!0;if(Z.required&&!Array.isArray(Z.required))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u6570\u7EC4"})),J=!0;if(Z.required&&Z.required.some((X)=>typeof X!=="string"))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0}catch(X){j.error({err:X,item:Z,msg:"\u63A5\u53E3\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u63A5\u53E3\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();n0();var VG=["name","enable","deps","handler"];async function OG($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let X of $)try{if(!i(X)){j.warn(Object.assign({},c(X,["handler"]),{msg:"\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()===""){j.warn(Object.assign({},c(X,["handler"]),{msg:"\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}let G=X.customKeys;if(!Array.isArray(G)){j.warn(Object.assign({},c(X,["handler"]),{msg:"\u94A9\u5B50\u626B\u63CF\u7ED3\u679C\u7F3A\u5C11 customKeys\uFF08\u65E0\u6CD5\u5224\u65AD\u7528\u6237\u5BFC\u51FA\u7684\u5B57\u6BB5\u662F\u5426\u5408\u6CD5\uFF09"})),J=!0;continue}if(G.some((V)=>typeof V!=="string")){j.warn(Object.assign({},c(X,["handler"]),{msg:"\u94A9\u5B50\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let Y=G.filter((V)=>!VG.includes(V));if(Y.length>0){j.warn(Object.assign({},c(X,["handler"]),{msg:`\u94A9\u5B50\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${Y.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${VG.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${G.join(", ")}`})),J=!0;continue}let H=G.includes("enable"),z=G.includes("deps");if(H){if(typeof X.enable!=="boolean"){j.warn(Object.assign({},c(X,["handler"]),{msg:"\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}}else X.enable=!0;if(X.source==="core"){let V=typeof X.name==="string"?X.name:"";if(V===""){j.warn(Object.assign({},c(X,["handler"]),{msg:"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(V)){j.warn(Object.assign({},c(X,["handler"]),{msg:"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)){j.warn(Object.assign({},c(X,["handler"]),{msg:"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(V!==X.moduleName){j.warn(Object.assign({},c(X,["handler"]),{msg:"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:${V}`)){j.warn(Object.assign({},c(X,["handler"]),{msg:"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(z){if(!Array.isArray(X.deps)){j.warn(Object.assign({},c(X,["handler"]),{msg:"\u94A9\u5B50\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}if(X.deps.some((V)=>typeof V!=="string")){j.warn(Object.assign({},c(X,["handler"]),{msg:"\u94A9\u5B50\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}}else if(!Array.isArray(X.deps))X.deps=[];if(typeof X.handler!=="function"){j.warn(Object.assign({},c(X,["handler"]),{msg:"\u94A9\u5B50\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(G){j.error({err:G,item:X,msg:"\u94A9\u5B50\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u94A9\u5B50\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();kZ();function MH($){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:""}}var jG=async($)=>{let J=!1,Z=await qG($),X=[];for(let Y of Z)X.push({menu:Y,depth:1});let G=new Set;while(X.length>0){let Y=X.pop(),H=Y?.menu,z=typeof Y?.depth==="number"?Y.depth:0;if(H===null||typeof H!=="object"){J=!0,j.warn({menu:H,msg:"\u83DC\u5355\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61"});continue}if(z>3){J=!0,j.warn({path:H?.path,depth:z,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});continue}let V=H.children;if(typeof V<"u"&&!Array.isArray(V)){J=!0,j.warn({path:H?.path,childrenType:typeof V,msg:"\u83DC\u5355 children \u5FC5\u987B\u662F\u6570\u7EC4"});continue}if(Array.isArray(V)&&V.length>0)if(z>=3)J=!0,j.warn({path:H?.path,depth:z,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});else for(let S of V)X.push({menu:S,depth:z+1});let O=typeof H.path==="string"?H.path.trim():"",_=typeof H.name==="string"?H.name.trim():"",I=typeof H.sort==="number"?H.sort:999999;if(typeof H.path==="string")H.path=O;if(typeof H.name==="string")H.name=_;if(typeof H.sort>"u")H.sort=I;if(!O){J=!0,j.warn({menu:H,msg:"\u83DC\u5355\u7F3A\u5C11 path\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});continue}let B=MH(O);if(!B.ok)J=!0,j.warn({path:O,reason:B.reason,msg:"\u83DC\u5355 path \u4E0D\u5408\u6CD5"});if(!_)J=!0,j.warn({path:O,menu:H,msg:"\u83DC\u5355\u7F3A\u5C11 name\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});if(typeof H.sort<"u"&&typeof H.sort!=="number")J=!0,j.warn({path:O,sort:H.sort,msg:"\u83DC\u5355 sort \u5FC5\u987B\u662F number"});if(typeof H.sort==="number"&&(!Number.isFinite(H.sort)||H.sort<1))J=!0,j.warn({path:O,sort:H.sort,msg:"\u83DC\u5355 sort \u6700\u5C0F\u503C\u4E3A 1"});if(G.has(O)){J=!0,j.warn({path:O,msg:"\u83DC\u5355 path \u91CD\u590D\uFF08\u4E25\u683C\u6A21\u5F0F\u7981\u6B62\u91CD\u590D path\uFF09"});continue}G.add(O)}if(J)throw Error("\u83DC\u5355\u7ED3\u6784\u68C0\u67E5\u5931\u8D25");return Z};a();n0();var PG=["name","enable","deps","handler"];async function BG($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let X of $)try{if(!i(X)){j.warn(Object.assign({},c(X,["handler"]),{msg:"\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()===""){j.warn(Object.assign({},c(X,["handler"]),{msg:"\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}let G=X.customKeys;if(!Array.isArray(G)){j.warn(Object.assign({},c(X,["handler"]),{msg:"\u63D2\u4EF6\u626B\u63CF\u7ED3\u679C\u7F3A\u5C11 customKeys\uFF08\u65E0\u6CD5\u5224\u65AD\u7528\u6237\u5BFC\u51FA\u7684\u5B57\u6BB5\u662F\u5426\u5408\u6CD5\uFF09"})),J=!0;continue}if(G.some((V)=>typeof V!=="string")){j.warn(Object.assign({},c(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let Y=G.filter((V)=>!PG.includes(V));if(Y.length>0){j.warn(Object.assign({},c(X,["handler"]),{msg:`\u63D2\u4EF6\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${Y.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${PG.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${G.join(", ")}`})),J=!0;continue}let H=G.includes("enable"),z=G.includes("deps");if(H){if(typeof X.enable!=="boolean"){j.warn(Object.assign({},c(X,["handler"]),{msg:"\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}}else X.enable=!0;if(X.source==="core"){let V=typeof X.name==="string"?X.name:"";if(V===""){j.warn(Object.assign({},c(X,["handler"]),{msg:"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(V)){j.warn(Object.assign({},c(X,["handler"]),{msg:"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)){j.warn(Object.assign({},c(X,["handler"]),{msg:"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(V!==X.moduleName){j.warn(Object.assign({},c(X,["handler"]),{msg:"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:${V}`)){j.warn(Object.assign({},c(X,["handler"]),{msg:"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(z){if(!Array.isArray(X.deps)){j.warn(Object.assign({},c(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}if(X.deps.some((V)=>typeof V!=="string")){j.warn(Object.assign({},c(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}}else if(!Array.isArray(X.deps))X.deps=[];if(typeof X.handler!=="function"){j.warn(Object.assign({},c(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(G){j.error({err:G,item:X,msg:"\u63D2\u4EF6\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u63D2\u4EF6\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var LG=["id","created_at","updated_at","deleted_at","state"],SG=["string","number","text","array_string","array_text","array_number_string","array_number_text"],CG=["name","type","min","max","default","detail","index","unique","nullable","unsigned","regexp"],_H=/^_?[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)*$/,AH=/^[\u4e00-\u9fa5a-zA-Z0-9 _-]+$/,wG=65535;async function EG($){let J=!1;for(let Z of $){if(Z.type!=="table")continue;let X=typeof Z.sourceName==="string"?Z.sourceName:"",G=X?`${X}\u8868 `:"\u8868 ";try{let Y=Z.fileName,H=Z.content||{};if(!_H.test(Y)){j.warn(`${G}${Y} \u6587\u4EF6\u540D\u5FC5\u987B\u4F7F\u7528\u5C0F\u9A7C\u5CF0\u547D\u540D\uFF08\u4F8B\u5982 testCustomers.json\uFF09`),J=!0;continue}for(let[z,V]of Object.entries(H)){if(typeof V!=="object"||V===null||Array.isArray(V)){j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u89C4\u5219\u5FC5\u987B\u4E3A\u5BF9\u8C61`),J=!0;continue}if(LG.includes(z))j.warn(`${G}${Y} \u6587\u4EF6\u5305\u542B\u4FDD\u7559\u5B57\u6BB5 ${z}\uFF0C`+`\u4E0D\u80FD\u5728\u8868\u5B9A\u4E49\u4E2D\u4F7F\u7528\u4EE5\u4E0B\u5B57\u6BB5: ${LG.join(", ")}`),J=!0;let O=V,I=Object.keys(O).filter((D)=>!CG.includes(D));if(I.length>0)j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5305\u542B\u975E\u6CD5\u5C5E\u6027: ${I.join(", ")}\uFF0C`+`\u5141\u8BB8\u7684\u5C5E\u6027\u4E3A: ${CG.join(", ")}`),J=!0;if(!O.name||typeof O.name!=="string"){j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5 name \u6216\u7C7B\u578B\u9519\u8BEF`),J=!0;continue}if(!O.type||typeof O.type!=="string"){j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5 type \u6216\u7C7B\u578B\u9519\u8BEF`),J=!0;continue}if(O.min!==void 0&&!(O.min===null||typeof O.min==="number"))j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5 min \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u6570\u5B57`),J=!0;if(O.max!==void 0&&!(O.max===null||typeof O.max==="number"))j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5 max \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u6570\u5B57`),J=!0;if(O.detail!==void 0&&typeof O.detail!=="string")j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5 detail \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32`),J=!0;if(O.index!==void 0&&typeof O.index!=="boolean")j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5 index \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.unique!==void 0&&typeof O.unique!=="boolean")j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5 unique \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.nullable!==void 0&&typeof O.nullable!=="boolean")j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5 nullable \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.unsigned!==void 0&&typeof O.unsigned!=="boolean")j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5 unsigned \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.regexp!==void 0&&O.regexp!==null&&typeof O.regexp!=="string")j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5 regexp \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u5B57\u7B26\u4E32`),J=!0;let{name:B,type:S,min:C,max:T,default:E}=O;if(!AH.test(B))j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5\u540D\u79F0 "${B}" \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(!SG.includes(S))j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5\u7C7B\u578B "${S}" \u683C\u5F0F\u9519\u8BEF\uFF0C`+`\u5FC5\u987B\u4E3A${SG.join("\u3001")}\u4E4B\u4E00`),J=!0;if(S!=="number"&&O.unsigned!==void 0)j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u5B57\u6BB5\u7C7B\u578B\u4E3A ${S}\uFF0C\u4E0D\u5141\u8BB8\u8BBE\u7F6E unsigned\uFF08\u4EC5 number \u7C7B\u578B\u6709\u6548\uFF09`),J=!0;if(O.unique===!0&&O.index===!0)j.warn(`${G}${Y} \u6587\u4EF6 ${z} \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&&T!==void 0&&C!==null&&T!==null){if(C>T)j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u6700\u5C0F\u503C "${C}" \u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u503C "${T}"`),J=!0}if(S==="text"||S==="array_text"||S==="array_number_text"){if(C!==void 0&&C!==null)j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u7684 ${S} \u7C7B\u578B\u6700\u5C0F\u503C\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${C}"`),J=!0;if(T!==void 0&&T!==null)j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u7684 ${S} \u7C7B\u578B\u6700\u5927\u957F\u5EA6\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0;if(E!==void 0&&E!==null)j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u4E3A ${S} \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${E}"`),J=!0;if(O.index===!0)j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u4E3A ${S} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u521B\u5EFA\u7D22\u5F15\uFF08index=true \u65E0\u6548\uFF09`),J=!0;if(O.unique===!0)j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u4E3A ${S} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u552F\u4E00\u7EA6\u675F\uFF08unique=true \u65E0\u6548\uFF09`),J=!0}else if(S==="string"||S==="array_string"||S==="array_number_string"){if(T!==void 0&&(T===null||typeof T!=="number"))j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u4E3A ${S} \u7C7B\u578B\uFF0C`+`\u6700\u5927\u957F\u5EA6\u5FC5\u987B\u4E3A\u6570\u5B57\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0;else if(T!==void 0&&T>wG)j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u6700\u5927\u957F\u5EA6 ${T} \u8D8A\u754C\uFF0C`+`${S} \u7C7B\u578B\u957F\u5EA6\u5FC5\u987B\u5728 1..${wG} \u8303\u56F4\u5185`),J=!0}else if(S==="number"){if(E!==void 0&&E!==null&&typeof E!=="number")j.warn(`${G}${Y} \u6587\u4EF6 ${z} \u4E3A number \u7C7B\u578B\uFF0C`+`\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A\u6570\u5B57\u6216 null\uFF0C\u5F53\u524D\u4E3A "${E}"`),J=!0}}}catch(Y){j.error({msg:`${G}${Z.fileName} \u89E3\u6790\u5931\u8D25`,err:Y}),J=!0}}if(J)throw Error("\u8868\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var{SQL:TG,RedisClient:FH}=globalThis.Bun;class U${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",G=J.port||3306,Y=encodeURIComponent(J.username||"root"),H=encodeURIComponent(J.password||"root"),z=encodeURIComponent(J.database||"befly_demo"),V;if(Z==="sqlite")V=z;else{if(!X||!z)throw Error("\u6570\u636E\u5E93\u914D\u7F6E\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E\u53C2\u6570");V=`${Z}://${Y}:${H}@${X}:${G}/${z}`}let O;if(Z==="sqlite")O=new TG(V);else O=new TG({url:V,max:J.poolMax??1,bigint:!1});try{let I=(async()=>{let S="";if(Z==="sqlite")S=(await O`SELECT sqlite_version() AS version`)?.[0]?.version;else if(Z==="postgresql"||Z==="postgres")S=(await O`SELECT version() AS version`)?.[0]?.version;else S=(await O`SELECT VERSION() AS version`)?.[0]?.version;return S})(),B=new Promise((S,C)=>{setTimeout(()=>{C(Error(`\u6570\u636E\u5E93\u8FDE\u63A5\u8D85\u65F6 (${30000}ms)`))},30000)});return await Promise.race([I,B]),this.sqlClient=O,this.sqlConnectedAt=Date.now(),this.sqlPoolMax=J.poolMax??1,O}catch(_){j.error({err:_,msg:"[Connect] SQL \u8FDE\u63A5\u5931\u8D25"});try{await O?.close()}catch{}throw _}}static async disconnectSql(){if(this.sqlClient){try{await this.sqlClient.close()}catch($){j.error({err:$,msg:"[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,G=J.username||"",Y=J.password||"",H=J.db||0,z="";if(G&&Y)z=`${G}:${Y}@`;else if(Y)z=`:${Y}@`;let V=`redis://${z}${Z}:${X}/${H}`,O=new FH(V,{connectionTimeout:30000,idleTimeout:0,autoReconnect:!0,maxRetries:3,enableOfflineQueue:!0,enableAutoPipelining:!0});return await O.ping(),this.redisClient=O,this.redisConnectedAt=Date.now(),O}catch(Z){throw j.error({err:Z,msg:"[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($){j.error({err:$,msg:"[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 j.error({env:$.nodeEnv,err:J,msg:"\u6570\u636E\u5E93\u8FDE\u63A5\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 IJ={"@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 NG($,J,Z){if(!$||typeof $!=="object")return $;let X={};for(let[G,Y]of Object.entries($)){if(typeof Y==="string"&&Y.startsWith("@")){if(IJ[Y]){X[G]=IJ[Y];continue}let H=Object.keys(IJ).join(", ");throw Error(`API [${J}] (${Z}) \u5B57\u6BB5 [${G}] \u5F15\u7528\u4E86\u672A\u5B9A\u4E49\u7684\u9884\u8BBE\u5B57\u6BB5 "${Y}"\u3002\u53EF\u7528\u7684\u9884\u8BBE\u5B57\u6BB5\u6709: ${H}`)}X[G]=Y}return X}async function vG($){let J=new Map;for(let Z of $){if(Z.type!=="api")continue;try{let X=Z;X.fields=NG(X.fields||{},X.name,X.path),J.set(X.path,X)}catch(X){throw j.error({err:X,api:Z.relativePath,file:Z.filePath,msg:"\u63A5\u53E3\u52A0\u8F7D\u5931\u8D25"}),X}}return J}a();n0();function qJ($,J={}){let Z=J.moduleLabel||"\u6A21\u5757",X=J.getName||((I)=>{let B=I.moduleName;if(typeof B==="string"&&B.trim()!=="")return B;return _$(I.fileName)}),G=J.getDeps||((I)=>I.deps),Y=[],H=new Set,z=new Set,V={},O=!0;for(let I of $){let B=X(I);if(typeof B!=="string"||B.trim()===""){j.error({item:I,msg:`${Z} \u540D\u79F0\u89E3\u6790\u5931\u8D25\uFF08getName \u8FD4\u56DE\u7A7A\u5B57\u7B26\u4E32\uFF09`}),O=!1;continue}if(V[B]){j.error({name:B,first:V[B],second:I,msg:`${Z} \u540D\u79F0\u91CD\u590D\uFF0C\u65E0\u6CD5\u6839\u636E deps \u552F\u4E00\u5B9A\u4F4D`}),O=!1;continue}V[B]=I}if(!O)return!1;for(let I of $){let B=X(I),S=G(I);if(!Array.isArray(S)){j.error({module:B,item:I,msg:`${Z} \u7684 deps \u5FC5\u987B\u662F\u6570\u7EC4`}),O=!1;continue}for(let C of S){if(typeof C!=="string"){j.error({module:B,dependency:C,item:I,msg:`${Z} \u7684 deps \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4`}),O=!1;continue}if(!V[C])j.error({module:B,dependency:C,msg:`${Z} \u4F9D\u8D56\u672A\u627E\u5230`}),O=!1}}if(!O)return!1;let _=(I)=>{if(H.has(I))return;if(z.has(I)){j.error({module:I,msg:`${Z} \u5FAA\u73AF\u4F9D\u8D56`}),O=!1;return}let B=V[I];if(!B)return;let S=G(B);z.add(I);for(let C of S)_(C);z.delete(I),H.add(I),Y.push(B)};for(let I of $){let B=X(I);_(B)}return O?Y:!1}async function DG($){let J=[],Z=$.filter((G)=>{let Y=G?.moduleName;if(typeof Y!=="string"||Y.trim()==="")return!1;if(G?.enable===!1)return!1;return!0}),X=qJ(Z,{moduleLabel:"\u94A9\u5B50"});if(X===!1)throw Error("\u94A9\u5B50\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let G of X){let Y=G.moduleName,H=G;J.push({name:Y,enable:!0,deps:Array.isArray(H.deps)?H.deps:[],handler:H.handler})}return J}a();async function kG($,J){let Z=[],X=$.filter((Y)=>{let H=Y?.moduleName;if(typeof H!=="string"||H.trim()==="")return!1;if(Y?.enable===!1)return!1;return!0}),G=qJ(X,{moduleLabel:"\u63D2\u4EF6"});if(G===!1)throw Error("\u63D2\u4EF6\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let Y of G){let H=Y.moduleName,z=Y;try{let V=typeof z.handler==="function"?await z.handler(J):{};J[H]=V,Z.push({name:H,enable:!0,deps:Array.isArray(z.deps)?z.deps:[],handler:z.handler})}catch(V){throw j.error({err:V,plugin:H,msg:"\u63D2\u4EF6\u521D\u59CB\u5316\u5931\u8D25"}),V}}return Z}OJ();a();function xG($,J){let Z=$.headers.get("x-forwarded-for");if(typeof Z==="string"&&Z.trim()){let z=Z.split(",")[0];if(typeof z==="string"&&z.trim())return z.trim()}let X=$.headers.get("x-real-ip");if(typeof X==="string"&&X.trim())return X.trim();let G=$.headers.get("cf-connecting-ip");if(typeof G==="string"&&G.trim())return G.trim();let Y=$.headers.get("x-client-ip");if(typeof Y==="string"&&Y.trim())return Y.trim();let H=$.headers.get("true-client-ip");if(typeof H==="string"&&H.trim())return H.trim();if(J&&typeof J.requestIP==="function"){let z=J.requestIP($);if(z&&typeof z.address==="string"&&z.address.trim())return z.address.trim()}return"unknown"}a();function j$($,J,Z=1,X=null,G=null,Y=null){if($.requestId)j.info({event:"request_blocked",reason:J,reasonCode:Y,code:Z,detail:G,msg:"request blocked"});return Response.json({code:Z,msg:J,data:X,detail:G},{headers:$.corsHeaders})}function xZ($){if($.api&&$.requestId)j.info({event:"request_done",msg:"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,G)=>typeof G==="bigint"?G.toString():G);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})}n0();function yG($,J,Z){return async(X,G)=>{let Y=rX(),z=new URL(X.url).pathname||"/",V=xG(X,G),O=Date.now(),_={method:X.method,body:{},user:{},req:X,now:O,ip:V,headers:X.headers,route:z,requestId:Y,corsHeaders:{"X-Request-ID":Y}},I=$.get(z);if(I)_.api=I;return aX({requestId:Y,method:X.method,route:z,ip:V,now:O},async()=>{try{for(let B of J)if(await B.handler(Z,_),_.response)return _.response;if(_.api&&X.method!=="OPTIONS"){let B={event:"request",apiName:_.api.name};if(_.body&&Object.keys(_.body).length>0)B.body=_.body;B.msg="request",j.info(B)}if(!_.api){if(X.method!=="OPTIONS")_.response=Response.json({code:1,msg:"\u63A5\u53E3\u4E0D\u5B58\u5728"},{headers:_.corsHeaders})}else if(_.api.handler){let B=await _.api.handler(Z,_);if(B instanceof Response)_.response=B;else _.result=B}return xZ(_)}catch(B){let S=_.api?z:X.url;return j.error({err:B,path:S,msg:"\u8BF7\u6C42\u9519\u8BEF"}),_.result={code:1,msg:"\u5185\u90E8\u670D\u52A1\u9519\u8BEF"},xZ(_)}})}}q$();a();q$();import{fileURLToPath as RH}from"url";var IH=RH(import.meta.url),P$=FJ(IH);var k6=S$(P$).endsWith("/dist")?P$:m(P$,"dist"),x6=m(P$,"checks"),y6=m(P$,"plugins"),f6=m(P$,"hooks"),g6=m(P$,"apis"),h6=m(P$,"tables"),d0=process.cwd(),b6=m(d0,"checks"),c6=m(d0,"plugins"),p6=m(d0,"hooks"),u6=m(d0,"apis"),n6=m(d0,"tables"),fG=m(d0,"addons");function jJ($,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 gG($=void 0){return async(J)=>{let Z=jJ(J,$),X=new URL(J.url),G=m(d0,"public",X.pathname);try{if(J.method==="OPTIONS")return new Response(null,{status:204,headers:Z});let Y=Bun.file(G);if(await Y.exists())return new Response(Y,{headers:{"Content-Type":Y.type||"application/octet-stream",...Z}});else return Response.json({code:1,msg:"\u6587\u4EF6\u672A\u627E\u5230"},{headers:Z})}catch(Y){return j.error({err:Y,msg:"\u9759\u6001\u6587\u4EF6\u5904\u7406\u5931\u8D25"}),Response.json({code:1,msg:"\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25"},{headers:Z})}}}a();n0();var qH=($)=>{let J=$.split("/").map((Y)=>Y.trim()).filter((Y)=>Y.length>0),X=(J[1]||"")==="addon"?4:3,G=J.slice(0,Math.min(X,J.length));if(G.length===0)return"";return`/${G.join("/")}`};async function hG($,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){j.debug(`${"addon_admin_api"} \u8868\u4E0D\u5B58\u5728`);return}let G=(await $.db.getAll({table:"addon_admin_api",fields:["id","path","parentPath","name","addonName","auth","state"],where:{state$gte:0}})).data.lists||[],Y=lX(G,(_)=>_.path),H=[],z=[],V=[],O=new Set;for(let _ of J){if(_.type!=="api")continue;let I=_.auth===!1||_.auth===0?0:1,B=qH(_.path);O.add(_.path);let S=Y[_.path];if(S){if(_.name!==S.name||_.path!==S.path||_.addonName!==S.addonName||B!==S.parentPath||I!==S.auth)z.push({id:S.id,name:_.name,path:_.path,parentPath:B,addonName:_.addonName,auth:I})}else H.push({name:_.name,path:_.path,parentPath:B,addonName:_.addonName,auth:I})}for(let _ of G)if(!O.has(_.path))V.push(_.id);if(z.length>0)try{await $.db.updBatch("addon_admin_api",z.map((_)=>{return{id:_.id,data:{name:_.name,path:_.path,parentPath:_.parentPath,addonName:_.addonName,auth:_.auth}}}))}catch(_){j.error({err:_,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u66F4\u65B0\u5931\u8D25"})}if(H.length>0)try{await $.db.insBatch("addon_admin_api",H.map((_)=>{return{name:_.name,path:_.path,parentPath:_.parentPath,addonName:_.addonName,auth:_.auth}}))}catch(_){j.error({err:_,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u65B0\u589E\u5931\u8D25"})}if(V.length>0)try{await $.db.delForceBatch("addon_admin_api",V)}catch(_){j.error({err:_,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u5220\u9664\u5931\u8D25"})}}async function bG($){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 jH}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=jH("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 G=new Bun.CryptoHasher($,J);return G.update(Z),G.digest(X)}static async hashFile($,J="sha256",Z="hex"){let X=Bun.file($),G=new Bun.CryptoHasher(J),H=X.stream().getReader();try{while(!0){let{done:z,value:V}=await H.read();if(z)break;G.update(V)}return G.digest(Z)}finally{H.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 G=0;G<Z.length;G++)X+=Z[G].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 cG($,J={}){if(!J.devPassword)return;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){j.debug("addon_admin_admin \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_role")).data){j.debug("addon_admin_role \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_menu")).data){j.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_api")).data){j.debug("addon_admin_api \u8868\u4E0D\u5B58\u5728");return}let Z=await $.db.getAll({table:"addon_admin_menu",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),X=await $.db.getAll({table:"addon_admin_api",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),G=await $.db.getOne({table:"addon_admin_role",where:{code:"dev"}}),Y={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:Z.data.lists.map((O)=>O.path).filter((O)=>O),apis:X.data.lists.map((O)=>O.path).filter((O)=>O),sort:0};if(G.data)await $.db.updData({table:"addon_admin_role",where:{code:"dev"},data:{name:Y.name,description:Y.description,menus:Y.menus,apis:Y.apis,sort:Y.sort}});else await $.db.insData({table:"addon_admin_role",data:Y});let H={nickname:"\u5F00\u53D1\u8005",email:J.devEmail||"dev@qq.com",username:"dev",password:await y$.hashPassword(y$.sha256(J.devPassword+"befly")),roleCode:"dev",roleType:"admin"};if((await $.db.getOne({table:"addon_admin_admin",where:{username:"dev"}})).data)await $.db.updData({table:"addon_admin_admin",where:{username:"dev"},data:{nickname:H.nickname,email:H.email,username:H.username,password:H.password,roleCode:H.roleCode,roleType:H.roleType}});else await $.db.insData({table:"addon_admin_admin",data:H});let V=[{code:"user",name:"\u7528\u6237\u89D2\u8272",description:"\u666E\u901A\u7528\u6237\u89D2\u8272",sort:1},{code:"admin",name:"\u7BA1\u7406\u5458\u89D2\u8272",description:"\u7BA1\u7406\u5458\u89D2\u8272",sort:2},{code:"guest",name:"\u8BBF\u5BA2\u89D2\u8272",description:"\u8BBF\u5BA2\u89D2\u8272",sort:3}];for(let O of V)if((await $.db.getOne({table:"addon_admin_role",where:{code:O.code}})).data?.id)await $.db.updData({table:"addon_admin_role",where:{code:O.code},data:{name:O.name,description:O.description,sort:O.sort}});else await $.db.insData({table:"addon_admin_role",data:{code:O.code,name:O.name,description:O.description,sort:O.sort}})}a();kZ();function PH($){let J=$.config?.disableMenus,Z=Array.isArray(J)?J:[],X=[];for(let Y of Z){if(typeof Y!=="string")continue;let H=Y.trim();if(!H)continue;X.push(H)}if(X.length===0)return()=>!1;let G=X.map((Y)=>new Bun.Glob(Y));return(Y)=>{if(typeof Y!=="string")return!1;let H=Y.trim();if(!H)return!1;let z=[];if(z.push(H),H.startsWith("/"))z.push(H.slice(1));else z.push(`/${H}`);for(let V of G){let O=V.match;if(typeof O!=="function")throw Error("syncMenu: \u5F53\u524D Bun \u7248\u672C\u4E0D\u652F\u6301 Bun.Glob.match\uFF0C\u65E0\u6CD5\u6309 disableMenus \u505A glob \u5339\u914D");for(let _ of z)if(O.call(V,_))return!0}return!1}}function pG($,J){let Z=[];for(let X of $){if(X===null||typeof X!=="object")continue;let G=typeof X.path==="string"?String(X.path).trim():"";if(G&&J(G))continue;let Y=X.children,H=Array.isArray(Y)&&Y.length>0?pG(Y,J):[],z={};if(typeof X.name==="string")z.name=X.name;if(typeof X.path==="string")z.path=X.path;if(typeof X.sort==="number")z.sort=X.sort;if(typeof X.parentPath==="string")z.parentPath=X.parentPath;if(H.length>0)z.children=H;Z.push(z)}return Z}function BH($){let J=new Map,Z=[];for(let X of $)Z.push({menu:X,parentPathFromTree:""});while(Z.length>0){let X=Z.pop(),G=X?X.menu:null;if(!G)continue;let Y=typeof G.path==="string"?G.path:"",H=G.children;if(H&&Array.isArray(H)&&H.length>0){let I=typeof Y==="string"?Y:"";for(let B of H)Z.push({menu:B,parentPathFromTree:I})}if(!Y)continue;let z=typeof G.name==="string"?G.name:"";if(!z)continue;let V=typeof G.sort==="number"?G.sort:999999,_=typeof G.parentPath==="string"?G.parentPath:typeof X?.parentPathFromTree==="string"?X.parentPathFromTree:IG(Y);J.set(Y,{path:Y,name:z,sort:V,parentPath:_})}return J}async function uG($,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){j.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}let Z=PH($),X=pG(J,Z),G=BH(X),Y=new Set;for(let z of G.keys())Y.add(z);let H="addon_admin_menu";await $.db.trans(async(z)=>{let O=(await z.getAll({table:H,fields:["id","name","path","parentPath","sort","state"]})).data.lists||[],_=O.filter((w)=>typeof w?.state==="number"&&w.state>=0),I=new Map,B=new Set,S=new Map;for(let w of _){if(typeof w?.path!=="string"||!w.path)continue;if(typeof w?.id!=="number")continue;if(Z(w.path))continue;let N=I.get(w.path);if(!N){I.set(w.path,w);continue}let p=typeof N?.id==="number"?N.id:0,v=w.id;if(v>p){if(I.set(w.path,w),p>0)B.add(p);let b=S.get(w.path)||{keptId:v,removedIds:[]};if(b.keptId=v,p>0)b.removedIds.push(p);S.set(w.path,b)}else{if(v>0)B.add(v);let b=S.get(w.path)||{keptId:p,removedIds:[]};if(b.keptId=p,v>0)b.removedIds.push(v);S.set(w.path,b)}}if(S.size>0){let w=[];for(let N of S.entries()){let p=N[0],v=N[1];if(w.push({path:p,keptId:v.keptId,removedIds:v.removedIds}),w.length>=10)break}j.warn({table:H,duplicatePaths:S.size,duplicateIds:B.size,examples:w,msg:"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 C=[],T=[];for(let w of G.values()){let N=I.get(w.path);if(N){let p=typeof N.parentPath==="string"?N.parentPath:"";if(N.name!==w.name||N.sort!==w.sort||p!==w.parentPath)C.push({id:N.id,data:{name:w.name,path:w.path,parentPath:w.parentPath,sort:w.sort}})}else T.push({name:w.name,path:w.path,parentPath:w.parentPath,sort:w.sort})}if(C.length>0)await z.updBatch(H,C);if(T.length>0)await z.insBatch(H,T);let E=new Set;for(let w of _){if(typeof w?.path!=="string"||!w.path)continue;if(!Y.has(w.path)){if(typeof w?.id==="number")E.add(w.id)}}for(let w of B)if(typeof w==="number"&&w>0)E.add(w);for(let w of O){if(typeof w?.path!=="string"||!w.path)continue;if(!Z(w.path))continue;if(typeof w?.id==="number"&&w.id>0)E.add(w.id)}let D=Array.from(E);if(D.length>0)await z.delForceBatch(H,D)})}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 g$($){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 BJ),f$.set("postgresql",new nG),f$.set("sqlite",new mG);let Z=f$.get($);if(!Z)throw J;return Z}function PJ($){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",G={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]},Y={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:G,comments:Y}}return{columns:g$("sqlite").getTableColumnsQuery($.table)}}function yZ($){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 BJ{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 nG{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 mG{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();n0();var SJ=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(),G="mysql";if(X==="postgres"||X==="postgresql")G="postgresql";else if(X==="sqlite")G="sqlite";await LH(G,$.db);let Y=$.config.db?.database||"",H={dbDialect:G,db:$.db,dbName:Y};for(let z of J){if(!z||z.type!=="table")continue;if(z.source!=="app"&&z.source!=="addon"&&z.source!=="core"){j.warn(`syncTable \u8DF3\u8FC7\u672A\u77E5\u6765\u6E90\u8868\u5B9A\u4E49: source=${String(z.source)} fileName=${String(z.fileName)}`);continue}let V=f(z.fileName),O=V;if(z.source==="addon"){if(!z.addonName||String(z.addonName).trim()==="")throw Error(`syncTable addon \u8868\u7F3A\u5C11 addonName: fileName=${String(z.fileName)}`);O=`addon_${f(z.addonName)}_${V}`}let _=z.content;if(!_||typeof _!=="object")throw Error(`syncTable \u8868\u5B9A\u4E49\u65E0\u6548: table=${O}`);for(let B of Object.values(_))iG(B);if(await J1(H,O))await wH(H,O,_);else await G1(H,O,_);Z.push(O)}if(Z.length>0){let z=Z.map((V)=>X0.tableColumns(V));await $.redis.delBatch(z)}}catch(Z){throw j.error({err:Z,msg:"\u6570\u636E\u5E93\u540C\u6B65\u5931\u8D25"}),Z}},C$={MYSQL_MIN_MAJOR:8,POSTGRES_MIN_MAJOR:17,SQLITE_MIN_VERSION:"3.50.0",SQLITE_MIN_VERSION_NUM:35000},sG={length:"\u957F\u5EA6",datatype:"\u7C7B\u578B",comment:"\u6CE8\u91CA",default:"\u9ED8\u8BA4\u503C",nullable:"\u53EF\u7A7A\u7EA6\u675F",unique:"\u552F\u4E00\u7EA6\u675F"},oG={ENGINE:"InnoDB",CHARSET:"utf8mb4",COLLATE:"utf8mb4_0900_ai_ci"},ZJ=[{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"}],gZ=ZJ.filter(($)=>$.needsIndex).map(($)=>$.name),lG={};for(let $ of ZJ)lG[$.name]=$;var rG={DB_VERSION_REQUIREMENTS:C$,CHANGE_TYPE_LABELS:sG,MYSQL_TABLE_CONFIG:oG,SYSTEM_INDEX_FIELDS:gZ,getTypeMapping:CJ,quoteIdentifier:G0,escapeComment:wJ,applyFieldDefaults:iG,isStringOrArrayType:JJ,getSqlType:hZ,resolveDefaultValue:XJ,generateDefaultSql:EJ,buildIndexSQL:LJ,buildSystemColumnDefs:aG,buildBusinessColumnDefs:eG,generateDDLClause:fZ,isCompatibleTypeChange:$1,compareFieldDefinition:X1,tableExistsRuntime:J1,getTableColumnsRuntime:Z1,getTableIndexesRuntime:bZ,createRuntime:($,J,Z="")=>{return{dbDialect:$,db:J,dbName:Z}}};SJ.TestKit=rG;Object.defineProperty(SJ,"TestKit",{value:rG,writable:!1,enumerable:!0,configurable:!1});function CJ($){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 G0($,J){return g$($).quoteIdent(J)}function wJ($){return String($).replace(/"/g,"\\\"")}function iG($){$.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 JJ($){return $==="string"||$==="array_string"||$==="array_number_string"}function hZ($,J,Z,X=!1){let G=CJ($);if(JJ(J))return`${G[J]}(${Z})`;let Y=G[J]||"TEXT";if($==="mysql"&&J==="number"&&X)return`${Y} UNSIGNED`;return Y}function XJ($,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 EJ($,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 LJ($,J,Z,X,G){let Y=G0($,J),H=G0($,Z),z=G0($,X);if($==="mysql"){let V=[];if(G==="create")V.push(`ADD INDEX ${H} (${z})`);else V.push(`DROP INDEX ${H}`);return`ALTER TABLE ${Y} ALGORITHM=INPLACE, LOCK=NONE, ${V.join(", ")}`}if($==="postgresql"){if(G==="create")return`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${H} ON ${Y}(${z})`;return`DROP INDEX CONCURRENTLY IF EXISTS ${H}`}if(G==="create")return`CREATE INDEX IF NOT EXISTS ${H} ON ${Y}(${z})`;return`DROP INDEX IF EXISTS ${H}`}function tG($,J){let Z=lG[J];if(!Z)return null;let X=G0($,Z.name);if($==="mysql")return`${X} ${Z.mysqlDdl} COMMENT "${wJ(Z.comment)}"`;if($==="postgresql")return`${X} ${Z.pgDdl}`;return`${X} ${Z.sqliteDdl}`}function aG($){let J=[];for(let Z of ZJ){let X=tG($,Z.name);if(X)J.push(X)}return J}function eG($,J){let Z=[];for(let[X,G]of Object.entries(J)){let Y=f(X),H=G0($,Y),z=hZ($,G.type,G.max,G.unsigned),V=XJ(G.default,G.type),O=EJ(V,G.type),_=G.unique?" UNIQUE":"",I=G.nullable?" NULL":" NOT NULL";if($==="mysql")Z.push(`${H} ${z}${_}${I}${O} COMMENT "${wJ(G.name)}"`);else Z.push(`${H} ${z}${_}${I}${O}`)}return Z}function fZ($,J,Z,X=!1){let G=f(J),Y=G0($,G),H=hZ($,Z.type,Z.max,Z.unsigned),z=XJ(Z.default,Z.type),V=EJ(z,Z.type),O=Z.unique?" UNIQUE":"",_=Z.nullable?" NULL":" NOT NULL";if($==="mysql")return`${X?"ADD COLUMN":"MODIFY COLUMN"} ${Y} ${H}${O}${_}${V} COMMENT "${wJ(Z.name)}"`;if($==="postgresql"){if(X)return`ADD COLUMN IF NOT EXISTS ${Y} ${H}${O}${_}${V}`;return`ALTER COLUMN ${Y} TYPE ${H}`}if(X)return`ADD COLUMN IF NOT EXISTS ${Y} ${H}${O}${_}${V}`;return""}async function dG($,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 G=J;return G=G.replace(/\bALGORITHM\s*=\s*(INPLACE|INSTANT)\b\s*,?\s*/g,"").replace(/\bLOCK\s*=\s*(NONE|SHARED|EXCLUSIVE)\b\s*,?\s*/g,""),G=G.replace(/,\s*,/g,", ").replace(/,\s*$/g,"").replace(/\s{2,}/g," ").trim(),await $.unsafe(G),!0}}else throw Z}}function $1($,J){let Z=String($||"").toLowerCase(),X=String(J||"").toLowerCase();if(Z===X)return!1;let G=Z.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),Y=X.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),H=["tinyint","smallint","mediumint","int","integer","bigint"],z=H.indexOf(G),V=H.indexOf(Y);if(z!==-1&&V!==-1&&V>z)return!0;if(G==="varchar"&&(Y==="text"||Y==="mediumtext"||Y==="longtext"))return!0;if(G==="character varying"&&Y==="text")return!0;return!1}async function J1($,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=g$($.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),G=Error(`runtime I/O \u5931\u8D25: op=tableExists table=${J} err=${X}`);if(Z?.sqlInfo)G.sqlInfo=Z.sqlInfo;throw G}}async function Z1($,J){let Z={};try{if($.dbDialect==="mysql"){let X=PJ({dialect:"mysql",table:J,dbName:$.dbName}),G=await $.db.unsafe(X.columns.sql,X.columns.params);for(let Y of G.data){let H=Y.COLUMN_DEFAULT;Z[Y.COLUMN_NAME]={type:Y.DATA_TYPE,columnType:Y.COLUMN_TYPE,length:Y.CHARACTER_MAXIMUM_LENGTH,max:Y.CHARACTER_MAXIMUM_LENGTH,nullable:Y.IS_NULLABLE==="YES",defaultValue:H,comment:Y.COLUMN_COMMENT}}}else if($.dbDialect==="postgresql"){let X=PJ({dialect:"postgresql",table:J,dbName:$.dbName}),G=await $.db.unsafe(X.columns.sql,X.columns.params),Y=X.comments?(await $.db.unsafe(X.comments.sql,X.comments.params)).data:[],H={};for(let z of Y)H[z.column_name]=z.column_comment;for(let z of G.data)Z[z.column_name]={type:z.data_type,columnType:z.data_type,length:z.character_maximum_length,max:z.character_maximum_length,nullable:String(z.is_nullable).toUpperCase()==="YES",defaultValue:z.column_default,comment:H[z.column_name]??null}}else if($.dbDialect==="sqlite"){let X=PJ({dialect:"sqlite",table:J,dbName:$.dbName}),G=await $.db.unsafe(X.columns.sql,X.columns.params);for(let Y of G.data){let H=String(Y.type||"").toUpperCase(),z=null,V=/^(\w+)\s*\((\d+)\)/.exec(H);if(V){let O=V[1],_=V[2];if(typeof O==="string")H=O;if(typeof _==="string")z=Number(_)}Z[Y.name]={type:H.toLowerCase(),columnType:H.toLowerCase(),length:z,max:z,nullable:Y.notnull===0,defaultValue:Y.dflt_value,comment:null}}}return Z}catch(X){let G=String(X?.message||X),Y=Error(`runtime I/O \u5931\u8D25: op=getTableColumns table=${J} err=${G}`);if(X?.sqlInfo)Y.sqlInfo=X.sqlInfo;throw Y}}async function bZ($,J){let Z={};try{if($.dbDialect==="mysql"){let X=yZ({dialect:"mysql",table:J,dbName:$.dbName}),G=await $.db.unsafe(X.sql,X.params);for(let Y of G.data){let H=Y.INDEX_NAME,z=Z[H];if(Array.isArray(z))z.push(Y.COLUMN_NAME);else Z[H]=[Y.COLUMN_NAME]}}else if($.dbDialect==="postgresql"){let X=yZ({dialect:"postgresql",table:J,dbName:$.dbName}),G=await $.db.unsafe(X.sql,X.params);for(let Y of G.data){let H=/\(([^)]+)\)/.exec(Y.indexdef);if(H){let z=H[1],V=typeof z==="string"?z.replace(/"/g,"").trim():"";Z[Y.indexname]=[V]}}}else if($.dbDialect==="sqlite"){let X=G0("sqlite",J),G=await $.db.unsafe(`PRAGMA index_list(${X})`);for(let Y of G.data){let H=G0("sqlite",Y.name),V=(await $.db.unsafe(`PRAGMA index_info(${H})`)).data.map((O)=>O.name);if(V.length===1)Z[Y.name]=V}}return Z}catch(X){let G=String(X?.message||X),Y=Error(`runtime I/O \u5931\u8D25: op=getTableIndexes table=${J} err=${G}`);if(X?.sqlInfo)Y.sqlInfo=X.sqlInfo;throw Y}}async function LH($,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,G=String(X).split(".")[0]||"0",Y=parseInt(G,10);if(!Number.isFinite(Y)||Y<C$.MYSQL_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u4EC5\u652F\u6301 MySQL ${C$.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,G=/PostgreSQL\s+(\d+)/i.exec(X),Y=G?G[1]:void 0,H=typeof Y==="string"?parseInt(Y,10):NaN;if(!Number.isFinite(H)||H<C$.POSTGRES_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 PostgreSQL >= ${C$.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,G=String(X).split(".").map((O)=>parseInt(O,10)||0),Y=G[0]??0,H=G[1]??0,z=G[2]??0,V=Y*1e4+H*100+z;if(!Number.isFinite(V)||V<C$.SQLITE_MIN_VERSION_NUM)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 SQLite >= ${C$.SQLITE_MIN_VERSION}\uFF0C\u5F53\u524D: ${X}`);return}}function X1($,J,Z){let X=[];if($!=="sqlite"&&JJ(Z.type)){if(J.max!==Z.max)X.push({type:"length",current:J.max,expected:Z.max})}if($!=="sqlite"){let _=J.comment||"";if(_!==Z.name)X.push({type:"comment",current:_,expected:Z.name})}let Y=CJ($)[Z.type];if(typeof Y!=="string")throw Error(`\u672A\u77E5\u5B57\u6BB5\u7C7B\u578B\u6620\u5C04\uFF1Adialect=${$} type=${String(Z.type)}`);let H=Y.toLowerCase(),z=J.type.toLowerCase();if(z!==H)X.push({type:"datatype",current:z,expected:H});let V=Z.nullable;if(J.nullable!==V)X.push({type:"nullable",current:J.nullable,expected:V});let O=XJ(Z.default,Z.type);if(String(J.defaultValue)!==String(O))X.push({type:"default",current:J.defaultValue,expected:O});return X}async function SH($,J,Z){if($.dbDialect!=="sqlite")throw Error(`rebuildSqliteTable \u4EC5\u652F\u6301 sqlite \u65B9\u8A00\uFF0C\u5F53\u524D: ${String($.dbDialect)}`);let X=G0("sqlite",J),Y=(await $.db.unsafe(`PRAGMA table_info(${X})`)).data.map((I)=>I.name),z=["id","created_at","updated_at","deleted_at","state",...Object.keys(Z).map((I)=>f(I))],V=`${J}__tmp__${Date.now()}`;await G1($,V,Z);let O=z.filter((I)=>Y.includes(I));if(O.length>0){let I=O.map((S)=>G0("sqlite",S)).join(", "),B=G0("sqlite",V);await $.db.unsafe(`INSERT INTO ${B} (${I}) SELECT ${I} FROM ${X}`)}await $.db.unsafe(`DROP TABLE ${X}`);let _=G0("sqlite",V);await $.db.unsafe(`ALTER TABLE ${_} RENAME TO ${X}`)}async function CH($,J,Z,X){if(!X||!X.changed)return;if($.dbDialect==="sqlite")if(X.modifyClauses.length>0||X.defaultClauses.length>0)await SH($,J,Z);else for(let G of X.addClauses){let Y=`ALTER TABLE ${G0($.dbDialect,J)} ${G}`;await $.db.unsafe(Y)}else{let G=[...X.addClauses,...X.modifyClauses];if(G.length>0){let Y=G0($.dbDialect,J),H=$.dbDialect==="mysql"?`ALTER TABLE ${Y} ALGORITHM=INSTANT, LOCK=NONE, ${G.join(", ")}`:`ALTER TABLE ${Y} ${G.join(", ")}`;if($.dbDialect==="mysql")await dG($.db,H);else await $.db.unsafe(H)}}if(X.defaultClauses.length>0)if($.dbDialect==="sqlite")j.warn(`SQLite \u4E0D\u652F\u6301\u4FEE\u6539\u9ED8\u8BA4\u503C\uFF0C\u8868 ${J} \u7684\u9ED8\u8BA4\u503C\u53D8\u66F4\u5DF2\u8DF3\u8FC7`);else{let G=G0($.dbDialect,J),Y=$.dbDialect==="mysql"?`ALTER TABLE ${G} ALGORITHM=INSTANT, LOCK=NONE, ${X.defaultClauses.join(", ")}`:`ALTER TABLE ${G} ${X.defaultClauses.join(", ")}`;if($.dbDialect==="mysql")await dG($.db,Y);else await $.db.unsafe(Y)}for(let G of X.indexActions){let Y=LJ($.dbDialect,J,G.indexName,G.fieldName,G.action);try{if(await $.db.unsafe(Y),G.action==="create")j.debug(`[\u7D22\u5F15\u53D8\u5316] \u65B0\u5EFA\u7D22\u5F15 ${J}.${G.indexName} (${G.fieldName})`);else j.debug(`[\u7D22\u5F15\u53D8\u5316] \u5220\u9664\u7D22\u5F15 ${J}.${G.indexName} (${G.fieldName})`)}catch(H){throw j.error({err:H,table:J,index:G.indexName,field:G.fieldName,msg:`${G.action==="create"?"\u521B\u5EFA":"\u5220\u9664"}\u7D22\u5F15\u5931\u8D25`}),H}}if($.dbDialect==="postgresql"&&X.commentActions&&X.commentActions.length>0)for(let G of X.commentActions)await $.db.unsafe(G)}async function G1($,J,Z,X=gZ){let Y=[...aG($.dbDialect),...eG($.dbDialect,Z)].join(`,
7
- `),H=G0($.dbDialect,J),{ENGINE:z,CHARSET:V,COLLATE:O}=oG,_=$.dbDialect==="mysql"?`CREATE TABLE ${H} (
2
+ var BW=Object.create;var{getPrototypeOf:LW,defineProperty:dG,getOwnPropertyNames:SW}=Object;var CW=Object.prototype.hasOwnProperty;var wW=($,J,Z)=>{Z=$!=null?BW(LW($)):{};let G=J||!$||!$.__esModule?dG(Z,"default",{value:$,enumerable:!0}):Z;for(let X of SW($))if(!CW.call(G,X))dG(G,X,{get:()=>$[X],enumerable:!0});return G};var s=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var V$=($,J)=>()=>($&&(J=$($=0)),J);var _$=import.meta.require;function AZ($,J="dateTime"){let Z=$.getFullYear(),G=$.getMonth()+1,X=$.getDate(),Y=$.getHours(),H=$.getMinutes(),U=$.getSeconds(),z=G<10?`0${G}`:String(G),O=X<10?`0${X}`:String(X),_=Y<10?`0${Y}`:String(Y),I=H<10?`0${H}`:String(H),B=U<10?`0${U}`:String(U);if(J==="date")return`${Z}-${z}-${O}`;if(J==="time")return`${_}:${I}:${B}`;return`${Z}-${z}-${O} ${_}:${I}:${B}`}function i($){if(typeof $!=="object"||$===null)return!1;let J=Object.getPrototypeOf($);return J===Object.prototype||J===null}function FZ($){if($===null)return"null";if($===void 0)return"undefined";if(Array.isArray($))return"array";let J=typeof $;if(J==="string")return"string";if(J==="number")return"number";if(J==="boolean")return"boolean";if(J==="bigint")return"bigint";if(J==="symbol")return"symbol";if(J==="function")return"function";return"object"}function k$($,J,Z,G){if(typeof $!=="number")return J;if(!Number.isFinite($))return J;let X=Math.floor($);if(X<Z)return J;if(X>G)return G;return X}function sG($,J){if(typeof J!=="function")return;if(!i($))return;for(let Z of Object.keys($))J($[Z],Z)}function TW($){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 NW($){if($.length===0)return $;return $.charAt(0).toUpperCase()+$.slice(1)}function A$($){let J=TW($);if(J.length===0)return"";let Z=J[0];if(!Z)return"";let G=Z.toLowerCase(),X=J.slice(1).map((Y)=>NW(Y.toLowerCase()));return[G].concat(X).join("")}function vW($){return String($).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").trim()}function f($){let J=vW($);if(J.length===0)return"";return J.split(/\s+/).filter((Z)=>Z.length>0).map((Z)=>Z.toLowerCase()).join("_")}function c($,J){if(!i($))return{};let Z=new Set(Array.isArray(J)?J:[]),G={};for(let[X,Y]of Object.entries($)){if(Z.has(X))continue;G[X]=Y}return G}function lG($,J){let Z={};if(!Array.isArray($)||typeof J!=="function")return Z;for(let G of $){let X=J(G);if(typeof X!=="string"||X==="")continue;Z[X]=G}return Z}function rG(){return Date.now().toString(36)+Math.random().toString(36).slice(2,7)}var RZ=($)=>{if(!$||!i($))return $;let J={};for(let[Z,G]of Object.entries($)){let X=A$(Z);J[X]=G}return J},oG=($)=>{if(!$||!i($))return $;let J={};for(let[Z,G]of Object.entries($)){let X=f(Z);J[X]=G}return J},IZ=($)=>{if(!$||!Array.isArray($))return $;return $.map((J)=>RZ(J))};var n0=()=>{};function PZ($){let J=[];for(let X of $.builtinPatterns){let Y=String(X).trim();if(Y.length>0)J.push(Y.toLowerCase())}if(Array.isArray($.userPatterns))for(let X of $.userPatterns){let Y=String(X).trim();if(Y.length>0)J.push(Y.toLowerCase())}let Z=new Set,G=[];for(let X of J){if(!X.includes("*")){Z.add(X);continue}let Y=X.replace(/\*+/g,"").trim();if(!Y)continue;G.push(Y)}return{exactSet:Z,contains:G}}function BZ($,J){let Z=String($).toLowerCase();if(J.exactSet.has(Z))return!0;for(let G of J.contains)if(Z.includes(G))return!0;return!1}function OJ($,J){if($.length<=J)return $;return $.slice(0,J)}function iG($,J){let Z={name:$.name||"Error",message:OJ($.message||"",J.maxStringLen)};if(typeof $.stack==="string")Z.stack=OJ($.stack,J.maxStringLen);return Z}function DW($,J,Z){if(typeof $==="string")return $;if($ instanceof Error)try{return JSON.stringify(iG($,J))}catch{return`${$.name||"Error"}: ${$.message||""}`}if($&&typeof $==="object"){if(Z.has($))return"[Circular]"}try{let G=Z;return JSON.stringify($,(Y,H)=>{if(Y&&BZ(Y,J.sensitiveKeyMatcher))return"[MASKED]";if(H&&typeof H==="object"){if(G.has(H))return"[Circular]";G.add(H)}return H})}catch{try{return String($)}catch{return"[Unserializable]"}}}function qZ($,J,Z){let G=DW($,J,Z);return OJ(G,J.maxStringLen)}function jZ($,J,Z,G,X){if($===null||$===void 0)return $;if(typeof $==="string")return OJ($,J.maxStringLen);if(typeof $==="number"||typeof $==="boolean"||typeof $==="bigint")return $;if($ instanceof Error)return iG($,J);let Y=Array.isArray($),H=i($);if(!Y&&!H)return qZ($,J,X);if(X.has($))return"[Circular]";if(G>=J.sanitizeDepth)return qZ($,J,X);if(Z.nodes>=J.sanitizeNodes)return qZ($,J,X);if(X.add($),Z.nodes=Z.nodes+1,Y){let I=$,B=[],S=I.length>J.maxArrayItems?J.maxArrayItems:I.length;for(let C=0;C<S;C++)B[C]=jZ(I[C],J,Z,G+1,X);return B}let U=$,z={},O=Object.entries(U),_=O.length>J.sanitizeObjectKeys?J.sanitizeObjectKeys:O.length;for(let I=0;I<_;I++){let B=O[I];if(!B)continue;let S=B[0],C=B[1];if(BZ(S,J.sensitiveKeyMatcher)){z[S]="[MASKED]";continue}z[S]=jZ(C,J,Z,G+1,X)}return z}function LZ($,J){let Z=new WeakSet,G={nodes:0},X={};for(let[Y,H]of Object.entries($)){if(BZ(Y,J.sensitiveKeyMatcher)){X[Y]="[MASKED]";continue}X[Y]=jZ(H,J,G,0,Z)}return X}var tG=V$(()=>{n0()});import{AsyncLocalStorage as kW}from"async_hooks";function aG($,J){return SZ.run($,J)}function eG(){let $=SZ.getStore();if(!$)return null;return $}function $X($,J,Z,G){let X=SZ.getStore();if(!X)return;X.userId=$===void 0?null:$,X.roleCode=J===void 0?null:J,X.nickname=Z===void 0?null:Z,X.roleType=G===void 0?null:G}var SZ;var KJ=V$(()=>{SZ=new kW});import{createWriteStream as yW,existsSync as xW,mkdirSync as fW}from"fs";import{stat as gW}from"fs/promises";import{hostname as hW}from"os";import{isAbsolute as bW,join as cW,resolve as pW}from"path";function AJ($){try{process.stderr.write(`${$}
3
+ `)}catch{}}function mW($,J){let Z=[],G=0;while($.length>0){let X=$[0],Y=Buffer.byteLength(X);if(Z.length>0&&G+Y>J)break;Z.push(X),G=G+Y,$.shift()}return{chunk:Z.join(""),bytes:G}}class EZ{pending;pendingBytes;scheduledTimer;flushing;maxBufferBytes;flushDelayMs;maxBatchBytes;writeChunk;onShutdown;constructor($){this.pending=[],this.pendingBytes=0,this.scheduledTimer=null,this.flushing=!1,this.maxBufferBytes=$.maxBufferBytes,this.flushDelayMs=$.flushDelayMs,this.maxBatchBytes=$.maxBatchBytes,this.writeChunk=$.writeChunk,this.onShutdown=$.onShutdown?$.onShutdown:null}scheduleFlush(){if(this.scheduledTimer)return;this.scheduledTimer=setTimeout(()=>{this.scheduledTimer=null,this.flush()},this.flushDelayMs)}cancelScheduledFlush(){if(!this.scheduledTimer)return;clearTimeout(this.scheduledTimer),this.scheduledTimer=null}enqueue($){let J=Buffer.byteLength($);if(this.pendingBytes+J>this.maxBufferBytes)return;this.pending.push($),this.pendingBytes=this.pendingBytes+J,this.scheduleFlush()}async flushNow(){this.cancelScheduledFlush(),await this.flush()}async shutdown(){if(this.cancelScheduledFlush(),await this.flush(),this.onShutdown)await this.onShutdown()}async flush(){if(this.flushing)return;this.flushing=!0;try{while(this.pending.length>0){let J=mW(this.pending,this.maxBatchBytes).chunk,Z=Buffer.byteLength(J);if(this.pendingBytes=this.pendingBytes-Z,!await this.writeChunk(J,Z)){this.pending=[],this.pendingBytes=0;break}}}finally{if(this.flushing=!1,this.pending.length>0)this.scheduleFlush()}}}function dW($){let J=()=>{return $==="stderr"?process.stderr:process.stdout},Z=new EZ({maxBufferBytes:10485760,flushDelayMs:10,maxBatchBytes:65536,writeChunk:async(G)=>{try{let X=J();if(!X.write(G))await new Promise((H)=>{X.once("drain",()=>H())});return!0}catch(X){return AJ(`[Logger] stream sink error: ${X?.message||X}`),!1}}});return{enqueue(G){Z.enqueue(G)},async flushNow(){await Z.flushNow()},async shutdown(){await Z.shutdown()}}}class CZ{prefix;maxFileBytes;buffer;stream;streamDate;streamIndex;streamSizeBytes;disabled;constructor($){this.prefix=$.prefix,this.maxFileBytes=$.maxFileBytes,this.stream=null,this.streamDate="",this.streamIndex=0,this.streamSizeBytes=0,this.disabled=!1,this.buffer=new EZ({maxBufferBytes:10485760,flushDelayMs:10,maxBatchBytes:65536,writeChunk:async(J,Z)=>{if(this.disabled)return!1;try{if(await this.ensureStreamReady(Z),!this.stream)return!1;if(!this.stream.write(J))await new Promise((X)=>{this.stream.once("drain",()=>X())});return this.streamSizeBytes=this.streamSizeBytes+Z,!0}catch(G){return AJ(`[Logger] file sink flush error (${this.prefix}): ${G?.message||G}`),this.disabled=!0,await this.closeStream(),!1}},onShutdown:async()=>{await this.closeStream()}})}enqueue($){if(this.disabled)return;this.buffer.enqueue($)}async flushNow(){await this.buffer.flushNow()}async shutdown(){await this.buffer.shutdown()}async closeStream(){if(!this.stream)return;let $=this.stream;this.stream=null,await new Promise((J)=>{try{$.end(()=>J())}catch{J()}})}openStream($){try{this.stream=yW($,{flags:"a"}),this.stream.on("error",(J)=>{AJ(`[Logger] file sink error (${this.prefix}): ${J?.message||J}`),this.disabled=!0,this.closeStream()})}catch(J){AJ(`[Logger] createWriteStream failed (${this.prefix}): ${J?.message||J}`),this.disabled=!0,this.stream=null}}getFilePath($,J){let Z=J>0?`.${J}`:"",G=`${this.prefix}.${$}${Z}.log`;return cW(YX(),G)}async ensureStreamReady($){let J=AZ(new Date,"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),G=0;try{let X=await gW(Z);G=typeof X.size==="number"?X.size:0}catch{G=0}if(this.streamDate=J,this.streamIndex=0,this.streamSizeBytes=G,this.openStream(Z),!this.stream)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);if(this.streamDate=J,this.streamSizeBytes=0,this.openStream(Z),!this.stream)return}}}async function sW(){if(S$)return;let $=[];if(G$)$.push({flush:()=>G$?G$.flushNow():Promise.resolve()});if(X$)$.push({flush:()=>X$?X$.flushNow():Promise.resolve()});if(Y$)$.push({flush:()=>Y$?Y$.flushNow():Promise.resolve()});for(let J of $)try{await J.flush()}catch{}}async function XX(){if(S$)return;let $=F$,J=R$,Z=G$,G=X$,X=Y$,Y=[];if(Z)Y.push({shutdown:()=>Z.shutdown()});if(G)Y.push({shutdown:()=>G.shutdown()});if(X)Y.push({shutdown:()=>X.shutdown()});for(let H of Y)try{await H.shutdown()}catch{}if(G$===Z)G$=null;if(X$===G)X$=null;if(Y$===X)Y$=null;if(F$===$)F$=null;if(R$===J)R$=null}function YX(){let $=m0.dir||"./logs";if(bW($))return $;return pW(uW,$)}function oW(){let $=YX();try{if(!xW($))fW($,{recursive:!0})}catch(J){throw Error(`\u521B\u5EFA logs \u76EE\u5F55\u5931\u8D25: ${$}. ${J?.message||J}`)}}function lW($){XX(),m0=Object.assign({debug:0,dir:"./logs",console:1,maxSize:20},$);{let J=m0.maxSize,Z=typeof J==="number"&&Number.isFinite(J)?J:20;if(Z<10)Z=10;if(Z>100)Z=100;m0.maxSize=Z}F$=null,R$=null,G$=null,X$=null,Y$=null,wZ={maxStringLen:k$(m0.maxStringLen,100,20,200000),maxArrayItems:k$(m0.maxArrayItems,100,10,5000),sanitizeDepth:k$(m0.sanitizeDepth,3,1,10),sanitizeNodes:k$(m0.sanitizeNodes,500,50,20000),sanitizeObjectKeys:k$(m0.sanitizeObjectKeys,100,10,5000),sensitiveKeyMatcher:PZ({builtinPatterns:GX,userPatterns:m0.excludeFields})}}function rW($){S$=$}function a$($){if(S$)return S$;if($==="app"){if(F$)return F$}else if(R$)return R$;oW();let J=typeof m0.maxSize==="number"?m0.maxSize:20,Z=Math.floor(J*1024*1024);if($==="app"){if(!G$)G$=new CZ({prefix:"app",maxFileBytes:Z});if(m0.console===1&&!Y$)Y$=dW("stdout");return F$=ZX({fileSink:G$,consoleSink:m0.console===1?Y$:null}),F$}if(!X$)X$=new CZ({prefix:"error",maxFileBytes:Z});return R$=ZX({fileSink:X$,consoleSink:null}),R$}function iW($,J){let Z=Date.now(),G={level:$,time:Z,timeFormat:AZ(new Date(Z)),pid:process.pid,hostname:nW};if(J&&i(J)){let X=Object.assign({},J,G);if(J.msg!==void 0)X.msg=J.msg;else if(X.msg===void 0)X.msg="";return`${JX(X)}
4
+ `}if(G.msg===void 0)G.msg="";return`${JX(G)}
5
+ `}function JX($){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 ZX($){let{fileSink:J,consoleSink:Z}=$,G=(X,Y)=>{if(X==="debug"&&m0.debug!==1)return;let H=LZ(Y,wZ),U=iW(X,H);if(J.enqueue(U),Z)Z.enqueue(U)};return{info(X){G("info",X)},warn(X){G("warn",X)},error(X){G("error",X)},debug(X){G("debug",X)}}}function tW(){let $=eG();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 aW($,J){let Z={};for(let[X,Y]of Object.entries($))Z[X]=Y;let G=["requestId","method","route","ip","now","durationSinceNowMs","userId","roleCode","nickname","roleType"];for(let X of G)if(Z[X]===void 0)Z[X]=J[X];return Z}function MJ($){if(i($))return $;if($ instanceof Error)return{err:$,msg:$.message||$.name||"Error"};if($===void 0)return{msg:""};if($===null)return{msg:"null"};if(typeof $==="object")return{value:$};try{return{msg:String($)}}catch{return{msg:"[Unserializable]"}}}function _J($){let J=tW();if(!J)return $;return aW($,J)}class WX{maybeSanitizeForMock($){if(!S$)return $;return LZ($,wZ)}info($){let J=_J(MJ($)),Z=this.maybeSanitizeForMock(J);return a$("app").info(Z)}warn($){let J=_J(MJ($)),Z=this.maybeSanitizeForMock(J);return a$("app").warn(Z)}error($){let J=_J(MJ($)),Z=this.maybeSanitizeForMock(J),G=a$("app").error(Z);if(S$)return G;return a$("error").error(Z),G}debug($){if(m0.debug!==1)return;let J=_J(MJ($)),Z=this.maybeSanitizeForMock(J);return a$("app").debug(Z)}async flush(){await sW()}configure($){lW($)}setMock($){rW($)}async shutdown(){await XX()}}var uW,GX,wZ,nW,F$=null,R$=null,S$=null,G$=null,X$=null,Y$=null,m0,j;var a=V$(()=>{tG();n0();KJ();uW=process.cwd(),GX=["*password*","pass","pwd","*token*","access_token","refresh_token","accessToken","refreshToken","authorization","cookie","set-cookie","*secret*","apiKey","api_key","privateKey","private_key"],wZ={maxStringLen:100,maxArrayItems:100,sanitizeDepth:3,sanitizeNodes:500,sanitizeObjectKeys:100,sensitiveKeyMatcher:PZ({builtinPatterns:GX,userPatterns:[]})},nW=(()=>{try{return hW()}catch{return"unknown"}})(),m0={debug:0,dir:"./logs",console:1,maxSize:20};j=new WX});import{isAbsolute as eW}from"path";import{pathToFileURL as $H}from"url";function JH($){return/^[a-zA-Z]:[\\/]/.test($)}function ZH($){if(eW($)||JH($))return $H($).href;return $}async function I$($,J){try{let X=($.endsWith(".json")?await import(ZH($),{with:{type:"json"}}):await import($))?.default;if(X===null||X===void 0)return J;let Y=FZ(J),H=FZ(X);if(Y!==H)return j.warn({file:$,msg:"importDefault \u5BFC\u5165\u7C7B\u578B\u4E0E\u9ED8\u8BA4\u503C\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C",expectedType:Y,actualType:H}),J;return X}catch(Z){return j.warn({err:Z,file:$,msg:"importDefault \u5BFC\u5165\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C"}),J}}var FJ=V$(()=>{a();n0()});function $J($=""){if(!$)return $;return $.replace(/\\/g,"/").replace(XH,(J)=>J.toUpperCase())}function UH(){if(typeof process<"u"&&typeof process.cwd==="function")return process.cwd().replace(/\\/g,"/");return"/"}function NZ($,J){let Z="",G=0,X=-1,Y=0,H=null;for(let U=0;U<=$.length;++U){if(U<$.length)H=$[U];else if(H==="/")break;else H="/";if(H==="/"){if(X===U-1||Y===1);else if(Y===2){if(Z.length<2||G!==2||Z[Z.length-1]!=="."||Z[Z.length-2]!=="."){if(Z.length>2){let z=Z.lastIndexOf("/");if(z===-1)Z="",G=0;else Z=Z.slice(0,z),G=Z.length-1-Z.lastIndexOf("/");X=U,Y=0;continue}else if(Z.length>0){Z="",G=0,X=U,Y=0;continue}}if(J)Z+=Z.length>0?"/..":"..",G=2}else{if(Z.length>0)Z+=`/${$.slice(X+1,U)}`;else Z=$.slice(X+1,U);G=U-X-1}X=U,Y=0}else if(H==="."&&Y!==-1)++Y;else Y=-1}return Z}var XH,YH,WH,MX,KX,HH,QH,C$=function($){if($.length===0)return".";$=$J($);let J=$.match(YH),Z=y$($),G=$[$.length-1]==="/";if($=NZ($,!Z),$.length===0){if(Z)return"/";return G?"./":"."}if(G)$+="/";if(MX.test($))$+="/";if(J){if(!Z)return`//./${$}`;return`//${$}`}return Z&&!y$($)?`/${$}`:$},m=function(...$){let J="";for(let Z of $){if(!Z)continue;if(J.length>0){let G=J[J.length-1]==="/",X=Z[0]==="/";if(G&&X)J+=Z.slice(1);else J+=G||X?Z:`/${Z}`}else J+=Z}return C$(J)},e$=function(...$){$=$.map((G)=>$J(G));let J="",Z=!1;for(let G=$.length-1;G>=-1&&!Z;G--){let X=G>=0?$[G]:UH();if(!X||X.length===0)continue;J=`${X}/${J}`,Z=y$(X)}if(J=NZ(J,!Z),Z&&!y$(J))return`/${J}`;return J.length>0?J:"."},y$=function($){return WH.test($)},_X=function($){if($==="..")return"";let J=HH.exec($J($));return J&&J[1]||""},vZ=function($,J){let Z=e$($).replace(KX,"$1").split("/"),G=e$(J).replace(KX,"$1").split("/");if(G[0][1]===":"&&Z[0][1]===":"&&Z[0]!==G[0])return G.join("/");let X=[...Z];for(let Y of X){if(G[0]!==Y)break;Z.shift(),G.shift()}return[...Z.map(()=>".."),...G].join("/")},RJ=function($){let J=$J($).replace(/\/$/,"").split("/").slice(0,-1);if(J.length===1&&MX.test(J[0]))J[0]+="/";return J.join("/")||(y$($)?"/":".")},AX=function($,J){let Z=$J($).split("/"),G="";for(let X=Z.length-1;X>=0;X--){let Y=Z[X];if(Y){G=Y;break}}return J&&G.endsWith(J)?G.slice(0,-J.length):G},JJ=function($){let J=QH.exec($)?.[0]?.replace(/\\/g,"/")||"",Z=AX($),G=_X(Z);return{root:J,dir:RJ($),base:Z,ext:G,name:Z.slice(0,Z.length-G.length)}};var FX=V$(()=>{XH=/^[A-Za-z]:\//;YH=/^[/\\]{2}/,WH=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,MX=/^[A-Za-z]:$/,KX=/^\/([A-Za-z]:)?$/,HH=/.(\.[^./]+|\.)$/,QH=/^[/\\]|^[a-zA-Z]:[/\\]/});var j$=V$(()=>{FX()});import{statSync as VH}from"fs";var IJ=($,J)=>{if(J.isDirectory())return!0;if(!J.isSymbolicLink())return!1;try{return VH(m($,J.name)).isDirectory()}catch{return!1}};var DZ=V$(()=>{j$()});import{existsSync as x$}from"fs";import{readdir as zH}from"fs/promises";function OH($){if(!$||typeof $!=="object")return null;if(typeof $.title!=="string"||!$.title)return null;let J=typeof $.order==="number"&&Number.isFinite($.order)&&Number.isInteger($.order)&&$.order>=0?$.order:void 0;return{title:$.title,order:J}}async function RX($,J,Z=""){if(!x$($))return[];let G=[],X=await zH($,{withFileTypes:!0});for(let Y of X){if(!IJ($,Y)||Y.name==="components")continue;let H=m($,Y.name),U=m(H,"meta.json"),z=m(H,"index.vue"),O=null;if(!x$(U))continue;if(!x$(z)){j.warn({path:H,msg:"\u76EE\u5F55\u5B58\u5728 meta.json \u4F46\u7F3A\u5C11 index.vue\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}let _=await I$(U,{});if(O=OH(_),!O?.title){j.warn({path:U,msg:"meta.json \u7F3A\u5C11\u6709\u6548\u7684 title\uFF08\u4EE5\u53CA\u53EF\u9009 order:number\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}if(!O?.title)continue;let I=String(Y.name).replace(/_\d+$/,""),B;if(I==="index")B=Z;else B=Z?`${Z}/${I}`:`/${I}`;let S=J?B?`${J}${B}`:J:B||"/",C={name:O.title,path:S,sort:O.order??999999},T=await RX(H,J,B);if(T.length>0)C.children=T;G.push(C)}return G.sort((Y,H)=>(Y.sort??999999)-(H.sort??999999)),G}function IX($){let J=$.split("/").filter((Z)=>Boolean(Z));if(J.length<=1)return"";return`/${J.slice(0,-1).join("/")}`}async function qX($){let J=[];for(let G of $){let X=m(G.fullPath,"adminViews"),Y=m(G.fullPath,"views","admin"),H=x$(X)?X:x$(Y)?Y:null;if(!H)continue;try{let U=`/${G.source}/${G.name}`,z=await RX(H,U);if(z.length>0)for(let O of z)J.push(O)}catch(U){j.warn({err:U,addon:G.name,addonSource:G.source,dir:H,msg:"\u626B\u63CF addon views \u76EE\u5F55\u5931\u8D25"})}}let Z=m(process.cwd(),"menus.json");if(x$(Z)){let G=await I$(Z,[]);if(Array.isArray(G)&&G.length>0)for(let X of G)J.push(X)}return J}var kZ=V$(()=>{j$();a();FJ();DZ()});var u$=s((nU,wY)=>{var CY={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 p$ extends Error{constructor($,J,Z){super(J);if(Error.captureStackTrace(this,this.constructor),this.code=$,Z)for(let G in Z)this[G]=Z[G]}}p$.codes=CY;p$.wrap=function($,J,Z){if($ instanceof p$)return $;return new p$(J,Z,{originalError:$})};wY.exports={TokenError:p$,TOKEN_ERROR_CODES:CY}});var iZ=s((mU,EY)=>{var{TokenError:H$}=u$();function BQ({complete:$,checkTyp:J},Z){if(Z instanceof Buffer)Z=Z.toString("utf-8");else if(typeof Z!=="string")throw new H$(H$.codes.invalidType,"The token must be a string or a buffer.");let G=Z.indexOf("."),X=Z.lastIndexOf(".");if(G===-1||G>=X)throw new H$(H$.codes.malformed,"The token is malformed.");let Y=!1;try{let H=JSON.parse(Buffer.from(Z.slice(0,G),"base64").toString("utf-8"));if(J&&H.typ!==J)throw new H$(H$.codes.invalidType,`The type must be "${J}".`,{header:H});Y=!0;let U=Buffer.from(Z.slice(G+1,X),"base64").toString("utf-8");if(U=JSON.parse(U),!U||typeof U!=="object")throw new H$(H$.codes.invalidPayload,"The payload must be an object",{payload:U});return $?{header:H,payload:U,signature:Z.slice(X+1),input:Z.slice(0,X)}:U}catch(H){throw H$.wrap(H,H$.codes.malformed,`The token ${Y?"payload":"header"} is not a valid base64url serialized JSON.`)}}EY.exports=function(J={}){let Z=J.complete||!1,G=J.checkTyp;return BQ.bind(null,{complete:Z,checkTyp:G})}});var NY=s((dU,TY)=>{function Q$($){if(typeof $!=="function")throw Error("obliterator/iterator: expecting a function!");this.next=$}if(typeof Symbol<"u")Q$.prototype[Symbol.iterator]=function(){return this};Q$.of=function(){var $=arguments,J=$.length,Z=0;return new Q$(function(){if(Z>=J)return{done:!0};return{done:!1,value:$[Z++]}})};Q$.empty=function(){var $=new Q$(function(){return{done:!0}});return $};Q$.fromSequence=function($){var J=0,Z=$.length;return new Q$(function(){if(J>=Z)return{done:!0};return{done:!1,value:$[J++]}})};Q$.is=function($){if($ instanceof Q$)return!0;return typeof $==="object"&&$!==null&&typeof $.next==="function"};TY.exports=Q$});var vY=s((LQ)=>{LQ.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<"u";LQ.SYMBOL_SUPPORT=typeof Symbol<"u"});var tZ=s((oU,kY)=>{var DY=vY(),wQ=DY.ARRAY_BUFFER_SUPPORT,EQ=DY.SYMBOL_SUPPORT;kY.exports=function(J,Z){var G,X,Y,H,U;if(!J)throw Error("obliterator/forEach: invalid iterable.");if(typeof Z!=="function")throw Error("obliterator/forEach: expecting a callback.");if(Array.isArray(J)||wQ&&ArrayBuffer.isView(J)||typeof J==="string"||J.toString()==="[object Arguments]"){for(Y=0,H=J.length;Y<H;Y++)Z(J[Y],Y);return}if(typeof J.forEach==="function"){J.forEach(Z);return}if(EQ&&Symbol.iterator in J&&typeof J.next!=="function")J=J[Symbol.iterator]();if(typeof J.next==="function"){G=J,Y=0;while(U=G.next(),U.done!==!0)Z(U.value,Y),Y++;return}for(X in J)if(J.hasOwnProperty(X))Z(J[X],X);return}});var aZ=s((fQ)=>{var TQ=Math.pow(2,8)-1,NQ=Math.pow(2,16)-1,vQ=Math.pow(2,32)-1,DQ=Math.pow(2,7)-1,kQ=Math.pow(2,15)-1,yQ=Math.pow(2,31)-1;fQ.getPointerArray=function($){var J=$-1;if(J<=TQ)return Uint8Array;if(J<=NQ)return Uint16Array;if(J<=vQ)return Uint32Array;throw Error("mnemonist: Pointer Array of size > 4294967295 is not supported.")};fQ.getSignedPointerArray=function($){var J=$-1;if(J<=DQ)return Int8Array;if(J<=kQ)return Int16Array;if(J<=yQ)return Int32Array;return Float64Array};fQ.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 xQ={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};fQ.getMinimalRepresentation=function($,J){var Z=null,G=0,X,Y,H,U,z;for(U=0,z=$.length;U<z;U++)if(H=J?J($[U]):$[U],Y=fQ.getNumberType(H),X=xQ[Y.name],X>G)G=X,Z=Y;return Z};fQ.isTypedArray=function($){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView($)};fQ.concat=function(){var $=0,J,Z,G;for(J=0,G=arguments.length;J<G;J++)$+=arguments[J].length;var X=new arguments[0].constructor($);for(J=0,Z=0;J<G;J++)X.set(arguments[J],Z),Z+=arguments[J].length;return X};fQ.indices=function($){var J=fQ.getPointerArray($),Z=new J($);for(var G=0;G<$;G++)Z[G]=G;return Z}});var hY=s((dQ)=>{var fY=tZ(),gY=aZ();function uQ($){return Array.isArray($)||gY.isTypedArray($)}function eZ($){if(typeof $.length==="number")return $.length;if(typeof $.size==="number")return $.size;return}function nQ($){var J=eZ($),Z=typeof J==="number"?Array(J):[],G=0;return fY($,function(X){Z[G++]=X}),Z}function mQ($){var J=eZ($),Z=typeof J==="number"?gY.getPointerArray(J):Array,G=typeof J==="number"?Array(J):[],X=typeof J==="number"?new Z(J):[],Y=0;return fY($,function(H){G[Y]=H,X[Y]=Y++}),[G,X]}dQ.isArrayLike=uQ;dQ.guessLength=eZ;dQ.toArray=nQ;dQ.toArrayWithIndices=mQ});var JG=s((iU,bY)=>{var $G=NY(),iQ=tZ(),tQ=aZ(),aQ=hY();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 G=tQ.getPointerArray(Z);this.forward=new G(Z),this.backward=new G(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[$],G=this.forward[$];if(this.tail===$)this.tail=Z;else this.backward[G]=Z;return this.forward[Z]=G,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,G=null,X=this.items[$];if(typeof X<"u")return this.splayOnTop(X),Z=this.V[X],this.V[X]=J,{evicted:!1,key:$,value:Z};if(this.size<this.capacity)X=this.size++;else X=this.tail,this.tail=this.backward[X],Z=this.V[X],G=this.K[X],delete this.items[G];if(this.items[$]=X,this.K[X]=$,this.V[X]=J,this.forward[X]=this.head,this.backward[this.head]=X,this.head=X,G)return{evicted:!0,key:G,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,G=this.size,X=this.head,Y=this.K,H=this.V,U=this.forward;while(Z<G)$.call(J,H[X],Y[X],this),X=U[X],Z++};p0.prototype.keys=function(){var $=0,J=this.size,Z=this.head,G=this.K,X=this.forward;return new $G(function(){if($>=J)return{done:!0};var Y=G[Z];if($++,$<J)Z=X[Z];return{done:!1,value:Y}})};p0.prototype.values=function(){var $=0,J=this.size,Z=this.head,G=this.V,X=this.forward;return new $G(function(){if($>=J)return{done:!0};var Y=G[Z];if($++,$<J)Z=X[Z];return{done:!1,value:Y}})};p0.prototype.entries=function(){var $=0,J=this.size,Z=this.head,G=this.K,X=this.V,Y=this.forward;return new $G(function(){if($>=J)return{done:!0};var H=G[Z],U=X[Z];if($++,$<J)Z=Y[Z];return{done:!1,value:[H,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,G){if(arguments.length<2){if(G=aQ.guessLength($),typeof G!=="number")throw Error("mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.")}else if(arguments.length===2)G=J,J=null,Z=null;var X=new p0(J,Z,G);return iQ($,function(Y,H){X.set(H,Y)}),X};bY.exports=p0});var GG=s((cY,ZG)=>{(function($,J){function Z(q,W){if(!q)throw Error(W||"Assertion failed")}function G(q,W){q.super_=W;var V=function(){};V.prototype=W.prototype,q.prototype=new V,q.prototype.constructor=q}function X(q,W,V){if(X.isBN(q))return q;if(this.negative=0,this.words=null,this.length=0,this.red=null,q!==null){if(W==="le"||W==="be")V=W,W=10;this._init(q||0,W||10,V||"be")}}if(typeof $==="object")$.exports=X;else J.BN=X;X.BN=X,X.wordSize=26;var Y;try{if(typeof window<"u"&&typeof window.Buffer<"u")Y=window.Buffer;else Y=_$("buffer").Buffer}catch(q){}X.isBN=function(W){if(W instanceof X)return!0;return W!==null&&typeof W==="object"&&W.constructor.wordSize===X.wordSize&&Array.isArray(W.words)},X.max=function(W,V){if(W.cmp(V)>0)return W;return V},X.min=function(W,V){if(W.cmp(V)<0)return W;return V},X.prototype._init=function(W,V,K){if(typeof W==="number")return this._initNumber(W,V,K);if(typeof W==="object")return this._initArray(W,V,K);if(V==="hex")V=16;Z(V===(V|0)&&V>=2&&V<=36),W=W.toString().replace(/\s+/g,"");var M=0;if(W[0]==="-")M++,this.negative=1;if(M<W.length){if(V===16)this._parseHex(W,M,K);else if(this._parseBase(W,V,M),K==="le")this._initArray(this.toArray(),V,K)}},X.prototype._initNumber=function(W,V,K){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(K!=="le")return;this._initArray(this.toArray(),V,K)},X.prototype._initArray=function(W,V,K){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 M=0;M<this.length;M++)this.words[M]=0;var R,P,L=0;if(K==="be"){for(M=W.length-1,R=0;M>=0;M-=3)if(P=W[M]|W[M-1]<<8|W[M-2]<<16,this.words[R]|=P<<L&67108863,this.words[R+1]=P>>>26-L&67108863,L+=24,L>=26)L-=26,R++}else if(K==="le"){for(M=0,R=0;M<W.length;M+=3)if(P=W[M]|W[M+1]<<8|W[M+2]<<16,this.words[R]|=P<<L&67108863,this.words[R+1]=P>>>26-L&67108863,L+=24,L>=26)L-=26,R++}return this.strip()};function H(q,W){var V=q.charCodeAt(W);if(V>=65&&V<=70)return V-55;else if(V>=97&&V<=102)return V-87;else return V-48&15}function U(q,W,V){var K=H(q,V);if(V-1>=W)K|=H(q,V-1)<<4;return K}X.prototype._parseHex=function(W,V,K){this.length=Math.ceil((W.length-V)/6),this.words=Array(this.length);for(var M=0;M<this.length;M++)this.words[M]=0;var R=0,P=0,L;if(K==="be")for(M=W.length-1;M>=V;M-=2)if(L=U(W,V,M)<<R,this.words[P]|=L&67108863,R>=18)R-=18,P+=1,this.words[P]|=L>>>26;else R+=8;else{var A=W.length-V;for(M=A%2===0?V+1:V;M<W.length;M+=2)if(L=U(W,V,M)<<R,this.words[P]|=L&67108863,R>=18)R-=18,P+=1,this.words[P]|=L>>>26;else R+=8}this.strip()};function z(q,W,V,K){var M=0,R=Math.min(q.length,V);for(var P=W;P<R;P++){var L=q.charCodeAt(P)-48;if(M*=K,L>=49)M+=L-49+10;else if(L>=17)M+=L-17+10;else M+=L}return M}X.prototype._parseBase=function(W,V,K){this.words=[0],this.length=1;for(var M=0,R=1;R<=67108863;R*=V)M++;M--,R=R/V|0;var P=W.length-K,L=P%M,A=Math.min(P,P-L)+K,Q=0;for(var F=K;F<A;F+=M)if(Q=z(W,F,F+M,V),this.imuln(R),this.words[0]+Q<67108864)this.words[0]+=Q;else this._iaddn(Q);if(L!==0){var k=1;Q=z(W,F,W.length,V);for(F=0;F<L;F++)k*=V;if(this.imuln(k),this.words[0]+Q<67108864)this.words[0]+=Q;else this._iaddn(Q)}this.strip()},X.prototype.copy=function(W){W.words=Array(this.length);for(var V=0;V<this.length;V++)W.words[V]=this.words[V];W.length=this.length,W.negative=this.negative,W.red=this.red},X.prototype.clone=function(){var W=new X(null);return this.copy(W),W},X.prototype._expand=function(W){while(this.length<W)this.words[this.length++]=0;return this},X.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},X.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},X.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var O=["","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"],_=[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],I=[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(X.prototype.toString=function(W,V){W=W||10,V=V|0||1;var K;if(W===16||W==="hex"){K="";var M=0,R=0;for(var P=0;P<this.length;P++){var L=this.words[P],A=((L<<M|R)&16777215).toString(16);if(R=L>>>24-M&16777215,M+=2,M>=26)M-=26,P--;if(R!==0||P!==this.length-1)K=O[6-A.length]+A+K;else K=A+K}if(R!==0)K=R.toString(16)+K;while(K.length%V!==0)K="0"+K;if(this.negative!==0)K="-"+K;return K}if(W===(W|0)&&W>=2&&W<=36){var Q=_[W],F=I[W];K="";var k=this.clone();k.negative=0;while(!k.isZero()){var y=k.modn(F).toString(W);if(k=k.idivn(F),!k.isZero())K=O[Q-y.length]+y+K;else K=y+K}if(this.isZero())K="0"+K;while(K.length%V!==0)K="0"+K;if(this.negative!==0)K="-"+K;return K}Z(!1,"Base should be between 2 and 36")},X.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},X.prototype.toJSON=function(){return this.toString(16)},X.prototype.toBuffer=function(W,V){return Z(typeof Y<"u"),this.toArrayLike(Y,W,V)},X.prototype.toArray=function(W,V){return this.toArrayLike(Array,W,V)},X.prototype.toArrayLike=function(W,V,K){var M=this.byteLength(),R=K||Math.max(1,M);Z(M<=R,"byte array longer than desired length"),Z(R>0,"Requested array length <= 0"),this.strip();var P=V==="le",L=new W(R),A,Q,F=this.clone();if(!P){for(Q=0;Q<R-M;Q++)L[Q]=0;for(Q=0;!F.isZero();Q++)A=F.andln(255),F.iushrn(8),L[R-Q-1]=A}else{for(Q=0;!F.isZero();Q++)A=F.andln(255),F.iushrn(8),L[Q]=A;for(;Q<R;Q++)L[Q]=0}return L},Math.clz32)X.prototype._countBits=function(W){return 32-Math.clz32(W)};else X.prototype._countBits=function(W){var V=W,K=0;if(V>=4096)K+=13,V>>>=13;if(V>=64)K+=7,V>>>=7;if(V>=8)K+=4,V>>>=4;if(V>=2)K+=2,V>>>=2;return K+V};X.prototype._zeroBits=function(W){if(W===0)return 26;var V=W,K=0;if((V&8191)===0)K+=13,V>>>=13;if((V&127)===0)K+=7,V>>>=7;if((V&15)===0)K+=4,V>>>=4;if((V&3)===0)K+=2,V>>>=2;if((V&1)===0)K++;return K},X.prototype.bitLength=function(){var W=this.words[this.length-1],V=this._countBits(W);return(this.length-1)*26+V};function B(q){var W=Array(q.bitLength());for(var V=0;V<W.length;V++){var K=V/26|0,M=V%26;W[V]=(q.words[K]&1<<M)>>>M}return W}X.prototype.zeroBits=function(){if(this.isZero())return 0;var W=0;for(var V=0;V<this.length;V++){var K=this._zeroBits(this.words[V]);if(W+=K,K!==26)break}return W},X.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},X.prototype.toTwos=function(W){if(this.negative!==0)return this.abs().inotn(W).iaddn(1);return this.clone()},X.prototype.fromTwos=function(W){if(this.testn(W-1))return this.notn(W).iaddn(1).ineg();return this.clone()},X.prototype.isNeg=function(){return this.negative!==0},X.prototype.neg=function(){return this.clone().ineg()},X.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},X.prototype.iuor=function(W){while(this.length<W.length)this.words[this.length++]=0;for(var V=0;V<W.length;V++)this.words[V]=this.words[V]|W.words[V];return this.strip()},X.prototype.ior=function(W){return Z((this.negative|W.negative)===0),this.iuor(W)},X.prototype.or=function(W){if(this.length>W.length)return this.clone().ior(W);return W.clone().ior(this)},X.prototype.uor=function(W){if(this.length>W.length)return this.clone().iuor(W);return W.clone().iuor(this)},X.prototype.iuand=function(W){var V;if(this.length>W.length)V=W;else V=this;for(var K=0;K<V.length;K++)this.words[K]=this.words[K]&W.words[K];return this.length=V.length,this.strip()},X.prototype.iand=function(W){return Z((this.negative|W.negative)===0),this.iuand(W)},X.prototype.and=function(W){if(this.length>W.length)return this.clone().iand(W);return W.clone().iand(this)},X.prototype.uand=function(W){if(this.length>W.length)return this.clone().iuand(W);return W.clone().iuand(this)},X.prototype.iuxor=function(W){var V,K;if(this.length>W.length)V=this,K=W;else V=W,K=this;for(var M=0;M<K.length;M++)this.words[M]=V.words[M]^K.words[M];if(this!==V)for(;M<V.length;M++)this.words[M]=V.words[M];return this.length=V.length,this.strip()},X.prototype.ixor=function(W){return Z((this.negative|W.negative)===0),this.iuxor(W)},X.prototype.xor=function(W){if(this.length>W.length)return this.clone().ixor(W);return W.clone().ixor(this)},X.prototype.uxor=function(W){if(this.length>W.length)return this.clone().iuxor(W);return W.clone().iuxor(this)},X.prototype.inotn=function(W){Z(typeof W==="number"&&W>=0);var V=Math.ceil(W/26)|0,K=W%26;if(this._expand(V),K>0)V--;for(var M=0;M<V;M++)this.words[M]=~this.words[M]&67108863;if(K>0)this.words[M]=~this.words[M]&67108863>>26-K;return this.strip()},X.prototype.notn=function(W){return this.clone().inotn(W)},X.prototype.setn=function(W,V){Z(typeof W==="number"&&W>=0);var K=W/26|0,M=W%26;if(this._expand(K+1),V)this.words[K]=this.words[K]|1<<M;else this.words[K]=this.words[K]&~(1<<M);return this.strip()},X.prototype.iadd=function(W){var V;if(this.negative!==0&&W.negative===0)return this.negative=0,V=this.isub(W),this.negative^=1,this._normSign();else if(this.negative===0&&W.negative!==0)return W.negative=0,V=this.isub(W),W.negative=1,V._normSign();var K,M;if(this.length>W.length)K=this,M=W;else K=W,M=this;var R=0;for(var P=0;P<M.length;P++)V=(K.words[P]|0)+(M.words[P]|0)+R,this.words[P]=V&67108863,R=V>>>26;for(;R!==0&&P<K.length;P++)V=(K.words[P]|0)+R,this.words[P]=V&67108863,R=V>>>26;if(this.length=K.length,R!==0)this.words[this.length]=R,this.length++;else if(K!==this)for(;P<K.length;P++)this.words[P]=K.words[P];return this},X.prototype.add=function(W){var V;if(W.negative!==0&&this.negative===0)return W.negative=0,V=this.sub(W),W.negative^=1,V;else if(W.negative===0&&this.negative!==0)return this.negative=0,V=W.sub(this),this.negative=1,V;if(this.length>W.length)return this.clone().iadd(W);return W.clone().iadd(this)},X.prototype.isub=function(W){if(W.negative!==0){W.negative=0;var V=this.iadd(W);return W.negative=1,V._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(W),this.negative=1,this._normSign();var K=this.cmp(W);if(K===0)return this.negative=0,this.length=1,this.words[0]=0,this;var M,R;if(K>0)M=this,R=W;else M=W,R=this;var P=0;for(var L=0;L<R.length;L++)V=(M.words[L]|0)-(R.words[L]|0)+P,P=V>>26,this.words[L]=V&67108863;for(;P!==0&&L<M.length;L++)V=(M.words[L]|0)+P,P=V>>26,this.words[L]=V&67108863;if(P===0&&L<M.length&&M!==this)for(;L<M.length;L++)this.words[L]=M.words[L];if(this.length=Math.max(this.length,L),M!==this)this.negative=1;return this.strip()},X.prototype.sub=function(W){return this.clone().isub(W)};function S(q,W,V){V.negative=W.negative^q.negative;var K=q.length+W.length|0;V.length=K,K=K-1|0;var M=q.words[0]|0,R=W.words[0]|0,P=M*R,L=P&67108863,A=P/67108864|0;V.words[0]=L;for(var Q=1;Q<K;Q++){var F=A>>>26,k=A&67108863,y=Math.min(Q,W.length-1);for(var x=Math.max(0,Q-q.length+1);x<=y;x++){var u=Q-x|0;M=q.words[u]|0,R=W.words[x]|0,P=M*R+k,F+=P/67108864|0,k=P&67108863}V.words[Q]=k|0,A=F|0}if(A!==0)V.words[Q]=A|0;else V.length--;return V.strip()}var C=function(W,V,K){var M=W.words,R=V.words,P=K.words,L=0,A,Q,F,k=M[0]|0,y=k&8191,x=k>>>13,u=M[1]|0,l=u&8191,e=u>>>13,M$=M[2]|0,$0=M$&8191,Z0=M$>>>13,EG=M[3]|0,H0=EG&8191,Q0=EG>>>13,TG=M[4]|0,U0=TG&8191,V0=TG>>>13,NG=M[5]|0,z0=NG&8191,O0=NG>>>13,vG=M[6]|0,K0=vG&8191,M0=vG>>>13,DG=M[7]|0,_0=DG&8191,A0=DG>>>13,kG=M[8]|0,F0=kG&8191,R0=kG>>>13,yG=M[9]|0,I0=yG&8191,q0=yG>>>13,xG=R[0]|0,j0=xG&8191,P0=xG>>>13,fG=R[1]|0,B0=fG&8191,L0=fG>>>13,gG=R[2]|0,S0=gG&8191,C0=gG>>>13,hG=R[3]|0,w0=hG&8191,E0=hG>>>13,bG=R[4]|0,T0=bG&8191,N0=bG>>>13,cG=R[5]|0,v0=cG&8191,D0=cG>>>13,pG=R[6]|0,k0=pG&8191,y0=pG>>>13,uG=R[7]|0,x0=uG&8191,f0=uG>>>13,nG=R[8]|0,g0=nG&8191,h0=nG>>>13,mG=R[9]|0,b0=mG&8191,c0=mG>>>13;K.negative=W.negative^V.negative,K.length=19,A=Math.imul(y,j0),Q=Math.imul(y,P0),Q=Q+Math.imul(x,j0)|0,F=Math.imul(x,P0);var tJ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(tJ>>>26)|0,tJ&=67108863,A=Math.imul(l,j0),Q=Math.imul(l,P0),Q=Q+Math.imul(e,j0)|0,F=Math.imul(e,P0),A=A+Math.imul(y,B0)|0,Q=Q+Math.imul(y,L0)|0,Q=Q+Math.imul(x,B0)|0,F=F+Math.imul(x,L0)|0;var aJ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(aJ>>>26)|0,aJ&=67108863,A=Math.imul($0,j0),Q=Math.imul($0,P0),Q=Q+Math.imul(Z0,j0)|0,F=Math.imul(Z0,P0),A=A+Math.imul(l,B0)|0,Q=Q+Math.imul(l,L0)|0,Q=Q+Math.imul(e,B0)|0,F=F+Math.imul(e,L0)|0,A=A+Math.imul(y,S0)|0,Q=Q+Math.imul(y,C0)|0,Q=Q+Math.imul(x,S0)|0,F=F+Math.imul(x,C0)|0;var eJ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(eJ>>>26)|0,eJ&=67108863,A=Math.imul(H0,j0),Q=Math.imul(H0,P0),Q=Q+Math.imul(Q0,j0)|0,F=Math.imul(Q0,P0),A=A+Math.imul($0,B0)|0,Q=Q+Math.imul($0,L0)|0,Q=Q+Math.imul(Z0,B0)|0,F=F+Math.imul(Z0,L0)|0,A=A+Math.imul(l,S0)|0,Q=Q+Math.imul(l,C0)|0,Q=Q+Math.imul(e,S0)|0,F=F+Math.imul(e,C0)|0,A=A+Math.imul(y,w0)|0,Q=Q+Math.imul(y,E0)|0,Q=Q+Math.imul(x,w0)|0,F=F+Math.imul(x,E0)|0;var $Z=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+($Z>>>26)|0,$Z&=67108863,A=Math.imul(U0,j0),Q=Math.imul(U0,P0),Q=Q+Math.imul(V0,j0)|0,F=Math.imul(V0,P0),A=A+Math.imul(H0,B0)|0,Q=Q+Math.imul(H0,L0)|0,Q=Q+Math.imul(Q0,B0)|0,F=F+Math.imul(Q0,L0)|0,A=A+Math.imul($0,S0)|0,Q=Q+Math.imul($0,C0)|0,Q=Q+Math.imul(Z0,S0)|0,F=F+Math.imul(Z0,C0)|0,A=A+Math.imul(l,w0)|0,Q=Q+Math.imul(l,E0)|0,Q=Q+Math.imul(e,w0)|0,F=F+Math.imul(e,E0)|0,A=A+Math.imul(y,T0)|0,Q=Q+Math.imul(y,N0)|0,Q=Q+Math.imul(x,T0)|0,F=F+Math.imul(x,N0)|0;var JZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(JZ>>>26)|0,JZ&=67108863,A=Math.imul(z0,j0),Q=Math.imul(z0,P0),Q=Q+Math.imul(O0,j0)|0,F=Math.imul(O0,P0),A=A+Math.imul(U0,B0)|0,Q=Q+Math.imul(U0,L0)|0,Q=Q+Math.imul(V0,B0)|0,F=F+Math.imul(V0,L0)|0,A=A+Math.imul(H0,S0)|0,Q=Q+Math.imul(H0,C0)|0,Q=Q+Math.imul(Q0,S0)|0,F=F+Math.imul(Q0,C0)|0,A=A+Math.imul($0,w0)|0,Q=Q+Math.imul($0,E0)|0,Q=Q+Math.imul(Z0,w0)|0,F=F+Math.imul(Z0,E0)|0,A=A+Math.imul(l,T0)|0,Q=Q+Math.imul(l,N0)|0,Q=Q+Math.imul(e,T0)|0,F=F+Math.imul(e,N0)|0,A=A+Math.imul(y,v0)|0,Q=Q+Math.imul(y,D0)|0,Q=Q+Math.imul(x,v0)|0,F=F+Math.imul(x,D0)|0;var ZZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(ZZ>>>26)|0,ZZ&=67108863,A=Math.imul(K0,j0),Q=Math.imul(K0,P0),Q=Q+Math.imul(M0,j0)|0,F=Math.imul(M0,P0),A=A+Math.imul(z0,B0)|0,Q=Q+Math.imul(z0,L0)|0,Q=Q+Math.imul(O0,B0)|0,F=F+Math.imul(O0,L0)|0,A=A+Math.imul(U0,S0)|0,Q=Q+Math.imul(U0,C0)|0,Q=Q+Math.imul(V0,S0)|0,F=F+Math.imul(V0,C0)|0,A=A+Math.imul(H0,w0)|0,Q=Q+Math.imul(H0,E0)|0,Q=Q+Math.imul(Q0,w0)|0,F=F+Math.imul(Q0,E0)|0,A=A+Math.imul($0,T0)|0,Q=Q+Math.imul($0,N0)|0,Q=Q+Math.imul(Z0,T0)|0,F=F+Math.imul(Z0,N0)|0,A=A+Math.imul(l,v0)|0,Q=Q+Math.imul(l,D0)|0,Q=Q+Math.imul(e,v0)|0,F=F+Math.imul(e,D0)|0,A=A+Math.imul(y,k0)|0,Q=Q+Math.imul(y,y0)|0,Q=Q+Math.imul(x,k0)|0,F=F+Math.imul(x,y0)|0;var GZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(GZ>>>26)|0,GZ&=67108863,A=Math.imul(_0,j0),Q=Math.imul(_0,P0),Q=Q+Math.imul(A0,j0)|0,F=Math.imul(A0,P0),A=A+Math.imul(K0,B0)|0,Q=Q+Math.imul(K0,L0)|0,Q=Q+Math.imul(M0,B0)|0,F=F+Math.imul(M0,L0)|0,A=A+Math.imul(z0,S0)|0,Q=Q+Math.imul(z0,C0)|0,Q=Q+Math.imul(O0,S0)|0,F=F+Math.imul(O0,C0)|0,A=A+Math.imul(U0,w0)|0,Q=Q+Math.imul(U0,E0)|0,Q=Q+Math.imul(V0,w0)|0,F=F+Math.imul(V0,E0)|0,A=A+Math.imul(H0,T0)|0,Q=Q+Math.imul(H0,N0)|0,Q=Q+Math.imul(Q0,T0)|0,F=F+Math.imul(Q0,N0)|0,A=A+Math.imul($0,v0)|0,Q=Q+Math.imul($0,D0)|0,Q=Q+Math.imul(Z0,v0)|0,F=F+Math.imul(Z0,D0)|0,A=A+Math.imul(l,k0)|0,Q=Q+Math.imul(l,y0)|0,Q=Q+Math.imul(e,k0)|0,F=F+Math.imul(e,y0)|0,A=A+Math.imul(y,x0)|0,Q=Q+Math.imul(y,f0)|0,Q=Q+Math.imul(x,x0)|0,F=F+Math.imul(x,f0)|0;var XZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(XZ>>>26)|0,XZ&=67108863,A=Math.imul(F0,j0),Q=Math.imul(F0,P0),Q=Q+Math.imul(R0,j0)|0,F=Math.imul(R0,P0),A=A+Math.imul(_0,B0)|0,Q=Q+Math.imul(_0,L0)|0,Q=Q+Math.imul(A0,B0)|0,F=F+Math.imul(A0,L0)|0,A=A+Math.imul(K0,S0)|0,Q=Q+Math.imul(K0,C0)|0,Q=Q+Math.imul(M0,S0)|0,F=F+Math.imul(M0,C0)|0,A=A+Math.imul(z0,w0)|0,Q=Q+Math.imul(z0,E0)|0,Q=Q+Math.imul(O0,w0)|0,F=F+Math.imul(O0,E0)|0,A=A+Math.imul(U0,T0)|0,Q=Q+Math.imul(U0,N0)|0,Q=Q+Math.imul(V0,T0)|0,F=F+Math.imul(V0,N0)|0,A=A+Math.imul(H0,v0)|0,Q=Q+Math.imul(H0,D0)|0,Q=Q+Math.imul(Q0,v0)|0,F=F+Math.imul(Q0,D0)|0,A=A+Math.imul($0,k0)|0,Q=Q+Math.imul($0,y0)|0,Q=Q+Math.imul(Z0,k0)|0,F=F+Math.imul(Z0,y0)|0,A=A+Math.imul(l,x0)|0,Q=Q+Math.imul(l,f0)|0,Q=Q+Math.imul(e,x0)|0,F=F+Math.imul(e,f0)|0,A=A+Math.imul(y,g0)|0,Q=Q+Math.imul(y,h0)|0,Q=Q+Math.imul(x,g0)|0,F=F+Math.imul(x,h0)|0;var YZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(YZ>>>26)|0,YZ&=67108863,A=Math.imul(I0,j0),Q=Math.imul(I0,P0),Q=Q+Math.imul(q0,j0)|0,F=Math.imul(q0,P0),A=A+Math.imul(F0,B0)|0,Q=Q+Math.imul(F0,L0)|0,Q=Q+Math.imul(R0,B0)|0,F=F+Math.imul(R0,L0)|0,A=A+Math.imul(_0,S0)|0,Q=Q+Math.imul(_0,C0)|0,Q=Q+Math.imul(A0,S0)|0,F=F+Math.imul(A0,C0)|0,A=A+Math.imul(K0,w0)|0,Q=Q+Math.imul(K0,E0)|0,Q=Q+Math.imul(M0,w0)|0,F=F+Math.imul(M0,E0)|0,A=A+Math.imul(z0,T0)|0,Q=Q+Math.imul(z0,N0)|0,Q=Q+Math.imul(O0,T0)|0,F=F+Math.imul(O0,N0)|0,A=A+Math.imul(U0,v0)|0,Q=Q+Math.imul(U0,D0)|0,Q=Q+Math.imul(V0,v0)|0,F=F+Math.imul(V0,D0)|0,A=A+Math.imul(H0,k0)|0,Q=Q+Math.imul(H0,y0)|0,Q=Q+Math.imul(Q0,k0)|0,F=F+Math.imul(Q0,y0)|0,A=A+Math.imul($0,x0)|0,Q=Q+Math.imul($0,f0)|0,Q=Q+Math.imul(Z0,x0)|0,F=F+Math.imul(Z0,f0)|0,A=A+Math.imul(l,g0)|0,Q=Q+Math.imul(l,h0)|0,Q=Q+Math.imul(e,g0)|0,F=F+Math.imul(e,h0)|0,A=A+Math.imul(y,b0)|0,Q=Q+Math.imul(y,c0)|0,Q=Q+Math.imul(x,b0)|0,F=F+Math.imul(x,c0)|0;var WZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(WZ>>>26)|0,WZ&=67108863,A=Math.imul(I0,B0),Q=Math.imul(I0,L0),Q=Q+Math.imul(q0,B0)|0,F=Math.imul(q0,L0),A=A+Math.imul(F0,S0)|0,Q=Q+Math.imul(F0,C0)|0,Q=Q+Math.imul(R0,S0)|0,F=F+Math.imul(R0,C0)|0,A=A+Math.imul(_0,w0)|0,Q=Q+Math.imul(_0,E0)|0,Q=Q+Math.imul(A0,w0)|0,F=F+Math.imul(A0,E0)|0,A=A+Math.imul(K0,T0)|0,Q=Q+Math.imul(K0,N0)|0,Q=Q+Math.imul(M0,T0)|0,F=F+Math.imul(M0,N0)|0,A=A+Math.imul(z0,v0)|0,Q=Q+Math.imul(z0,D0)|0,Q=Q+Math.imul(O0,v0)|0,F=F+Math.imul(O0,D0)|0,A=A+Math.imul(U0,k0)|0,Q=Q+Math.imul(U0,y0)|0,Q=Q+Math.imul(V0,k0)|0,F=F+Math.imul(V0,y0)|0,A=A+Math.imul(H0,x0)|0,Q=Q+Math.imul(H0,f0)|0,Q=Q+Math.imul(Q0,x0)|0,F=F+Math.imul(Q0,f0)|0,A=A+Math.imul($0,g0)|0,Q=Q+Math.imul($0,h0)|0,Q=Q+Math.imul(Z0,g0)|0,F=F+Math.imul(Z0,h0)|0,A=A+Math.imul(l,b0)|0,Q=Q+Math.imul(l,c0)|0,Q=Q+Math.imul(e,b0)|0,F=F+Math.imul(e,c0)|0;var HZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(HZ>>>26)|0,HZ&=67108863,A=Math.imul(I0,S0),Q=Math.imul(I0,C0),Q=Q+Math.imul(q0,S0)|0,F=Math.imul(q0,C0),A=A+Math.imul(F0,w0)|0,Q=Q+Math.imul(F0,E0)|0,Q=Q+Math.imul(R0,w0)|0,F=F+Math.imul(R0,E0)|0,A=A+Math.imul(_0,T0)|0,Q=Q+Math.imul(_0,N0)|0,Q=Q+Math.imul(A0,T0)|0,F=F+Math.imul(A0,N0)|0,A=A+Math.imul(K0,v0)|0,Q=Q+Math.imul(K0,D0)|0,Q=Q+Math.imul(M0,v0)|0,F=F+Math.imul(M0,D0)|0,A=A+Math.imul(z0,k0)|0,Q=Q+Math.imul(z0,y0)|0,Q=Q+Math.imul(O0,k0)|0,F=F+Math.imul(O0,y0)|0,A=A+Math.imul(U0,x0)|0,Q=Q+Math.imul(U0,f0)|0,Q=Q+Math.imul(V0,x0)|0,F=F+Math.imul(V0,f0)|0,A=A+Math.imul(H0,g0)|0,Q=Q+Math.imul(H0,h0)|0,Q=Q+Math.imul(Q0,g0)|0,F=F+Math.imul(Q0,h0)|0,A=A+Math.imul($0,b0)|0,Q=Q+Math.imul($0,c0)|0,Q=Q+Math.imul(Z0,b0)|0,F=F+Math.imul(Z0,c0)|0;var QZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(QZ>>>26)|0,QZ&=67108863,A=Math.imul(I0,w0),Q=Math.imul(I0,E0),Q=Q+Math.imul(q0,w0)|0,F=Math.imul(q0,E0),A=A+Math.imul(F0,T0)|0,Q=Q+Math.imul(F0,N0)|0,Q=Q+Math.imul(R0,T0)|0,F=F+Math.imul(R0,N0)|0,A=A+Math.imul(_0,v0)|0,Q=Q+Math.imul(_0,D0)|0,Q=Q+Math.imul(A0,v0)|0,F=F+Math.imul(A0,D0)|0,A=A+Math.imul(K0,k0)|0,Q=Q+Math.imul(K0,y0)|0,Q=Q+Math.imul(M0,k0)|0,F=F+Math.imul(M0,y0)|0,A=A+Math.imul(z0,x0)|0,Q=Q+Math.imul(z0,f0)|0,Q=Q+Math.imul(O0,x0)|0,F=F+Math.imul(O0,f0)|0,A=A+Math.imul(U0,g0)|0,Q=Q+Math.imul(U0,h0)|0,Q=Q+Math.imul(V0,g0)|0,F=F+Math.imul(V0,h0)|0,A=A+Math.imul(H0,b0)|0,Q=Q+Math.imul(H0,c0)|0,Q=Q+Math.imul(Q0,b0)|0,F=F+Math.imul(Q0,c0)|0;var UZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(UZ>>>26)|0,UZ&=67108863,A=Math.imul(I0,T0),Q=Math.imul(I0,N0),Q=Q+Math.imul(q0,T0)|0,F=Math.imul(q0,N0),A=A+Math.imul(F0,v0)|0,Q=Q+Math.imul(F0,D0)|0,Q=Q+Math.imul(R0,v0)|0,F=F+Math.imul(R0,D0)|0,A=A+Math.imul(_0,k0)|0,Q=Q+Math.imul(_0,y0)|0,Q=Q+Math.imul(A0,k0)|0,F=F+Math.imul(A0,y0)|0,A=A+Math.imul(K0,x0)|0,Q=Q+Math.imul(K0,f0)|0,Q=Q+Math.imul(M0,x0)|0,F=F+Math.imul(M0,f0)|0,A=A+Math.imul(z0,g0)|0,Q=Q+Math.imul(z0,h0)|0,Q=Q+Math.imul(O0,g0)|0,F=F+Math.imul(O0,h0)|0,A=A+Math.imul(U0,b0)|0,Q=Q+Math.imul(U0,c0)|0,Q=Q+Math.imul(V0,b0)|0,F=F+Math.imul(V0,c0)|0;var VZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(VZ>>>26)|0,VZ&=67108863,A=Math.imul(I0,v0),Q=Math.imul(I0,D0),Q=Q+Math.imul(q0,v0)|0,F=Math.imul(q0,D0),A=A+Math.imul(F0,k0)|0,Q=Q+Math.imul(F0,y0)|0,Q=Q+Math.imul(R0,k0)|0,F=F+Math.imul(R0,y0)|0,A=A+Math.imul(_0,x0)|0,Q=Q+Math.imul(_0,f0)|0,Q=Q+Math.imul(A0,x0)|0,F=F+Math.imul(A0,f0)|0,A=A+Math.imul(K0,g0)|0,Q=Q+Math.imul(K0,h0)|0,Q=Q+Math.imul(M0,g0)|0,F=F+Math.imul(M0,h0)|0,A=A+Math.imul(z0,b0)|0,Q=Q+Math.imul(z0,c0)|0,Q=Q+Math.imul(O0,b0)|0,F=F+Math.imul(O0,c0)|0;var zZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,A=Math.imul(I0,k0),Q=Math.imul(I0,y0),Q=Q+Math.imul(q0,k0)|0,F=Math.imul(q0,y0),A=A+Math.imul(F0,x0)|0,Q=Q+Math.imul(F0,f0)|0,Q=Q+Math.imul(R0,x0)|0,F=F+Math.imul(R0,f0)|0,A=A+Math.imul(_0,g0)|0,Q=Q+Math.imul(_0,h0)|0,Q=Q+Math.imul(A0,g0)|0,F=F+Math.imul(A0,h0)|0,A=A+Math.imul(K0,b0)|0,Q=Q+Math.imul(K0,c0)|0,Q=Q+Math.imul(M0,b0)|0,F=F+Math.imul(M0,c0)|0;var OZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(OZ>>>26)|0,OZ&=67108863,A=Math.imul(I0,x0),Q=Math.imul(I0,f0),Q=Q+Math.imul(q0,x0)|0,F=Math.imul(q0,f0),A=A+Math.imul(F0,g0)|0,Q=Q+Math.imul(F0,h0)|0,Q=Q+Math.imul(R0,g0)|0,F=F+Math.imul(R0,h0)|0,A=A+Math.imul(_0,b0)|0,Q=Q+Math.imul(_0,c0)|0,Q=Q+Math.imul(A0,b0)|0,F=F+Math.imul(A0,c0)|0;var KZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(KZ>>>26)|0,KZ&=67108863,A=Math.imul(I0,g0),Q=Math.imul(I0,h0),Q=Q+Math.imul(q0,g0)|0,F=Math.imul(q0,h0),A=A+Math.imul(F0,b0)|0,Q=Q+Math.imul(F0,c0)|0,Q=Q+Math.imul(R0,b0)|0,F=F+Math.imul(R0,c0)|0;var MZ=(L+A|0)+((Q&8191)<<13)|0;L=(F+(Q>>>13)|0)+(MZ>>>26)|0,MZ&=67108863,A=Math.imul(I0,b0),Q=Math.imul(I0,c0),Q=Q+Math.imul(q0,b0)|0,F=Math.imul(q0,c0);var _Z=(L+A|0)+((Q&8191)<<13)|0;if(L=(F+(Q>>>13)|0)+(_Z>>>26)|0,_Z&=67108863,P[0]=tJ,P[1]=aJ,P[2]=eJ,P[3]=$Z,P[4]=JZ,P[5]=ZZ,P[6]=GZ,P[7]=XZ,P[8]=YZ,P[9]=WZ,P[10]=HZ,P[11]=QZ,P[12]=UZ,P[13]=VZ,P[14]=zZ,P[15]=OZ,P[16]=KZ,P[17]=MZ,P[18]=_Z,L!==0)P[19]=L,K.length++;return K};if(!Math.imul)C=S;function T(q,W,V){V.negative=W.negative^q.negative,V.length=q.length+W.length;var K=0,M=0;for(var R=0;R<V.length-1;R++){var P=M;M=0;var L=K&67108863,A=Math.min(R,W.length-1);for(var Q=Math.max(0,R-q.length+1);Q<=A;Q++){var F=R-Q,k=q.words[F]|0,y=W.words[Q]|0,x=k*y,u=x&67108863;P=P+(x/67108864|0)|0,u=u+L|0,L=u&67108863,P=P+(u>>>26)|0,M+=P>>>26,P&=67108863}V.words[R]=L,K=P,P=M}if(K!==0)V.words[R]=K;else V.length--;return V.strip()}function E(q,W,V){var K=new D;return K.mulp(q,W,V)}X.prototype.mulTo=function(W,V){var K,M=this.length+W.length;if(this.length===10&&W.length===10)K=C(this,W,V);else if(M<63)K=S(this,W,V);else if(M<1024)K=T(this,W,V);else K=E(this,W,V);return K};function D(q,W){this.x=q,this.y=W}D.prototype.makeRBT=function(W){var V=Array(W),K=X.prototype._countBits(W)-1;for(var M=0;M<W;M++)V[M]=this.revBin(M,K,W);return V},D.prototype.revBin=function(W,V,K){if(W===0||W===K-1)return W;var M=0;for(var R=0;R<V;R++)M|=(W&1)<<V-R-1,W>>=1;return M},D.prototype.permute=function(W,V,K,M,R,P){for(var L=0;L<P;L++)M[L]=V[W[L]],R[L]=K[W[L]]},D.prototype.transform=function(W,V,K,M,R,P){this.permute(P,W,V,K,M,R);for(var L=1;L<R;L<<=1){var A=L<<1,Q=Math.cos(2*Math.PI/A),F=Math.sin(2*Math.PI/A);for(var k=0;k<R;k+=A){var y=Q,x=F;for(var u=0;u<L;u++){var l=K[k+u],e=M[k+u],M$=K[k+u+L],$0=M[k+u+L],Z0=y*M$-x*$0;if($0=y*$0+x*M$,M$=Z0,K[k+u]=l+M$,M[k+u]=e+$0,K[k+u+L]=l-M$,M[k+u+L]=e-$0,u!==A)Z0=Q*y-F*x,x=Q*x+F*y,y=Z0}}}},D.prototype.guessLen13b=function(W,V){var K=Math.max(V,W)|1,M=K&1,R=0;for(K=K/2|0;K;K=K>>>1)R++;return 1<<R+1+M},D.prototype.conjugate=function(W,V,K){if(K<=1)return;for(var M=0;M<K/2;M++){var R=W[M];W[M]=W[K-M-1],W[K-M-1]=R,R=V[M],V[M]=-V[K-M-1],V[K-M-1]=-R}},D.prototype.normalize13b=function(W,V){var K=0;for(var M=0;M<V/2;M++){var R=Math.round(W[2*M+1]/V)*8192+Math.round(W[2*M]/V)+K;if(W[M]=R&67108863,R<67108864)K=0;else K=R/67108864|0}return W},D.prototype.convert13b=function(W,V,K,M){var R=0;for(var P=0;P<V;P++)R=R+(W[P]|0),K[2*P]=R&8191,R=R>>>13,K[2*P+1]=R&8191,R=R>>>13;for(P=2*V;P<M;++P)K[P]=0;Z(R===0),Z((R&-8192)===0)},D.prototype.stub=function(W){var V=Array(W);for(var K=0;K<W;K++)V[K]=0;return V},D.prototype.mulp=function(W,V,K){var M=2*this.guessLen13b(W.length,V.length),R=this.makeRBT(M),P=this.stub(M),L=Array(M),A=Array(M),Q=Array(M),F=Array(M),k=Array(M),y=Array(M),x=K.words;x.length=M,this.convert13b(W.words,W.length,L,M),this.convert13b(V.words,V.length,F,M),this.transform(L,P,A,Q,M,R),this.transform(F,P,k,y,M,R);for(var u=0;u<M;u++){var l=A[u]*k[u]-Q[u]*y[u];Q[u]=A[u]*y[u]+Q[u]*k[u],A[u]=l}return this.conjugate(A,Q,M),this.transform(A,Q,x,P,M,R),this.conjugate(x,P,M),this.normalize13b(x,M),K.negative=W.negative^V.negative,K.length=W.length+V.length,K.strip()},X.prototype.mul=function(W){var V=new X(null);return V.words=Array(this.length+W.length),this.mulTo(W,V)},X.prototype.mulf=function(W){var V=new X(null);return V.words=Array(this.length+W.length),E(this,W,V)},X.prototype.imul=function(W){return this.clone().mulTo(W,this)},X.prototype.imuln=function(W){Z(typeof W==="number"),Z(W<67108864);var V=0;for(var K=0;K<this.length;K++){var M=(this.words[K]|0)*W,R=(M&67108863)+(V&67108863);V>>=26,V+=M/67108864|0,V+=R>>>26,this.words[K]=R&67108863}if(V!==0)this.words[K]=V,this.length++;return this.length=W===0?1:this.length,this},X.prototype.muln=function(W){return this.clone().imuln(W)},X.prototype.sqr=function(){return this.mul(this)},X.prototype.isqr=function(){return this.imul(this.clone())},X.prototype.pow=function(W){var V=B(W);if(V.length===0)return new X(1);var K=this;for(var M=0;M<V.length;M++,K=K.sqr())if(V[M]!==0)break;if(++M<V.length)for(var R=K.sqr();M<V.length;M++,R=R.sqr()){if(V[M]===0)continue;K=K.mul(R)}return K},X.prototype.iushln=function(W){Z(typeof W==="number"&&W>=0);var V=W%26,K=(W-V)/26,M=67108863>>>26-V<<26-V,R;if(V!==0){var P=0;for(R=0;R<this.length;R++){var L=this.words[R]&M,A=(this.words[R]|0)-L<<V;this.words[R]=A|P,P=L>>>26-V}if(P)this.words[R]=P,this.length++}if(K!==0){for(R=this.length-1;R>=0;R--)this.words[R+K]=this.words[R];for(R=0;R<K;R++)this.words[R]=0;this.length+=K}return this.strip()},X.prototype.ishln=function(W){return Z(this.negative===0),this.iushln(W)},X.prototype.iushrn=function(W,V,K){Z(typeof W==="number"&&W>=0);var M;if(V)M=(V-V%26)/26;else M=0;var R=W%26,P=Math.min((W-R)/26,this.length),L=67108863^67108863>>>R<<R,A=K;if(M-=P,M=Math.max(0,M),A){for(var Q=0;Q<P;Q++)A.words[Q]=this.words[Q];A.length=P}if(P===0);else if(this.length>P){this.length-=P;for(Q=0;Q<this.length;Q++)this.words[Q]=this.words[Q+P]}else this.words[0]=0,this.length=1;var F=0;for(Q=this.length-1;Q>=0&&(F!==0||Q>=M);Q--){var k=this.words[Q]|0;this.words[Q]=F<<26-R|k>>>R,F=k&L}if(A&&F!==0)A.words[A.length++]=F;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},X.prototype.ishrn=function(W,V,K){return Z(this.negative===0),this.iushrn(W,V,K)},X.prototype.shln=function(W){return this.clone().ishln(W)},X.prototype.ushln=function(W){return this.clone().iushln(W)},X.prototype.shrn=function(W){return this.clone().ishrn(W)},X.prototype.ushrn=function(W){return this.clone().iushrn(W)},X.prototype.testn=function(W){Z(typeof W==="number"&&W>=0);var V=W%26,K=(W-V)/26,M=1<<V;if(this.length<=K)return!1;var R=this.words[K];return!!(R&M)},X.prototype.imaskn=function(W){Z(typeof W==="number"&&W>=0);var V=W%26,K=(W-V)/26;if(Z(this.negative===0,"imaskn works only with positive numbers"),this.length<=K)return this;if(V!==0)K++;if(this.length=Math.min(K,this.length),V!==0){var M=67108863^67108863>>>V<<V;this.words[this.length-1]&=M}return this.strip()},X.prototype.maskn=function(W){return this.clone().imaskn(W)},X.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)},X.prototype._iaddn=function(W){this.words[0]+=W;for(var V=0;V<this.length&&this.words[V]>=67108864;V++)if(this.words[V]-=67108864,V===this.length-1)this.words[V+1]=1;else this.words[V+1]++;return this.length=Math.max(this.length,V+1),this},X.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 V=0;V<this.length&&this.words[V]<0;V++)this.words[V]+=67108864,this.words[V+1]-=1;return this.strip()},X.prototype.addn=function(W){return this.clone().iaddn(W)},X.prototype.subn=function(W){return this.clone().isubn(W)},X.prototype.iabs=function(){return this.negative=0,this},X.prototype.abs=function(){return this.clone().iabs()},X.prototype._ishlnsubmul=function(W,V,K){var M=W.length+K,R;this._expand(M);var P,L=0;for(R=0;R<W.length;R++){P=(this.words[R+K]|0)+L;var A=(W.words[R]|0)*V;P-=A&67108863,L=(P>>26)-(A/67108864|0),this.words[R+K]=P&67108863}for(;R<this.length-K;R++)P=(this.words[R+K]|0)+L,L=P>>26,this.words[R+K]=P&67108863;if(L===0)return this.strip();Z(L===-1),L=0;for(R=0;R<this.length;R++)P=-(this.words[R]|0)+L,L=P>>26,this.words[R]=P&67108863;return this.negative=1,this.strip()},X.prototype._wordDiv=function(W,V){var K=this.length-W.length,M=this.clone(),R=W,P=R.words[R.length-1]|0,L=this._countBits(P);if(K=26-L,K!==0)R=R.ushln(K),M.iushln(K),P=R.words[R.length-1]|0;var A=M.length-R.length,Q;if(V!=="mod"){Q=new X(null),Q.length=A+1,Q.words=Array(Q.length);for(var F=0;F<Q.length;F++)Q.words[F]=0}var k=M.clone()._ishlnsubmul(R,1,A);if(k.negative===0){if(M=k,Q)Q.words[A]=1}for(var y=A-1;y>=0;y--){var x=(M.words[R.length+y]|0)*67108864+(M.words[R.length+y-1]|0);x=Math.min(x/P|0,67108863),M._ishlnsubmul(R,x,y);while(M.negative!==0)if(x--,M.negative=0,M._ishlnsubmul(R,1,y),!M.isZero())M.negative^=1;if(Q)Q.words[y]=x}if(Q)Q.strip();if(M.strip(),V!=="div"&&K!==0)M.iushrn(K);return{div:Q||null,mod:M}},X.prototype.divmod=function(W,V,K){if(Z(!W.isZero()),this.isZero())return{div:new X(0),mod:new X(0)};var M,R,P;if(this.negative!==0&&W.negative===0){if(P=this.neg().divmod(W,V),V!=="mod")M=P.div.neg();if(V!=="div"){if(R=P.mod.neg(),K&&R.negative!==0)R.iadd(W)}return{div:M,mod:R}}if(this.negative===0&&W.negative!==0){if(P=this.divmod(W.neg(),V),V!=="mod")M=P.div.neg();return{div:M,mod:P.mod}}if((this.negative&W.negative)!==0){if(P=this.neg().divmod(W.neg(),V),V!=="div"){if(R=P.mod.neg(),K&&R.negative!==0)R.isub(W)}return{div:P.div,mod:R}}if(W.length>this.length||this.cmp(W)<0)return{div:new X(0),mod:this};if(W.length===1){if(V==="div")return{div:this.divn(W.words[0]),mod:null};if(V==="mod")return{div:null,mod:new X(this.modn(W.words[0]))};return{div:this.divn(W.words[0]),mod:new X(this.modn(W.words[0]))}}return this._wordDiv(W,V)},X.prototype.div=function(W){return this.divmod(W,"div",!1).div},X.prototype.mod=function(W){return this.divmod(W,"mod",!1).mod},X.prototype.umod=function(W){return this.divmod(W,"mod",!0).mod},X.prototype.divRound=function(W){var V=this.divmod(W);if(V.mod.isZero())return V.div;var K=V.div.negative!==0?V.mod.isub(W):V.mod,M=W.ushrn(1),R=W.andln(1),P=K.cmp(M);if(P<0||R===1&&P===0)return V.div;return V.div.negative!==0?V.div.isubn(1):V.div.iaddn(1)},X.prototype.modn=function(W){Z(W<=67108863);var V=67108864%W,K=0;for(var M=this.length-1;M>=0;M--)K=(V*K+(this.words[M]|0))%W;return K},X.prototype.idivn=function(W){Z(W<=67108863);var V=0;for(var K=this.length-1;K>=0;K--){var M=(this.words[K]|0)+V*67108864;this.words[K]=M/W|0,V=M%W}return this.strip()},X.prototype.divn=function(W){return this.clone().idivn(W)},X.prototype.egcd=function(W){Z(W.negative===0),Z(!W.isZero());var V=this,K=W.clone();if(V.negative!==0)V=V.umod(W);else V=V.clone();var M=new X(1),R=new X(0),P=new X(0),L=new X(1),A=0;while(V.isEven()&&K.isEven())V.iushrn(1),K.iushrn(1),++A;var Q=K.clone(),F=V.clone();while(!V.isZero()){for(var k=0,y=1;(V.words[0]&y)===0&&k<26;++k,y<<=1);if(k>0){V.iushrn(k);while(k-- >0){if(M.isOdd()||R.isOdd())M.iadd(Q),R.isub(F);M.iushrn(1),R.iushrn(1)}}for(var x=0,u=1;(K.words[0]&u)===0&&x<26;++x,u<<=1);if(x>0){K.iushrn(x);while(x-- >0){if(P.isOdd()||L.isOdd())P.iadd(Q),L.isub(F);P.iushrn(1),L.iushrn(1)}}if(V.cmp(K)>=0)V.isub(K),M.isub(P),R.isub(L);else K.isub(V),P.isub(M),L.isub(R)}return{a:P,b:L,gcd:K.iushln(A)}},X.prototype._invmp=function(W){Z(W.negative===0),Z(!W.isZero());var V=this,K=W.clone();if(V.negative!==0)V=V.umod(W);else V=V.clone();var M=new X(1),R=new X(0),P=K.clone();while(V.cmpn(1)>0&&K.cmpn(1)>0){for(var L=0,A=1;(V.words[0]&A)===0&&L<26;++L,A<<=1);if(L>0){V.iushrn(L);while(L-- >0){if(M.isOdd())M.iadd(P);M.iushrn(1)}}for(var Q=0,F=1;(K.words[0]&F)===0&&Q<26;++Q,F<<=1);if(Q>0){K.iushrn(Q);while(Q-- >0){if(R.isOdd())R.iadd(P);R.iushrn(1)}}if(V.cmp(K)>=0)V.isub(K),M.isub(R);else K.isub(V),R.isub(M)}var k;if(V.cmpn(1)===0)k=M;else k=R;if(k.cmpn(0)<0)k.iadd(W);return k},X.prototype.gcd=function(W){if(this.isZero())return W.abs();if(W.isZero())return this.abs();var V=this.clone(),K=W.clone();V.negative=0,K.negative=0;for(var M=0;V.isEven()&&K.isEven();M++)V.iushrn(1),K.iushrn(1);do{while(V.isEven())V.iushrn(1);while(K.isEven())K.iushrn(1);var R=V.cmp(K);if(R<0){var P=V;V=K,K=P}else if(R===0||K.cmpn(1)===0)break;V.isub(K)}while(!0);return K.iushln(M)},X.prototype.invm=function(W){return this.egcd(W).a.umod(W)},X.prototype.isEven=function(){return(this.words[0]&1)===0},X.prototype.isOdd=function(){return(this.words[0]&1)===1},X.prototype.andln=function(W){return this.words[0]&W},X.prototype.bincn=function(W){Z(typeof W==="number");var V=W%26,K=(W-V)/26,M=1<<V;if(this.length<=K)return this._expand(K+1),this.words[K]|=M,this;var R=M;for(var P=K;R!==0&&P<this.length;P++){var L=this.words[P]|0;L+=R,R=L>>>26,L&=67108863,this.words[P]=L}if(R!==0)this.words[P]=R,this.length++;return this},X.prototype.isZero=function(){return this.length===1&&this.words[0]===0},X.prototype.cmpn=function(W){var V=W<0;if(this.negative!==0&&!V)return-1;if(this.negative===0&&V)return 1;this.strip();var K;if(this.length>1)K=1;else{if(V)W=-W;Z(W<=67108863,"Number is too big");var M=this.words[0]|0;K=M===W?0:M<W?-1:1}if(this.negative!==0)return-K|0;return K},X.prototype.cmp=function(W){if(this.negative!==0&&W.negative===0)return-1;if(this.negative===0&&W.negative!==0)return 1;var V=this.ucmp(W);if(this.negative!==0)return-V|0;return V},X.prototype.ucmp=function(W){if(this.length>W.length)return 1;if(this.length<W.length)return-1;var V=0;for(var K=this.length-1;K>=0;K--){var M=this.words[K]|0,R=W.words[K]|0;if(M===R)continue;if(M<R)V=-1;else if(M>R)V=1;break}return V},X.prototype.gtn=function(W){return this.cmpn(W)===1},X.prototype.gt=function(W){return this.cmp(W)===1},X.prototype.gten=function(W){return this.cmpn(W)>=0},X.prototype.gte=function(W){return this.cmp(W)>=0},X.prototype.ltn=function(W){return this.cmpn(W)===-1},X.prototype.lt=function(W){return this.cmp(W)===-1},X.prototype.lten=function(W){return this.cmpn(W)<=0},X.prototype.lte=function(W){return this.cmp(W)<=0},X.prototype.eqn=function(W){return this.cmpn(W)===0},X.prototype.eq=function(W){return this.cmp(W)===0},X.red=function(W){return new o(W)},X.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)},X.prototype.fromRed=function(){return Z(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},X.prototype._forceRed=function(W){return this.red=W,this},X.prototype.forceRed=function(W){return Z(!this.red,"Already a number in reduction context"),this._forceRed(W)},X.prototype.redAdd=function(W){return Z(this.red,"redAdd works only with red numbers"),this.red.add(this,W)},X.prototype.redIAdd=function(W){return Z(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,W)},X.prototype.redSub=function(W){return Z(this.red,"redSub works only with red numbers"),this.red.sub(this,W)},X.prototype.redISub=function(W){return Z(this.red,"redISub works only with red numbers"),this.red.isub(this,W)},X.prototype.redShl=function(W){return Z(this.red,"redShl works only with red numbers"),this.red.shl(this,W)},X.prototype.redMul=function(W){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,W),this.red.mul(this,W)},X.prototype.redIMul=function(W){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,W),this.red.imul(this,W)},X.prototype.redSqr=function(){return Z(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},X.prototype.redISqr=function(){return Z(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},X.prototype.redSqrt=function(){return Z(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},X.prototype.redInvm=function(){return Z(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},X.prototype.redNeg=function(){return Z(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},X.prototype.redPow=function(W){return Z(this.red&&!W.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,W)};var w={k256:null,p224:null,p192:null,p25519:null};function N(q,W){this.name=q,this.p=new X(W,16),this.n=this.p.bitLength(),this.k=new X(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}N.prototype._tmp=function(){var W=new X(null);return W.words=Array(Math.ceil(this.n/13)),W},N.prototype.ireduce=function(W){var V=W,K;do this.split(V,this.tmp),V=this.imulK(V),V=V.iadd(this.tmp),K=V.bitLength();while(K>this.n);var M=K<this.n?-1:V.ucmp(this.p);if(M===0)V.words[0]=0,V.length=1;else if(M>0)V.isub(this.p);else if(V.strip!==void 0)V.strip();else V._strip();return V},N.prototype.split=function(W,V){W.iushrn(this.n,0,V)},N.prototype.imulK=function(W){return W.imul(this.k)};function p(){N.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}G(p,N),p.prototype.split=function(W,V){var K=4194303,M=Math.min(W.length,9);for(var R=0;R<M;R++)V.words[R]=W.words[R];if(V.length=M,W.length<=9){W.words[0]=0,W.length=1;return}var P=W.words[9];V.words[V.length++]=P&K;for(R=10;R<W.length;R++){var L=W.words[R]|0;W.words[R-10]=(L&K)<<4|P>>>22,P=L}if(P>>>=22,W.words[R-10]=P,P===0&&W.length>10)W.length-=10;else W.length-=9},p.prototype.imulK=function(W){W.words[W.length]=0,W.words[W.length+1]=0,W.length+=2;var V=0;for(var K=0;K<W.length;K++){var M=W.words[K]|0;V+=M*977,W.words[K]=V&67108863,V=M*64+(V/67108864|0)}if(W.words[W.length-1]===0){if(W.length--,W.words[W.length-1]===0)W.length--}return W};function v(){N.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}G(v,N);function b(){N.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}G(b,N);function r(){N.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}G(r,N),r.prototype.imulK=function(W){var V=0;for(var K=0;K<W.length;K++){var M=(W.words[K]|0)*19+V,R=M&67108863;M>>>=26,W.words[K]=R,V=M}if(V!==0)W.words[W.length++]=V;return W},X._prime=function(W){if(w[W])return w[W];var V;if(W==="k256")V=new p;else if(W==="p224")V=new v;else if(W==="p192")V=new b;else if(W==="p25519")V=new r;else throw Error("Unknown prime "+W);return w[W]=V,V};function o(q){if(typeof q==="string"){var W=X._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}o.prototype._verify1=function(W){Z(W.negative===0,"red works only with positives"),Z(W.red,"red works only with red numbers")},o.prototype._verify2=function(W,V){Z((W.negative|V.negative)===0,"red works only with positives"),Z(W.red&&W.red===V.red,"red works only with red numbers")},o.prototype.imod=function(W){if(this.prime)return this.prime.ireduce(W)._forceRed(this);return W.umod(this.m)._forceRed(this)},o.prototype.neg=function(W){if(W.isZero())return W.clone();return this.m.sub(W)._forceRed(this)},o.prototype.add=function(W,V){this._verify2(W,V);var K=W.add(V);if(K.cmp(this.m)>=0)K.isub(this.m);return K._forceRed(this)},o.prototype.iadd=function(W,V){this._verify2(W,V);var K=W.iadd(V);if(K.cmp(this.m)>=0)K.isub(this.m);return K},o.prototype.sub=function(W,V){this._verify2(W,V);var K=W.sub(V);if(K.cmpn(0)<0)K.iadd(this.m);return K._forceRed(this)},o.prototype.isub=function(W,V){this._verify2(W,V);var K=W.isub(V);if(K.cmpn(0)<0)K.iadd(this.m);return K},o.prototype.shl=function(W,V){return this._verify1(W),this.imod(W.ushln(V))},o.prototype.imul=function(W,V){return this._verify2(W,V),this.imod(W.imul(V))},o.prototype.mul=function(W,V){return this._verify2(W,V),this.imod(W.mul(V))},o.prototype.isqr=function(W){return this.imul(W,W.clone())},o.prototype.sqr=function(W){return this.mul(W,W)},o.prototype.sqrt=function(W){if(W.isZero())return W.clone();var V=this.m.andln(3);if(Z(V%2===1),V===3){var K=this.m.add(new X(1)).iushrn(2);return this.pow(W,K)}var M=this.m.subn(1),R=0;while(!M.isZero()&&M.andln(1)===0)R++,M.iushrn(1);Z(!M.isZero());var P=new X(1).toRed(this),L=P.redNeg(),A=this.m.subn(1).iushrn(1),Q=this.m.bitLength();Q=new X(2*Q*Q).toRed(this);while(this.pow(Q,A).cmp(L)!==0)Q.redIAdd(L);var F=this.pow(Q,M),k=this.pow(W,M.addn(1).iushrn(1)),y=this.pow(W,M),x=R;while(y.cmp(P)!==0){var u=y;for(var l=0;u.cmp(P)!==0;l++)u=u.redSqr();Z(l<x);var e=this.pow(F,new X(1).iushln(x-l-1));k=k.redMul(e),F=e.redSqr(),y=y.redMul(F),x=l}return k},o.prototype.invm=function(W){var V=W._invmp(this.m);if(V.negative!==0)return V.negative=0,this.imod(V).redNeg();else return this.imod(V)},o.prototype.pow=function(W,V){if(V.isZero())return new X(1).toRed(this);if(V.cmpn(1)===0)return W.clone();var K=4,M=Array(1<<K);M[0]=new X(1).toRed(this),M[1]=W;for(var R=2;R<M.length;R++)M[R]=this.mul(M[R-1],W);var P=M[0],L=0,A=0,Q=V.bitLength()%26;if(Q===0)Q=26;for(R=V.length-1;R>=0;R--){var F=V.words[R];for(var k=Q-1;k>=0;k--){var y=F>>k&1;if(P!==M[0])P=this.sqr(P);if(y===0&&L===0){A=0;continue}if(L<<=1,L|=y,A++,A!==K&&(R!==0||k!==0))continue;P=this.mul(P,M[L]),A=0,L=0}Q=26}return P},o.prototype.convertTo=function(W){var V=W.umod(this.m);return V===W?V.clone():V},o.prototype.convertFrom=function(W){var V=W.clone();return V.red=null,V},X.mont=function(W){return new u0(W)};function u0(q){if(o.call(this,q),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new X(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)}G(u0,o),u0.prototype.convertTo=function(W){return this.imod(W.ushln(this.shift))},u0.prototype.convertFrom=function(W){var V=this.imod(W.mul(this.rinv));return V.red=null,V},u0.prototype.imul=function(W,V){if(W.isZero()||V.isZero())return W.words[0]=0,W.length=1,W;var K=W.imul(V),M=K.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),R=K.isub(M).iushrn(this.shift),P=R;if(R.cmp(this.m)>=0)P=R.isub(this.m);else if(R.cmpn(0)<0)P=R.iadd(this.m);return P._forceRed(this)},u0.prototype.mul=function(W,V){if(W.isZero()||V.isZero())return new X(0)._forceRed(this);var K=W.mul(V),M=K.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),R=K.isub(M).iushrn(this.shift),P=R;if(R.cmp(this.m)>=0)P=R.isub(this.m);else if(R.cmpn(0)<0)P=R.iadd(this.m);return P._forceRed(this)},u0.prototype.invm=function(W){var V=this.imod(W._invmp(this.m).mul(this.r2));return V._forceRed(this)}})(typeof ZG>"u"||ZG,cY)});var pY=s((tU,XG)=>{if(typeof Object.create==="function")XG.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 XG.exports=function(J,Z){if(Z){J.super_=Z;var G=function(){};G.prototype=Z.prototype,J.prototype=new G,J.prototype.constructor=J}}});var L$=s((aU,YG)=>{try{if(xJ=_$("util"),typeof xJ.inherits!=="function")throw"";YG.exports=xJ.inherits}catch($){YG.exports=pY()}var xJ});var gJ=s((eU,uY)=>{var fJ=_$("buffer"),n$=fJ.Buffer,t0={},a0;for(a0 in fJ){if(!fJ.hasOwnProperty(a0))continue;if(a0==="SlowBuffer"||a0==="Buffer")continue;t0[a0]=fJ[a0]}var m$=t0.Buffer={};for(a0 in n$){if(!n$.hasOwnProperty(a0))continue;if(a0==="allocUnsafe"||a0==="allocUnsafeSlow")continue;m$[a0]=n$[a0]}t0.Buffer.prototype=n$.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 n$($,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 G=n$($);if(!J||J.length===0)G.fill(0);else if(typeof Z==="string")G.fill(J,Z);else G.fill(J);return G};if(!t0.kStringMaxLength)try{t0.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch($){}if(!t0.constants){if(t0.constants={MAX_LENGTH:t0.kMaxLength},t0.kStringMaxLength)t0.constants.MAX_STRING_LENGTH=t0.kStringMaxLength}uY.exports=t0});var hJ=s(($9)=>{var eQ=L$();function e0($){this._reporterState={obj:null,path:[],options:$||{},errors:[]}}$9.Reporter=e0;e0.prototype.isError=function(J){return J instanceof d$};e0.prototype.save=function(){let J=this._reporterState;return{obj:J.obj,pathLen:J.path.length}};e0.prototype.restore=function(J){let Z=this._reporterState;Z.obj=J.obj,Z.path=Z.path.slice(0,J.pathLen)};e0.prototype.enterKey=function(J){return this._reporterState.path.push(J)};e0.prototype.exitKey=function(J){let Z=this._reporterState;Z.path=Z.path.slice(0,J-1)};e0.prototype.leaveKey=function(J,Z,G){let X=this._reporterState;if(this.exitKey(J),X.obj!==null)X.obj[Z]=G};e0.prototype.path=function(){return this._reporterState.path.join("/")};e0.prototype.enterObject=function(){let J=this._reporterState,Z=J.obj;return J.obj={},Z};e0.prototype.leaveObject=function(J){let Z=this._reporterState,G=Z.obj;return Z.obj=J,G};e0.prototype.error=function(J){let Z,G=this._reporterState,X=J instanceof d$;if(X)Z=J;else Z=new d$(G.path.map(function(Y){return"["+JSON.stringify(Y)+"]"}).join(""),J.message||J,J.stack);if(!G.options.partial)throw Z;if(!X)G.errors.push(Z);return Z};e0.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)}eQ(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 l$=s((G9)=>{var Z9=L$(),bJ=hJ().Reporter,s$=gJ().Buffer;function $$($,J){if(bJ.call(this,J),!s$.isBuffer($)){this.error("Input not Buffer");return}this.base=$,this.offset=0,this.length=$.length}Z9($$,bJ);G9.DecoderBuffer=$$;$$.isDecoderBuffer=function(J){if(J instanceof $$)return!0;return typeof J==="object"&&s$.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"};$$.prototype.save=function(){return{offset:this.offset,reporter:bJ.prototype.save.call(this)}};$$.prototype.restore=function(J){let Z=new $$(this.base);return Z.offset=J.offset,Z.length=this.offset,this.offset=J.offset,bJ.prototype.restore.call(this,J.reporter),Z};$$.prototype.isEmpty=function(){return this.offset===this.length};$$.prototype.readUInt8=function(J){if(this.offset+1<=this.length)return this.base.readUInt8(this.offset++,!0);else return this.error(J||"DecoderBuffer overrun")};$$.prototype.skip=function(J,Z){if(!(this.offset+J<=this.length))return this.error(Z||"DecoderBuffer overrun");let G=new $$(this.base);return G._reporterState=this._reporterState,G.offset=this.offset,G.length=this.offset+J,this.offset+=J,G};$$.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=s$.byteLength($);else if(s$.isBuffer($))this.value=$,this.length=$.length;else return J.error("Unsupported type: "+typeof $)}G9.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=s$.alloc(this.length);if(!Z)Z=0;if(this.length===0)return J;if(Array.isArray(this.value))this.value.forEach(function(G){G.join(J,Z),Z+=G.length});else{if(typeof this.value==="number")J[Z]=this.value;else if(typeof this.value==="string")J.write(this.value,Z);else if(s$.isBuffer(this.value))this.value.copy(J,Z);Z+=this.length}return J}});var dY=s((Z7,mY)=>{mY.exports=nY;function nY($,J){if(!$)throw Error(J||"Assertion failed")}nY.equal=function(J,Z,G){if(J!=Z)throw Error(G||"Assertion failed: "+J+" != "+Z)}});var cJ=s((G7,oY)=>{var W9=hJ().Reporter,H9=l$().EncoderBuffer,Q9=l$().DecoderBuffer,o0=dY(),sY=["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"],U9=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(sY),V9=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function t($,J,Z){let G={};if(this._baseState=G,G.name=Z,G.enc=$,G.parent=J||null,G.children=null,G.tag=null,G.args=null,G.reverseArgs=null,G.choice=null,G.optional=!1,G.any=!1,G.obj=!1,G.use=null,G.useDecoder=null,G.key=null,G.default=null,G.explicit=null,G.implicit=null,G.contains=null,!G.parent)G.children=[],this._wrap()}oY.exports=t;var z9=["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={};z9.forEach(function(X){Z[X]=J[X]});let G=new this.constructor(Z.parent);return G._baseState=Z,G};t.prototype._wrap=function(){let J=this._baseState;U9.forEach(function(Z){this[Z]=function(){let X=new this.constructor(this);return J.children.push(X),X[Z].apply(X,arguments)}},this)};t.prototype._init=function(J){let Z=this._baseState;o0(Z.parent===null),J.call(this),Z.children=Z.children.filter(function(G){return G._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,G=J.filter(function(X){return X instanceof this.constructor},this);if(J=J.filter(function(X){return!(X instanceof this.constructor)},this),G.length!==0)o0(Z.children===null),Z.children=G,G.forEach(function(X){X._baseState.parent=this},this);if(J.length!==0)o0(Z.args===null),Z.args=J,Z.reverseArgs=J.map(function(X){if(typeof X!=="object"||X.constructor!==Object)return X;let Y={};return Object.keys(X).forEach(function(H){if(H==(H|0))H|=0;let U=X[H];Y[U]=H}),Y})};V9.forEach(function($){t.prototype[$]=function(){let Z=this._baseState;throw Error($+" not implemented for encoding: "+Z.enc)}});sY.forEach(function($){t.prototype[$]=function(){let Z=this._baseState,G=Array.prototype.slice.call(arguments);return o0(Z.tag===null),Z.tag=$,this._useArgs(G),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(G){return J[G]})),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 G=this._baseState;if(G.parent===null)return J.wrapResult(G.children[0]._decode(J,Z));let X=G.default,Y=!0,H=null;if(G.key!==null)H=J.enterKey(G.key);if(G.optional){let z=null;if(G.explicit!==null)z=G.explicit;else if(G.implicit!==null)z=G.implicit;else if(G.tag!==null)z=G.tag;if(z===null&&!G.any){let O=J.save();try{if(G.choice===null)this._decodeGeneric(G.tag,J,Z);else this._decodeChoice(J,Z);Y=!0}catch(_){Y=!1}J.restore(O)}else if(Y=this._peekTag(J,z,G.any),J.isError(Y))return Y}let U;if(G.obj&&Y)U=J.enterObject();if(Y){if(G.explicit!==null){let O=this._decodeTag(J,G.explicit);if(J.isError(O))return O;J=O}let z=J.offset;if(G.use===null&&G.choice===null){let O;if(G.any)O=J.save();let _=this._decodeTag(J,G.implicit!==null?G.implicit:G.tag,G.any);if(J.isError(_))return _;if(G.any)X=J.raw(O);else J=_}if(Z&&Z.track&&G.tag!==null)Z.track(J.path(),z,J.length,"tagged");if(Z&&Z.track&&G.tag!==null)Z.track(J.path(),J.offset,J.length,"content");if(G.any);else if(G.choice===null)X=this._decodeGeneric(G.tag,J,Z);else X=this._decodeChoice(J,Z);if(J.isError(X))return X;if(!G.any&&G.choice===null&&G.children!==null)G.children.forEach(function(_){_._decode(J,Z)});if(G.contains&&(G.tag==="octstr"||G.tag==="bitstr")){let O=new Q9(X);X=this._getUse(G.contains,J._reporterState.obj)._decode(O,Z)}}if(G.obj&&Y)X=J.leaveObject(U);if(G.key!==null&&(X!==null||Y===!0))J.leaveKey(H,G.key,X);else if(H!==null)J.exitKey(H);return X};t.prototype._decodeGeneric=function(J,Z,G){let X=this._baseState;if(J==="seq"||J==="set")return null;if(J==="seqof"||J==="setof")return this._decodeList(Z,J,X.args[0],G);else if(/str$/.test(J))return this._decodeStr(Z,J,G);else if(J==="objid"&&X.args)return this._decodeObjid(Z,X.args[0],X.args[1],G);else if(J==="objid")return this._decodeObjid(Z,null,null,G);else if(J==="gentime"||J==="utctime")return this._decodeTime(Z,J,G);else if(J==="null_")return this._decodeNull(Z,G);else if(J==="bool")return this._decodeBool(Z,G);else if(J==="objDesc")return this._decodeStr(Z,J,G);else if(J==="int"||J==="enum")return this._decodeInt(Z,X.args&&X.args[0],G);if(X.use!==null)return this._getUse(X.use,Z._reporterState.obj)._decode(Z,G);else return Z.error("unknown tag: "+J)};t.prototype._getUse=function(J,Z){let G=this._baseState;if(G.useDecoder=this._use(J,Z),o0(G.useDecoder._baseState.parent===null),G.useDecoder=G.useDecoder._baseState.children[0],G.implicit!==G.useDecoder._baseState.implicit)G.useDecoder=G.useDecoder.clone(),G.useDecoder._baseState.implicit=G.implicit;return G.useDecoder};t.prototype._decodeChoice=function(J,Z){let G=this._baseState,X=null,Y=!1;if(Object.keys(G.choice).some(function(H){let U=J.save(),z=G.choice[H];try{let O=z._decode(J,Z);if(J.isError(O))return!1;X={type:H,value:O},Y=!0}catch(O){return J.restore(U),!1}return!0},this),!Y)return J.error("Choice not matched");return X};t.prototype._createEncoderBuffer=function(J){return new H9(J,this.reporter)};t.prototype._encode=function(J,Z,G){let X=this._baseState;if(X.default!==null&&X.default===J)return;let Y=this._encodeValue(J,Z,G);if(Y===void 0)return;if(this._skipDefault(Y,Z,G))return;return Y};t.prototype._encodeValue=function(J,Z,G){let X=this._baseState;if(X.parent===null)return X.children[0]._encode(J,Z||new W9);let Y=null;if(this.reporter=Z,X.optional&&J===void 0)if(X.default!==null)J=X.default;else return;let H=null,U=!1;if(X.any)Y=this._createEncoderBuffer(J);else if(X.choice)Y=this._encodeChoice(J,Z);else if(X.contains)H=this._getUse(X.contains,G)._encode(J,Z),U=!0;else if(X.children)H=X.children.map(function(z){if(z._baseState.tag==="null_")return z._encode(null,Z,J);if(z._baseState.key===null)return Z.error("Child should have a key");let O=Z.enterKey(z._baseState.key);if(typeof J!=="object")return Z.error("Child expected, but input is not object");let _=z._encode(J[z._baseState.key],Z,J);return Z.leaveKey(O),_},this).filter(function(z){return z}),H=this._createEncoderBuffer(H);else if(X.tag==="seqof"||X.tag==="setof"){if(!(X.args&&X.args.length===1))return Z.error("Too many args for : "+X.tag);if(!Array.isArray(J))return Z.error("seqof/setof, but data is not Array");let z=this.clone();z._baseState.implicit=null,H=this._createEncoderBuffer(J.map(function(O){let _=this._baseState;return this._getUse(_.args[0],J)._encode(O,Z)},z))}else if(X.use!==null)Y=this._getUse(X.use,G)._encode(J,Z);else H=this._encodePrimitive(X.tag,J),U=!0;if(!X.any&&X.choice===null){let z=X.implicit!==null?X.implicit:X.tag,O=X.implicit===null?"universal":"context";if(z===null){if(X.use===null)Z.error("Tag could be omitted only for .use()")}else if(X.use===null)Y=this._encodeComposite(z,U,O,H)}if(X.explicit!==null)Y=this._encodeComposite(X.explicit,!1,"context",Y);return Y};t.prototype._encodeChoice=function(J,Z){let G=this._baseState,X=G.choice[J.type];if(!X)o0(!1,J.type+" not found in "+JSON.stringify(Object.keys(G.choice)));return X._encode(J.value,Z)};t.prototype._encodePrimitive=function(J,Z){let G=this._baseState;if(/str$/.test(J))return this._encodeStr(Z,J);else if(J==="objid"&&G.args)return this._encodeObjid(Z,G.reverseArgs[0],G.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,G.args&&G.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 pJ=s((O9)=>{function lY($){let J={};return Object.keys($).forEach(function(Z){if((Z|0)==Z)Z=Z|0;let G=$[Z];J[G]=Z}),J}O9.tagClass={0:"universal",1:"application",2:"context",3:"private"};O9.tagClassByName=lY(O9.tagClass);O9.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"};O9.tagByName=lY(O9.tag)});var HG=s((Y7,eY)=>{var _9=L$(),O$=gJ().Buffer,tY=cJ(),WG=pJ();function aY($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new Z$,this.tree._init($.body)}eY.exports=aY;aY.prototype.encode=function(J,Z){return this.tree._encode(J,Z).join()};function Z$($){tY.call(this,"der",$)}_9(Z$,tY);Z$.prototype._encodeComposite=function(J,Z,G,X){let Y=A9(J,Z,G,this.reporter);if(X.length<128){let z=O$.alloc(2);return z[0]=Y,z[1]=X.length,this._createEncoderBuffer([z,X])}let H=1;for(let z=X.length;z>=256;z>>=8)H++;let U=O$.alloc(2+H);U[0]=Y,U[1]=128|H;for(let z=1+H,O=X.length;O>0;z--,O>>=8)U[z]=O&255;return this._createEncoderBuffer([U,X])};Z$.prototype._encodeStr=function(J,Z){if(Z==="bitstr")return this._createEncoderBuffer([J.unused|0,J.data]);else if(Z==="bmpstr"){let G=O$.alloc(J.length*2);for(let X=0;X<J.length;X++)G.writeUInt16BE(J.charCodeAt(X),X*2);return this._createEncoderBuffer(G)}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")};Z$.prototype._encodeObjid=function(J,Z,G){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(!G){if(J[1]>=40)return this.reporter.error("Second objid identifier OOB");J.splice(0,2,J[0]*40+J[1])}let X=0;for(let U=0;U<J.length;U++){let z=J[U];for(X++;z>=128;z>>=7)X++}let Y=O$.alloc(X),H=Y.length-1;for(let U=J.length-1;U>=0;U--){let z=J[U];Y[H--]=z&127;while((z>>=7)>0)Y[H--]=128|z&127}return this._createEncoderBuffer(Y)};function J$($){if($<10)return"0"+$;else return $}Z$.prototype._encodeTime=function(J,Z){let G,X=new Date(J);if(Z==="gentime")G=[J$(X.getUTCFullYear()),J$(X.getUTCMonth()+1),J$(X.getUTCDate()),J$(X.getUTCHours()),J$(X.getUTCMinutes()),J$(X.getUTCSeconds()),"Z"].join("");else if(Z==="utctime")G=[J$(X.getUTCFullYear()%100),J$(X.getUTCMonth()+1),J$(X.getUTCDate()),J$(X.getUTCHours()),J$(X.getUTCMinutes()),J$(X.getUTCSeconds()),"Z"].join("");else this.reporter.error("Encoding "+Z+" time is not supported yet");return this._encodeStr(G,"octstr")};Z$.prototype._encodeNull=function(){return this._createEncoderBuffer("")};Z$.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"&&!O$.isBuffer(J)){let Y=J.toArray();if(!J.sign&&Y[0]&128)Y.unshift(0);J=O$.from(Y)}if(O$.isBuffer(J)){let Y=J.length;if(J.length===0)Y++;let H=O$.alloc(Y);if(J.copy(H),J.length===0)H[0]=0;return this._createEncoderBuffer(H)}if(J<128)return this._createEncoderBuffer(J);if(J<256)return this._createEncoderBuffer([0,J]);let G=1;for(let Y=J;Y>=256;Y>>=8)G++;let X=Array(G);for(let Y=X.length-1;Y>=0;Y--)X[Y]=J&255,J>>=8;if(X[0]&128)X.unshift(0);return this._createEncoderBuffer(O$.from(X))};Z$.prototype._encodeBool=function(J){return this._createEncoderBuffer(J?255:0)};Z$.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getEncoder("der").tree};Z$.prototype._skipDefault=function(J,Z,G){let X=this._baseState,Y;if(X.default===null)return!1;let H=J.join();if(X.defaultBuffer===void 0)X.defaultBuffer=this._encodeValue(X.default,Z,G).join();if(H.length!==X.defaultBuffer.length)return!1;for(Y=0;Y<H.length;Y++)if(H[Y]!==X.defaultBuffer[Y])return!1;return!0};function A9($,J,Z,G){let X;if($==="seqof")$="seq";else if($==="setof")$="set";if(WG.tagByName.hasOwnProperty($))X=WG.tagByName[$];else if(typeof $==="number"&&($|0)===$)X=$;else return G.error("Unknown tag: "+$);if(X>=31)return G.error("Multi-octet tag encoding unsupported");if(!J)X|=32;return X|=WG.tagClassByName[Z||"universal"]<<6,X}});var J1=s((W7,$1)=>{var F9=L$(),QG=HG();function UG($){QG.call(this,$),this.enc="pem"}F9(UG,QG);$1.exports=UG;UG.prototype.encode=function(J,Z){let X=QG.prototype.encode.call(this,J).toString("base64"),Y=["-----BEGIN "+Z.label+"-----"];for(let H=0;H<X.length;H+=64)Y.push(X.slice(H,H+64));return Y.push("-----END "+Z.label+"-----"),Y.join(`
6
+ `)}});var VG=s((G1)=>{var Z1=G1;Z1.der=HG();Z1.pem=J1()});var OG=s((Q7,U1)=>{var R9=L$(),I9=GG(),X1=l$().DecoderBuffer,W1=cJ(),Y1=pJ();function H1($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new r0,this.tree._init($.body)}U1.exports=H1;H1.prototype.decode=function(J,Z){if(!X1.isDecoderBuffer(J))J=new X1(J,Z);return this.tree._decode(J,Z)};function r0($){W1.call(this,"der",$)}R9(r0,W1);r0.prototype._peekTag=function(J,Z,G){if(J.isEmpty())return!1;let X=J.save(),Y=zG(J,'Failed to peek tag: "'+Z+'"');if(J.isError(Y))return Y;return J.restore(X),Y.tag===Z||Y.tagStr===Z||Y.tagStr+"of"===Z||G};r0.prototype._decodeTag=function(J,Z,G){let X=zG(J,'Failed to decode tag of "'+Z+'"');if(J.isError(X))return X;let Y=Q1(J,X.primitive,'Failed to get length of "'+Z+'"');if(J.isError(Y))return Y;if(!G&&X.tag!==Z&&X.tagStr!==Z&&X.tagStr+"of"!==Z)return J.error('Failed to match tag: "'+Z+'"');if(X.primitive||Y!==null)return J.skip(Y,'Failed to match body of: "'+Z+'"');let H=J.save(),U=this._skipUntilEnd(J,'Failed to skip indefinite length body: "'+this.tag+'"');if(J.isError(U))return U;return Y=J.offset-H.offset,J.restore(H),J.skip(Y,'Failed to match body of: "'+Z+'"')};r0.prototype._skipUntilEnd=function(J,Z){for(;;){let G=zG(J,Z);if(J.isError(G))return G;let X=Q1(J,G.primitive,Z);if(J.isError(X))return X;let Y;if(G.primitive||X!==null)Y=J.skip(X);else Y=this._skipUntilEnd(J,Z);if(J.isError(Y))return Y;if(G.tagStr==="end")break}};r0.prototype._decodeList=function(J,Z,G,X){let Y=[];while(!J.isEmpty()){let H=this._peekTag(J,"end");if(J.isError(H))return H;let U=G.decode(J,"der",X);if(J.isError(U)&&H)break;Y.push(U)}return Y};r0.prototype._decodeStr=function(J,Z){if(Z==="bitstr"){let G=J.readUInt8();if(J.isError(G))return G;return{unused:G,data:J.raw()}}else if(Z==="bmpstr"){let G=J.raw();if(G.length%2===1)return J.error("Decoding of string type: bmpstr length mismatch");let X="";for(let Y=0;Y<G.length/2;Y++)X+=String.fromCharCode(G.readUInt16BE(Y*2));return X}else if(Z==="numstr"){let G=J.raw().toString("ascii");if(!this._isNumstr(G))return J.error("Decoding of string type: numstr unsupported characters");return G}else if(Z==="octstr")return J.raw();else if(Z==="objDesc")return J.raw();else if(Z==="printstr"){let G=J.raw().toString("ascii");if(!this._isPrintstr(G))return J.error("Decoding of string type: printstr unsupported characters");return G}else if(/str$/.test(Z))return J.raw().toString();else return J.error("Decoding of string type: "+Z+" unsupported")};r0.prototype._decodeObjid=function(J,Z,G){let X,Y=[],H=0,U=0;while(!J.isEmpty())if(U=J.readUInt8(),H<<=7,H|=U&127,(U&128)===0)Y.push(H),H=0;if(U&128)Y.push(H);let z=Y[0]/40|0,O=Y[0]%40;if(G)X=Y;else X=[z,O].concat(Y.slice(1));if(Z){let _=Z[X.join(" ")];if(_===void 0)_=Z[X.join(".")];if(_!==void 0)X=_}return X};r0.prototype._decodeTime=function(J,Z){let G=J.raw().toString(),X,Y,H,U,z,O;if(Z==="gentime")X=G.slice(0,4)|0,Y=G.slice(4,6)|0,H=G.slice(6,8)|0,U=G.slice(8,10)|0,z=G.slice(10,12)|0,O=G.slice(12,14)|0;else if(Z==="utctime")if(X=G.slice(0,2)|0,Y=G.slice(2,4)|0,H=G.slice(4,6)|0,U=G.slice(6,8)|0,z=G.slice(8,10)|0,O=G.slice(10,12)|0,X<70)X=2000+X;else X=1900+X;else return J.error("Decoding "+Z+" time is not supported yet");return Date.UTC(X,Y-1,H,U,z,O,0)};r0.prototype._decodeNull=function(){return null};r0.prototype._decodeBool=function(J){let Z=J.readUInt8();if(J.isError(Z))return Z;else return Z!==0};r0.prototype._decodeInt=function(J,Z){let G=J.raw(),X=new I9(G);if(Z)X=Z[X.toString(10)]||X;return X};r0.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getDecoder("der").tree};function zG($,J){let Z=$.readUInt8(J);if($.isError(Z))return Z;let G=Y1.tagClass[Z>>6],X=(Z&32)===0;if((Z&31)===31){let H=Z;Z=0;while((H&128)===128){if(H=$.readUInt8(J),$.isError(H))return H;Z<<=7,Z|=H&127}}else Z&=31;let Y=Y1.tag[Z];return{cls:G,primitive:X,tag:Z,tagStr:Y}}function Q1($,J,Z){let G=$.readUInt8(Z);if($.isError(G))return G;if(!J&&G===128)return null;if((G&128)===0)return G;let X=G&127;if(X>4)return $.error("length octect is too long");G=0;for(let Y=0;Y<X;Y++){G<<=8;let H=$.readUInt8(Z);if($.isError(H))return H;G|=H}return G}});var z1=s((U7,V1)=>{var q9=L$(),j9=gJ().Buffer,KG=OG();function MG($){KG.call(this,$),this.enc="pem"}q9(MG,KG);V1.exports=MG;MG.prototype.decode=function(J,Z){let G=J.toString().split(/[\r\n]+/g),X=Z.label.toUpperCase(),Y=/^-----(BEGIN|END) ([^-]+)-----$/,H=-1,U=-1;for(let _=0;_<G.length;_++){let I=G[_].match(Y);if(I===null)continue;if(I[2]!==X)continue;if(H===-1){if(I[1]!=="BEGIN")break;H=_}else{if(I[1]!=="END")break;U=_;break}}if(H===-1||U===-1)throw Error("PEM section not found for: "+X);let z=G.slice(H+1,U).join("");z.replace(/[^a-z0-9+/=]+/gi,"");let O=j9.from(z,"base64");return KG.prototype.decode.call(this,O,Z)}});var _G=s((K1)=>{var O1=K1;O1.der=OG();O1.pem=z1()});var _1=s((M1)=>{var P9=VG(),B9=_G(),L9=L$(),S9=M1;S9.define=function(J,Z){return new r$(J,Z)};function r$($,J){this.name=$,this.body=J,this.decoders={},this.encoders={}}r$.prototype._createNamed=function(J){let Z=this.name;function G(X){this._initNamed(X,Z)}return L9(G,J),G.prototype._initNamed=function(Y,H){J.call(this,Y,H)},new G(this)};r$.prototype._getDecoder=function(J){if(J=J||"der",!this.decoders.hasOwnProperty(J))this.decoders[J]=this._createNamed(B9[J]);return this.decoders[J]};r$.prototype.decode=function(J,Z,G){return this._getDecoder(Z).decode(J,G)};r$.prototype._getEncoder=function(J){if(J=J||"der",!this.encoders.hasOwnProperty(J))this.encoders[J]=this._createNamed(P9[J]);return this.encoders[J]};r$.prototype.encode=function(J,Z,G){return this._getEncoder(Z).encode(J,G)}});var F1=s((A1)=>{var uJ=A1;uJ.Reporter=hJ().Reporter;uJ.DecoderBuffer=l$().DecoderBuffer;uJ.EncoderBuffer=l$().EncoderBuffer;uJ.Node=cJ()});var q1=s((I1)=>{var R1=I1;R1._reverse=function(J){let Z={};return Object.keys(J).forEach(function(G){if((G|0)==G)G=G|0;let X=J[G];Z[X]=G}),Z};R1.der=pJ()});var P1=s((j1)=>{var i$=j1;i$.bignum=GG();i$.define=_1().define;i$.base=F1();i$.constants=q1();i$.decoders=_G();i$.encoders=VG()});var S1=s((AG,L1)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var nJ=_$("buffer"),U$=nJ.Buffer;function B1($,J){for(var Z in $)J[Z]=$[Z]}if(U$.from&&U$.alloc&&U$.allocUnsafe&&U$.allocUnsafeSlow)L1.exports=nJ;else B1(nJ,AG),AG.Buffer=v$;function v$($,J,Z){return U$($,J,Z)}v$.prototype=Object.create(U$.prototype);B1(U$,v$);v$.from=function($,J,Z){if(typeof $==="number")throw TypeError("Argument must not be a number");return U$($,J,Z)};v$.alloc=function($,J,Z){if(typeof $!=="number")throw TypeError("Argument must be a number");var G=U$($);if(J!==void 0)if(typeof Z==="string")G.fill(J,Z);else G.fill(J);else G.fill(0);return G};v$.allocUnsafe=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return U$($)};v$.allocUnsafeSlow=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return nJ.SlowBuffer($)}});var w1=s((_7,C1)=>{function FG($){var J=($/8|0)+($%8===0?0:1);return J}var C9={ES256:FG(256),ES384:FG(384),ES512:FG(521)};function w9($){var J=C9[$];if(J)return J;throw Error('Unknown algorithm "'+$+'"')}C1.exports=w9});var y1=s((A7,k1)=>{var mJ=S1().Buffer,T1=w1(),dJ=128,N1=0,E9=32,T9=16,N9=2,v1=T9|E9|N1<<6,sJ=N9|N1<<6;function v9($){return $.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function D1($){if(mJ.isBuffer($))return $;else if(typeof $==="string")return mJ.from($,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function D9($,J){$=D1($);var Z=T1(J),G=Z+1,X=$.length,Y=0;if($[Y++]!==v1)throw Error('Could not find expected "seq"');var H=$[Y++];if(H===(dJ|1))H=$[Y++];if(X-Y<H)throw Error('"seq" specified length of "'+H+'", only "'+(X-Y)+'" remaining');if($[Y++]!==sJ)throw Error('Could not find expected "int" for "r"');var U=$[Y++];if(X-Y-2<U)throw Error('"r" specified length of "'+U+'", only "'+(X-Y-2)+'" available');if(G<U)throw Error('"r" specified length of "'+U+'", max of "'+G+'" is acceptable');var z=Y;if(Y+=U,$[Y++]!==sJ)throw Error('Could not find expected "int" for "s"');var O=$[Y++];if(X-Y!==O)throw Error('"s" specified length of "'+O+'", expected "'+(X-Y)+'"');if(G<O)throw Error('"s" specified length of "'+O+'", max of "'+G+'" is acceptable');var _=Y;if(Y+=O,Y!==X)throw Error('Expected to consume entire buffer, but "'+(X-Y)+'" bytes remain');var I=Z-U,B=Z-O,S=mJ.allocUnsafe(I+U+B+O);for(Y=0;Y<I;++Y)S[Y]=0;$.copy(S,Y,z+Math.max(-I,0),z+U),Y=Z;for(var C=Y;Y<C+B;++Y)S[Y]=0;return $.copy(S,Y,_+Math.max(-B,0),_+O),S=S.toString("base64"),S=v9(S),S}function E1($,J,Z){var G=0;while(J+G<Z&&$[J+G]===0)++G;var X=$[J+G]>=dJ;if(X)--G;return G}function k9($,J){$=D1($);var Z=T1(J),G=$.length;if(G!==Z*2)throw TypeError('"'+J+'" signatures must be "'+Z*2+'" bytes, saw "'+G+'"');var X=E1($,0,Z),Y=E1($,Z,$.length),H=Z-X,U=Z-Y,z=2+H+1+1+U,O=z<dJ,_=mJ.allocUnsafe((O?2:3)+z),I=0;if(_[I++]=v1,O)_[I++]=z;else _[I++]=dJ|1,_[I++]=z&255;if(_[I++]=sJ,_[I++]=H,X<0)_[I++]=0,I+=$.copy(_,I,0,Z);else I+=$.copy(_,I,X,Z);if(_[I++]=sJ,_[I++]=U,Y<0)_[I++]=0,$.copy(_,I,Z);else $.copy(_,I,Z+Y);return _}k1.exports={derToJose:D9,joseToDer:k9}});var jG=s((F7,l1)=>{var qG=P1(),{createHmac:g1,createVerify:y9,createSign:x9,timingSafeEqual:f9,createPublicKey:g9,constants:{RSA_PKCS1_PSS_PADDING:h1,RSA_PSS_SALTLEN_DIGEST:b1,RSA_PKCS1_PADDING:c1,RSA_PSS_SALTLEN_MAX_SIGN:h9,RSA_PSS_SALTLEN_AUTO:b9},sign:x1,verify:f1}=_$("crypto"),{joseToDer:c9,derToJose:p9}=y1(),p1=JG(),{TokenError:J0}=u$(),u1=/[=+/]/g,u9={"=":"","+":"-","/":"_"},n1=/^-----BEGIN(?: (RSA|EC|ENCRYPTED))? PRIVATE KEY-----/,m1=/^-----BEGIN(?: (RSA))? PUBLIC KEY-----/,oJ=new p1(1000),RG=new p1(1000),d1=["HS256","HS384","HS512"],n9=["ES256","ES384","ES512"],IG=["RS256","RS384","RS512","PS256","PS384","PS512"],m9=["EdDSA"],s1={"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"]}},d9=qG.define("PrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),s9=qG.define("PublicKey",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),o9=qG.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 o1($){return u9[$]}function QJ($,J,Z,G){return $.set(J,[Z,G]),Z||G}function l9($){if($.match(m1)||$.includes("-----BEGIN CERTIFICATE-----"))throw new J0(J0.codes.invalidKey,"Public keys are not supported for signing.");let J=$.trim().match(n1);if(!J)return"HS256";let Z,G,X;switch(J[1]){case"RSA":return"RS256";case"EC":Z=o9.decode($,"pem",{label:"EC PRIVATE KEY"}),X=Z.parameters.value.join(".");break;case"ENCRYPTED":return"ENCRYPTED";default:switch(Z=d9.decode($,"pem",{label:"PRIVATE KEY"}),G=Z.algorithm.algorithm.join("."),G){case"1.2.840.113549.1.1.1":return"RS256";case"1.2.840.10045.2.1":X=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 ${G}.`)}}let Y=s1[X];if(!Y)throw new J0(J0.codes.invalidKey,`Unsupported EC private key with curve ${X}.`);return`ES${Y.bits}`}function r9($){let J=$.match(m1);if($.match(n1))throw new J0(J0.codes.invalidKey,"Private keys are not supported for verifying.");else if(J&&J[1]==="RSA")return IG;else if(!J&&!$.includes("-----BEGIN CERTIFICATE-----"))return d1;if($.includes("-----BEGIN CERTIFICATE-----"))$=g9($).export({type:"spki",format:"pem"});let Z=s9.decode($,"pem",{label:"PUBLIC KEY"}),G=Z.algorithm.algorithm.join("."),X;switch(G){case"1.2.840.113549.1.1.1":return IG;case"1.2.840.10045.2.1":X=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 ${G}.`)}let Y=s1[X];if(!Y)throw new J0(J0.codes.invalidKey,`Unsupported EC public key with curve ${X}.`);return[`ES${Y.bits}`]}function i9($,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,G]=oJ.get($)||[];if(Z)return Z;else if(G)throw G;try{let X=l9($);if(X==="ENCRYPTED")return QJ(oJ,$,J);return QJ(oJ,$,X)}catch(X){throw QJ(oJ,$,null,J0.wrap(X,J0.codes.invalidKey,"Unsupported PEM private key."))}}function t9($){if(!$)return"none";let[J,Z]=RG.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 QJ(RG,$,r9($))}catch(G){throw QJ(RG,$,null,J0.wrap(G,J0.codes.invalidKey,"Unsupported PEM public key."))}}function a9($,J,Z){try{let G=$.slice(0,2),X=`sha${$.slice(2)}`,Y,H;switch(G){case"HS":Y=g1(X,J).update(Z).digest("base64");break;case"ES":Y=p9(x1(X,Buffer.from(Z,"utf-8"),J),$).toString("base64");break;case"RS":case"PS":if(H={key:J,padding:c1,saltLength:h9},G==="PS")H.padding=h1,H.saltLength=b1;Y=x9(X).update(Z).sign(H).toString("base64");break;case"Ed":Y=x1(void 0,Buffer.from(Z,"utf-8"),J).toString("base64")}return Y.replace(u1,o1)}catch(G){throw new J0(J0.codes.signError,"Cannot create the signature.",{originalError:G})}}function e9($,J,Z,G){try{let X=$.slice(0,2),Y=`SHA${$.slice(2)}`;if(G=Buffer.from(G,"base64"),X==="HS")try{return f9(g1(Y,J).update(Z).digest(),G)}catch{return!1}else if(X==="Ed")if(typeof f1==="function")return f1(void 0,Buffer.from(Z,"utf-8"),J,G);else throw new J0(J0.codes.signError,"EdDSA algorithms are not supported by your Node.js version.");let H={key:J,padding:c1,saltLength:b9};if(X==="PS")H.padding=h1,H.saltLength=b1;else if(X==="ES")G=c9(G,$);return y9("RSA-"+Y).update(Z).verify(H,G)}catch(X){throw new J0(J0.codes.verifyError,"Cannot verify the signature.",{originalError:X})}}l1.exports={base64UrlMatcher:u1,base64UrlReplacer:o1,hsAlgorithms:d1,rsaAlgorithms:IG,esAlgorithms:n9,edAlgorithms:m9,detectPrivateKeyAlgorithm:i9,detectPublicKeyAlgorithms:t9,createSignature:a9,verifySignature:e9}});var PG=s((R7,i1)=>{var{createHash:r1}=_$("crypto"),$8=/"alg"\s*:\s*"[HERP]S(256|384)"/m,J8=/"alg"\s*:\s*"EdDSA"/m,Z8=/"crv"\s*:\s*"Ed448"/m;function G8($,J,Z){let G=$(J,Z);if(G&&typeof G.then==="function")G.then((X)=>{process.nextTick(()=>Z(null,X))}).catch(Z)}function X8($){if(typeof $==="function")return[$];let J,Z,G=new Promise((X,Y)=>{J=X,Z=Y});return[function(X,Y){if(X)return Z(X);return J(Y)},G]}function Y8($){let J=$.split(".",1)[0],Z=Buffer.from(J,"base64").toString("utf-8"),G=null;if(Z.match(J8)&&Z.match(Z8))G=r1("shake256",{outputLength:114});else{let X=Z.match($8);G=r1(`sha${X?X[1]:"512"}`)}return G.update($).digest("hex")}i1.exports={getAsyncKey:G8,ensurePromiseCallback:X8,hashToken:Y8}});var GW=s((I7,ZW)=>{var{createPublicKey:W8,createSecretKey:H8}=_$("crypto"),Q8=JG(),{hsAlgorithms:a1,verifySignature:U8,detectPublicKeyAlgorithms:e1}=jG(),V8=iZ(),{TokenError:n}=u$(),{getAsyncKey:z8,ensurePromiseCallback:O8,hashToken:K8}=PG();function M8($,J){return $===J}function $W($,J){for(let Z of $)if(J.includes(Z))return;throw new n(n.codes.invalidKey,`Invalid public key provided for algorithms ${$.join(", ")}.`)}function JW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J?H8($):W8($)}function UJ($){if(!Array.isArray($))$=[$];return $.filter((J)=>J).map((J)=>{if(J&&typeof J.test==="function")return J;return{test:M8.bind(null,J)}})}function _8($){let J=parseInt($===!0?1000:$,10);return J>0?new Q8(J):null}function t$({cache:$,token:J,cacheTTL:Z,payload:G,ignoreExpiration:X,ignoreNotBefore:Y,maxAge:H,clockTimestamp:U=Date.now(),clockTolerance:z,errorCacheTTL:O,cacheKeyBuilder:_},I){if(!$)return I;let B=[I,0,0];if(I instanceof n){let T=typeof O==="function"?O(I):O;return B[2]=U+z+T,$.set(_(J),B),I}if(G&&typeof G.iat==="number"){if(B[1]=!Y&&typeof G.nbf==="number"?G.nbf*1000-z:0,!X){if(typeof G.exp==="number")B[2]=G.exp*1000+z;else if(H)B[2]=G.iat*1000+H+z}}let C=U+z+Z;return B[2]=B[2]===0?C:Math.min(B[2],C),$.set(_(J),B),I}function A8($,J,Z){if($ instanceof n){if(!J)throw $;J($)}else{if(!J)return $;J(null,$)}return Z}function F8($,J,Z,G,X){if(!X.includes(J.alg))throw new n(n.codes.invalidAlgorithm,"The token algorithm is invalid.");if(Z&&!U8(J.alg,G,$,Z))throw new n(n.codes.invalidSignature,"The token signature is invalid.")}function R8($,J,Z,G,X){let Y=Z?`The ${J} claim must be a ${X} or an array of ${X}s.`:`The ${J} claim must be a ${X}.`;if(G&&!Z)throw new n(n.codes.invalidClaimValue,Y);if($.map((H)=>typeof H).some((H)=>H!==X))throw new n(n.codes.invalidClaimType,Y)}function I8($,J,Z,G){let X=G?`None of ${J} claim values are allowed.`:`The ${J} claim value is not allowed.`;if(!$.some((Y)=>Z.some((H)=>H.test(Y))))throw new n(n.codes.invalidClaimValue,X)}function q8($,J,Z,G,X,Y){let H=$*1000+(J||0);if(!(G?Z>=H:Z<=H))throw new n(n.codes[X],`The token ${Y} at ${new Date(H).toISOString()}.`)}function t1($,{input:J,header:Z,payload:G,signature:X},{validators:Y,allowedAlgorithms:H,checkTyp:U,clockTimestamp:z,requiredClaims:O}){let _=$ instanceof Buffer?$.length:!!$;if(_&&!X)throw new n(n.codes.missingSignature,"The token signature is missing.");else if(!_&&X)throw new n(n.codes.missingKey,"The key option is missing.");if(F8(J,Z,X,$,H),U&&(typeof Z.typ!=="string"||U!==Z.typ.toLowerCase().replace(/^application\//,"")))throw new n(n.codes.invalidType,"Invalid typ.");if(O){for(let B of O)if(!(B in G))throw new n(n.codes.missingRequiredClaim,`The ${B} claim is required.`)}let I=z||Date.now();for(let{type:B,claim:S,allowed:C,array:T,modifier:E,greater:D,errorCode:w,errorVerb:N}of Y){let p=G[S],v=Array.isArray(p),b=v?p:[p];if(!(S in G))continue;if(R8(b,S,T,v,B==="date"?"number":"string"),B==="date")q8(p,E,I,D,w,N);else I8(b,S,C,v)}}function j8({key:$,allowedAlgorithms:J,complete:Z,cacheTTL:G,checkTyp:X,clockTimestamp:Y,clockTolerance:H,ignoreExpiration:U,ignoreNotBefore:z,maxAge:O,isAsync:_,validators:I,decode:B,cache:S,requiredClaims:C,errorCacheTTL:T,cacheKeyBuilder:E},D,w){let[N,p]=_?O8(w):[];if(S){let[V,K,M]=S.get(E(D))||[void 0,0,0],R=Y||Date.now();if(typeof V<"u"&&(K===0||R<K&&V.code==="FAST_JWT_INACTIVE"||R>=K&&V.code!=="FAST_JWT_INACTIVE")&&(M===0||R<=M))return A8(V,N,p)}let v;try{v=B(D)}catch(V){if(N)return N(V),p;throw V}let{header:b,payload:r,signature:o,input:u0}=v,q={cache:S,token:D,cacheTTL:G,errorCacheTTL:T,ignoreExpiration:U,ignoreNotBefore:z,maxAge:O,clockTimestamp:Y,clockTolerance:H,payload:r,cacheKeyBuilder:E},W={validators:I,allowedAlgorithms:J,checkTyp:X,clockTimestamp:Y,clockTolerance:H,requiredClaims:C};if(!N)try{return t1($,v,W),t$(q,Z?{header:b,payload:r,signature:o,input:u0}:r)}catch(V){throw t$(q,V)}return z8($,{header:b,payload:r,signature:o},(V,K)=>{if(V)return N(t$(q,n.wrap(V,n.codes.keyFetchingError,"Cannot fetch key.")));if(typeof K==="string")K=Buffer.from(K,"utf-8");else if(!(K instanceof Buffer))return N(t$(q,new n(n.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a public key.")));try{let M=e1(K);if(W.allowedAlgorithms.length)$W(J,M);else W.allowedAlgorithms=M;K=JW(K,M[0]===a1[0]),t1(K,v,W)}catch(M){return N(t$(q,M))}N(null,t$(q,Z?{header:b,payload:r,signature:o,input:D}:r))}),p}ZW.exports=function(J){let{key:Z,algorithms:G,complete:X,cache:Y,cacheTTL:H,errorCacheTTL:U,checkTyp:z,clockTimestamp:O,clockTolerance:_,ignoreExpiration:I,ignoreNotBefore:B,maxAge:S,allowedJti:C,allowedAud:T,allowedIss:E,allowedSub:D,allowedNonce:w,requiredClaims:N,cacheKeyBuilder:p}={cacheTTL:600000,clockTolerance:0,errorCacheTTL:-1,cacheKeyBuilder:K8,...J};if(!Array.isArray(G))G=[];let v=typeof Z;if(v!=="string"&&v!=="object"&&v!=="function")throw new n(n.codes.INVALID_OPTION,"The key option must be a string, a buffer or a function returning the algorithm secret or public key.");if(Z&&v!=="function"){let q=e1(Z);if(G.length)$W(G,q);else G=q;Z=JW(Z,q[0]===a1[0])}if(O&&(typeof O!=="number"||O<0))throw new n(n.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(_&&(typeof _!=="number"||_<0))throw new n(n.codes.invalidOption,"The clockTolerance option must be a positive number.");if(H&&(typeof H!=="number"||H<0))throw new n(n.codes.invalidOption,"The cacheTTL option must be a positive number.");if(U&&typeof U!=="function"&&typeof U!=="number"||U<-1)throw new n(n.codes.invalidOption,"The errorCacheTTL option must be a number greater than -1 or a function.");if(N&&!Array.isArray(N))throw new n(n.codes.invalidOption,"The requiredClaims option must be an array.");let b=[];if(!B)b.push({type:"date",claim:"nbf",errorCode:"inactive",errorVerb:"will be active",greater:!0,modifier:-_});if(!I)b.push({type:"date",claim:"exp",errorCode:"expired",errorVerb:"has expired",modifier:+_});if(typeof S==="number")b.push({type:"date",claim:"iat",errorCode:"expired",errorVerb:"has expired",modifier:S});if(C)b.push({type:"string",claim:"jti",allowed:UJ(C)});if(T)b.push({type:"string",claim:"aud",allowed:UJ(T),array:!0});if(E)b.push({type:"string",claim:"iss",allowed:UJ(E)});if(D)b.push({type:"string",claim:"sub",allowed:UJ(D)});if(w)b.push({type:"string",claim:"nonce",allowed:UJ(w)});let r=z?z.toLowerCase().replace(/^application\//,""):null,o={key:Z,allowedAlgorithms:G,complete:X,cacheTTL:H,errorCacheTTL:U,checkTyp:r,clockTimestamp:O,clockTolerance:_,ignoreExpiration:I,ignoreNotBefore:B,maxAge:S,isAsync:v==="function",validators:b,decode:V8({complete:!0}),cache:_8(Y),requiredClaims:N,cacheKeyBuilder:p},u0=j8.bind(null,o);return u0.cache=o.cache,u0}});var XW=s((S8)=>{var P8=/^(-?(?:\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?)?)?$/,lJ=1000,rJ=lJ*60,iJ=rJ*60,zJ=iJ*24,BG=zJ*365.25;function B8($){var J,Z=$.toLowerCase().match(P8);if(Z!=null&&(J=parseFloat(Z[1]))){if(Z[3]!=null)return J*lJ;if(Z[4]!=null)return J*rJ;if(Z[5]!=null)return J*iJ;if(Z[6]!=null)return J*zJ;if(Z[7]!=null)return J*zJ*7;if(Z[8]!=null)return J*BG;return J}}function VJ($,J,Z,G){var X=($|0)===$?$:~~($+0.5);return J+X+(G?" "+Z+(X!=1?"s":""):Z[0])}function L8($,J){var Z=$<0?"-":"",G=$<0?-$:$;if(G<lJ)return $+(J?" ms":"ms");if(G<rJ)return VJ(G/lJ,Z,"second",J);if(G<iJ)return VJ(G/rJ,Z,"minute",J);if(G<zJ)return VJ(G/iJ,Z,"hour",J);if(G<BG)return VJ(G/zJ,Z,"day",J);return VJ(G/BG,Z,"year",J)}S8.format=L8;S8.parse=B8});var OW=s((j7,zW)=>{var{base64UrlMatcher:LG,base64UrlReplacer:SG,hsAlgorithms:E8,esAlgorithms:T8,rsaAlgorithms:N8,edAlgorithms:v8,detectPrivateKeyAlgorithm:HW,createSignature:YW}=jG(),{TokenError:d}=u$(),{getAsyncKey:D8,ensurePromiseCallback:k8}=PG(),{createPrivateKey:y8,createSecretKey:x8}=_$("crypto"),{parse:WW}=XW(),QW=new Set([...E8,...T8,...N8,...v8,"none"]),f8=Array.from(QW).join(", ");function UW($,J){let Z=$.slice(0,2),G=J.slice(0,2),X=!0;if(Z==="RS"||Z==="PS")X=G==="RS"||Z==="RS"&&J==="ENCRYPTED";else if(Z==="ES"||Z==="Ed")X=Z===G||Z==="ES"&&J==="ENCRYPTED";if(!X)throw new d(d.codes.invalidKey,`Invalid private key provided for algorithm ${$}.`)}function VW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J[0]==="H"?x8($):y8($)}function g8({key:$,algorithm:J,noTimestamp:Z,mutatePayload:G,clockTimestamp:X,expiresIn:Y,notBefore:H,kid:U,typ:z,isAsync:O,additionalHeader:_,fixedPayload:I},B,S){let[C,T]=O?k8(S):[];if(typeof B!=="object")throw new d(d.codes.invalidType,"The payload must be an object.");if(B.exp&&(!Number.isInteger(B.exp)||B.exp<0))throw new d(d.codes.invalidClaimValue,"The exp claim must be a positive integer.");let E={alg:J,typ:z||"JWT",kid:U,..._},D="",w=B.iat*1000||X||Date.now(),N={...B,...I,iat:Z?void 0:Math.floor(w/1000),exp:B.exp?B.exp:Y?Math.floor((w+Y)/1000):void 0,nbf:B.nbf?B.nbf:H?Math.floor((w+H)/1000):void 0};if(G)Object.assign(B,N);if(D=Buffer.from(JSON.stringify(N),"utf-8").toString("base64").replace(LG,SG),!C){let v=Buffer.from(JSON.stringify(E),"utf-8").toString("base64").replace(LG,SG)+"."+D,b=J==="none"?"":YW(J,$,v);return v+"."+b}return D8($,{header:E,payload:B},(p,v)=>{if(p){let r=d.wrap(p,d.codes.keyFetchingError,"Cannot fetch key.");return C(r)}if(typeof v==="string")v=Buffer.from(v,"utf-8");else if(!(v instanceof Buffer))return C(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 b;try{let r=HW(v,J);if(J)UW(J,r);else E.alg=J=r;v=VW(v,J);let u0=Buffer.from(JSON.stringify(E),"utf-8").toString("base64").replace(LG,SG)+"."+D;b=u0+"."+YW(J,v,u0)}catch(r){return C(r)}C(null,b)}),T}zW.exports=function(J){let{key:Z,algorithm:G,noTimestamp:X,mutatePayload:Y,clockTimestamp:H,expiresIn:U,notBefore:z,jti:O,aud:_,iss:I,sub:B,nonce:S,kid:C,typ:T,header:E}={clockTimestamp:0,...J};if(G&&!QW.has(G))throw new d(d.codes.invalidOption,`The algorithm option must be one of the following values: ${f8}.`);let D=typeof Z,w=D==="object"&&Z&&Z.key&&Z.passphrase;if(G==="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||D!=="string"&&!(Z instanceof Buffer)&&D!=="function"&&!w)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(w&&!G)throw new d(d.codes.invalidAlgorithm,"When using password protected key you must provide the algorithm option.");if(Z&&D!=="function"){let v=HW(w?Z.key:Z,G);if(G)UW(G,v);else G=v;Z=VW(Z,G)}if(U){if(typeof U==="string")U=WW(U);if(typeof U!=="number")throw new d(d.codes.invalidOption,"The expiresIn option must be a positive number or a valid string.")}if(z){if(typeof z==="string")z=WW(z);if(typeof z!=="number"||z<0)throw new d(d.codes.invalidOption,"The notBefore option must be a positive number or a valid string.")}if(H&&(typeof H!=="number"||H<0))throw new d(d.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(O&&typeof O!=="string")throw new d(d.codes.invalidOption,"The jti option must be a string.");if(_&&typeof _!=="string"&&!Array.isArray(_))throw new d(d.codes.invalidOption,"The aud option must be a string or an array of strings.");if(I&&typeof I!=="string")throw new d(d.codes.invalidOption,"The iss option must be a string.");if(B&&typeof B!=="string")throw new d(d.codes.invalidOption,"The sub option must be a string.");if(S&&typeof S!=="string")throw new d(d.codes.invalidOption,"The nonce option must be a string.");if(C&&typeof C!=="string")throw new d(d.codes.invalidOption,"The kid option must be a string.");if(E&&typeof E!=="object")throw new d(d.codes.invalidOption,"The header option must be a object.");let p=Object.entries({jti:O,aud:_,iss:I,sub:B,nonce:S}).reduce((v,[b,r])=>{if(r!==void 0)v[b]=r;return v},{});return g8.bind(null,{key:Z,algorithm:G,noTimestamp:X,mutatePayload:Y,clockTimestamp:H,expiresIn:U,notBefore:z,kid:C,typ:T,isAsync:D==="function",additionalHeader:E,fixedPayload:p})}});var MW=s((P7,KW)=>{var{TokenError:h8,TOKEN_ERROR_CODES:b8}=u$(),c8=iZ(),p8=GW(),u8=OW();KW.exports={TokenError:h8,TOKEN_ERROR_CODES:b8,createDecoder:c8,createVerifier:p8,createSigner:u8}});FJ();import{join as TZ}from"path";n0();function q$($){if(Array.isArray($)){let J=[];for(let Z of $)J.push(q$(Z));return J}if(i($)){let J={};for(let Z of Object.keys($))J[Z]=q$($[Z]);return J}return $}function HX($,J){if(J===void 0)return $;if(Array.isArray($)&&Array.isArray(J)){for(let Z of J)$.push(q$(Z));return $}if(i($)&&i(J)){for(let Z of Object.keys(J)){let G=J[Z];if(G===void 0)continue;let X=$[Z];if(Array.isArray(X)&&Array.isArray(G)){let Y=[];for(let H of X)Y.push(q$(H));for(let H of G)Y.push(q$(H));$[Z]=Y;continue}if(i(X)&&i(G)){$[Z]=HX(q$(X),G);continue}$[Z]=q$(G)}return $}return q$(J)}function QX(...$){let J={};for(let Z of $){if(Z===void 0)continue;J=HX(J,Z)}return J}var GH={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:20,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:{}};async function UX($){if($!=="development"&&$!=="production")throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1ANODE_ENV \u53EA\u80FD\u662F 'development' \u6216 'production'\uFF0C\u5F53\u524D\u503C=${String($)}`);let J=TZ(process.cwd(),"configs"),Z=await I$(TZ(J,"befly.common.json"),{}),G=await I$(TZ(J,`befly.${$}.json`),{}),X=QX(GH,Z,G);X.nodeEnv=$;let Y=X?.redis?.prefix;if(typeof Y==="string"){if(Y.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=${Y}`)}return X}a();n0();async function VX($){let J=!1;for(let Z of $)try{if(typeof Z?.name!=="string"||Z.name.trim()===""){j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 name \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32"})),J=!0;continue}if(typeof Z?.handler!=="function"){j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}if(typeof Z?.path!=="string"||Z.path.trim()==="")j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;else{let G=Z.path.trim();if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(G))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09"})),J=!0;if(!G.startsWith("/api/"))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u5FC5\u987B\u4EE5 /api/ \u5F00\u5934"})),J=!0;if(G.includes(" "))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C"})),J=!0;if(G.includes("/api//"))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u51FA\u73B0 /api//\uFF08\u91CD\u590D\u659C\u6760\uFF09"})),J=!0}if(typeof Z?.routePrefix!=="string"||Z.routePrefix.trim()==="")j.warn(Object.assign({},c(Z,["handler"]),{msg:"\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()))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\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")j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 auth \u5C5E\u6027\u5FC5\u987B\u662F\u5E03\u5C14\u503C (true=\u9700\u767B\u5F55, false=\u516C\u5F00)"})),J=!0;if(Z.fields&&!i(Z.fields))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 fields \u5C5E\u6027\u5FC5\u987B\u662F\u5BF9\u8C61"})),J=!0;if(Z.required&&!Array.isArray(Z.required))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u6570\u7EC4"})),J=!0;if(Z.required&&Z.required.some((G)=>typeof G!=="string"))j.warn(Object.assign({},c(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0}catch(G){j.error({err:G,item:Z,msg:"\u63A5\u53E3\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u63A5\u53E3\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();n0();var zX=["name","enable","deps","handler"];async function OX($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let G of $)try{if(!i(G)){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u94A9\u5B50\u5BFC\u51FA\u5FC5\u987B\u662F\u5BF9\u8C61\uFF08export default { deps, handler }\uFF09"})),J=!0;continue}if(typeof G.moduleName!=="string"||G.moduleName.trim()===""){j.warn(Object.assign({},c(G,["handler"]),{msg:"\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}let X=G.customKeys;if(!Array.isArray(X)){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u94A9\u5B50\u626B\u63CF\u7ED3\u679C\u7F3A\u5C11 customKeys\uFF08\u65E0\u6CD5\u5224\u65AD\u7528\u6237\u5BFC\u51FA\u7684\u5B57\u6BB5\u662F\u5426\u5408\u6CD5\uFF09"})),J=!0;continue}if(X.some((z)=>typeof z!=="string")){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u94A9\u5B50\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let Y=X.filter((z)=>!zX.includes(z));if(Y.length>0){j.warn(Object.assign({},c(G,["handler"]),{msg:`\u94A9\u5B50\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${Y.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${zX.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${X.join(", ")}`})),J=!0;continue}let H=X.includes("enable"),U=X.includes("deps");if(H){if(typeof G.enable!=="boolean"){j.warn(Object.assign({},c(G,["handler"]),{msg:"\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}}else G.enable=!0;if(G.source==="core"){let z=typeof G.name==="string"?G.name:"";if(z===""){j.warn(Object.assign({},c(G,["handler"]),{msg:"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(z)){j.warn(Object.assign({},c(G,["handler"]),{msg:"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(G.moduleName)){j.warn(Object.assign({},c(G,["handler"]),{msg:"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(z!==G.moduleName){j.warn(Object.assign({},c(G,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u7684 name \u5FC5\u987B\u4E0E moduleName \u5B8C\u5168\u4E00\u81F4"})),J=!0;continue}if(typeof G.filePath!=="string"||!G.filePath.startsWith(`core:hook:${z}`)){j.warn(Object.assign({},c(G,["handler"]),{msg:"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(U){if(!Array.isArray(G.deps)){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u94A9\u5B50\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}if(G.deps.some((z)=>typeof z!=="string")){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u94A9\u5B50\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}}else if(!Array.isArray(G.deps))G.deps=[];if(typeof G.handler!=="function"){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u94A9\u5B50\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(X){j.error({err:X,item:G,msg:"\u94A9\u5B50\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u94A9\u5B50\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();kZ();function KH($){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:""}}var jX=async($)=>{let J=!1,Z=await qX($),G=[];for(let Y of Z)G.push({menu:Y,depth:1});let X=new Set;while(G.length>0){let Y=G.pop(),H=Y?.menu,U=typeof Y?.depth==="number"?Y.depth:0;if(H===null||typeof H!=="object"){J=!0,j.warn({menu:H,msg:"\u83DC\u5355\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61"});continue}if(U>3){J=!0,j.warn({path:H?.path,depth:U,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});continue}let z=H.children;if(typeof z<"u"&&!Array.isArray(z)){J=!0,j.warn({path:H?.path,childrenType:typeof z,msg:"\u83DC\u5355 children \u5FC5\u987B\u662F\u6570\u7EC4"});continue}if(Array.isArray(z)&&z.length>0)if(U>=3)J=!0,j.warn({path:H?.path,depth:U,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});else for(let S of z)G.push({menu:S,depth:U+1});let O=typeof H.path==="string"?H.path.trim():"",_=typeof H.name==="string"?H.name.trim():"",I=typeof H.sort==="number"?H.sort:999999;if(typeof H.path==="string")H.path=O;if(typeof H.name==="string")H.name=_;if(typeof H.sort>"u")H.sort=I;if(!O){J=!0,j.warn({menu:H,msg:"\u83DC\u5355\u7F3A\u5C11 path\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});continue}let B=KH(O);if(!B.ok)J=!0,j.warn({path:O,reason:B.reason,msg:"\u83DC\u5355 path \u4E0D\u5408\u6CD5"});if(!_)J=!0,j.warn({path:O,menu:H,msg:"\u83DC\u5355\u7F3A\u5C11 name\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});if(typeof H.sort<"u"&&typeof H.sort!=="number")J=!0,j.warn({path:O,sort:H.sort,msg:"\u83DC\u5355 sort \u5FC5\u987B\u662F number"});if(typeof H.sort==="number"&&(!Number.isFinite(H.sort)||H.sort<1))J=!0,j.warn({path:O,sort:H.sort,msg:"\u83DC\u5355 sort \u6700\u5C0F\u503C\u4E3A 1"});if(X.has(O)){J=!0,j.warn({path:O,msg:"\u83DC\u5355 path \u91CD\u590D\uFF08\u4E25\u683C\u6A21\u5F0F\u7981\u6B62\u91CD\u590D path\uFF09"});continue}X.add(O)}if(J)throw Error("\u83DC\u5355\u7ED3\u6784\u68C0\u67E5\u5931\u8D25");return Z};a();n0();var PX=["name","enable","deps","handler"];async function BX($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let G of $)try{if(!i(G)){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u63D2\u4EF6\u5BFC\u51FA\u5FC5\u987B\u662F\u5BF9\u8C61\uFF08export default { deps, handler }\uFF09"})),J=!0;continue}if(typeof G.moduleName!=="string"||G.moduleName.trim()===""){j.warn(Object.assign({},c(G,["handler"]),{msg:"\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}let X=G.customKeys;if(!Array.isArray(X)){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u63D2\u4EF6\u626B\u63CF\u7ED3\u679C\u7F3A\u5C11 customKeys\uFF08\u65E0\u6CD5\u5224\u65AD\u7528\u6237\u5BFC\u51FA\u7684\u5B57\u6BB5\u662F\u5426\u5408\u6CD5\uFF09"})),J=!0;continue}if(X.some((z)=>typeof z!=="string")){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u63D2\u4EF6\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let Y=X.filter((z)=>!PX.includes(z));if(Y.length>0){j.warn(Object.assign({},c(G,["handler"]),{msg:`\u63D2\u4EF6\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${Y.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${PX.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${X.join(", ")}`})),J=!0;continue}let H=X.includes("enable"),U=X.includes("deps");if(H){if(typeof G.enable!=="boolean"){j.warn(Object.assign({},c(G,["handler"]),{msg:"\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}}else G.enable=!0;if(G.source==="core"){let z=typeof G.name==="string"?G.name:"";if(z===""){j.warn(Object.assign({},c(G,["handler"]),{msg:"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(z)){j.warn(Object.assign({},c(G,["handler"]),{msg:"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(G.moduleName)){j.warn(Object.assign({},c(G,["handler"]),{msg:"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(z!==G.moduleName){j.warn(Object.assign({},c(G,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u7684 name \u5FC5\u987B\u4E0E moduleName \u5B8C\u5168\u4E00\u81F4"})),J=!0;continue}if(typeof G.filePath!=="string"||!G.filePath.startsWith(`core:plugin:${z}`)){j.warn(Object.assign({},c(G,["handler"]),{msg:"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(U){if(!Array.isArray(G.deps)){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u63D2\u4EF6\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}if(G.deps.some((z)=>typeof z!=="string")){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u63D2\u4EF6\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}}else if(!Array.isArray(G.deps))G.deps=[];if(typeof G.handler!=="function"){j.warn(Object.assign({},c(G,["handler"]),{msg:"\u63D2\u4EF6\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(X){j.error({err:X,item:G,msg:"\u63D2\u4EF6\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u63D2\u4EF6\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var LX=["id","created_at","updated_at","deleted_at","state"],SX=["string","number","text","array_string","array_text","array_number_string","array_number_text"],CX=["name","type","min","max","default","detail","index","unique","nullable","unsigned","regexp"],MH=/^_?[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)*$/,_H=/^[\u4e00-\u9fa5a-zA-Z0-9 _-]+$/,wX=65535;async function EX($){let J=!1;for(let Z of $){if(Z.type!=="table")continue;let G=typeof Z.sourceName==="string"?Z.sourceName:"",X=G?`${G}\u8868 `:"\u8868 ";try{let Y=Z.fileName,H=Z.content||{};if(!MH.test(Y)){j.warn(`${X}${Y} \u6587\u4EF6\u540D\u5FC5\u987B\u4F7F\u7528\u5C0F\u9A7C\u5CF0\u547D\u540D\uFF08\u4F8B\u5982 testCustomers.json\uFF09`),J=!0;continue}for(let[U,z]of Object.entries(H)){if(typeof z!=="object"||z===null||Array.isArray(z)){j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u89C4\u5219\u5FC5\u987B\u4E3A\u5BF9\u8C61`),J=!0;continue}if(LX.includes(U))j.warn(`${X}${Y} \u6587\u4EF6\u5305\u542B\u4FDD\u7559\u5B57\u6BB5 ${U}\uFF0C`+`\u4E0D\u80FD\u5728\u8868\u5B9A\u4E49\u4E2D\u4F7F\u7528\u4EE5\u4E0B\u5B57\u6BB5: ${LX.join(", ")}`),J=!0;let O=z,I=Object.keys(O).filter((D)=>!CX.includes(D));if(I.length>0)j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5305\u542B\u975E\u6CD5\u5C5E\u6027: ${I.join(", ")}\uFF0C`+`\u5141\u8BB8\u7684\u5C5E\u6027\u4E3A: ${CX.join(", ")}`),J=!0;if(!O.name||typeof O.name!=="string"){j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5 name \u6216\u7C7B\u578B\u9519\u8BEF`),J=!0;continue}if(!O.type||typeof O.type!=="string"){j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5 type \u6216\u7C7B\u578B\u9519\u8BEF`),J=!0;continue}if(O.min!==void 0&&!(O.min===null||typeof O.min==="number"))j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5 min \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u6570\u5B57`),J=!0;if(O.max!==void 0&&!(O.max===null||typeof O.max==="number"))j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5 max \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u6570\u5B57`),J=!0;if(O.detail!==void 0&&typeof O.detail!=="string")j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5 detail \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32`),J=!0;if(O.index!==void 0&&typeof O.index!=="boolean")j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5 index \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.unique!==void 0&&typeof O.unique!=="boolean")j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5 unique \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.nullable!==void 0&&typeof O.nullable!=="boolean")j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5 nullable \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.unsigned!==void 0&&typeof O.unsigned!=="boolean")j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5 unsigned \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.regexp!==void 0&&O.regexp!==null&&typeof O.regexp!=="string")j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5 regexp \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u5B57\u7B26\u4E32`),J=!0;let{name:B,type:S,min:C,max:T,default:E}=O;if(!_H.test(B))j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5\u540D\u79F0 "${B}" \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(!SX.includes(S))j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5\u7C7B\u578B "${S}" \u683C\u5F0F\u9519\u8BEF\uFF0C`+`\u5FC5\u987B\u4E3A${SX.join("\u3001")}\u4E4B\u4E00`),J=!0;if(S!=="number"&&O.unsigned!==void 0)j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u5B57\u6BB5\u7C7B\u578B\u4E3A ${S}\uFF0C\u4E0D\u5141\u8BB8\u8BBE\u7F6E unsigned\uFF08\u4EC5 number \u7C7B\u578B\u6709\u6548\uFF09`),J=!0;if(O.unique===!0&&O.index===!0)j.warn(`${X}${Y} \u6587\u4EF6 ${U} \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&&T!==void 0&&C!==null&&T!==null){if(C>T)j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u6700\u5C0F\u503C "${C}" \u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u503C "${T}"`),J=!0}if(S==="text"||S==="array_text"||S==="array_number_text"){if(C!==void 0&&C!==null)j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u7684 ${S} \u7C7B\u578B\u6700\u5C0F\u503C\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${C}"`),J=!0;if(T!==void 0&&T!==null)j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u7684 ${S} \u7C7B\u578B\u6700\u5927\u957F\u5EA6\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0;if(E!==void 0&&E!==null)j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u4E3A ${S} \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${E}"`),J=!0;if(O.index===!0)j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u4E3A ${S} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u521B\u5EFA\u7D22\u5F15\uFF08index=true \u65E0\u6548\uFF09`),J=!0;if(O.unique===!0)j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u4E3A ${S} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u552F\u4E00\u7EA6\u675F\uFF08unique=true \u65E0\u6548\uFF09`),J=!0}else if(S==="string"||S==="array_string"||S==="array_number_string"){if(T===void 0||T===null||typeof T!=="number")j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u4E3A ${S} \u7C7B\u578B\uFF0C`+`\u5FC5\u987B\u8BBE\u7F6E max \u4E14\u7C7B\u578B\u4E3A\u6570\u5B57\uFF1B\u5176\u4E2D array_*_string \u7684 max \u8868\u793A\u5355\u4E2A\u5143\u7D20\u957F\u5EA6\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0;else if(T>wX)j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u6700\u5927\u957F\u5EA6 ${T} \u8D8A\u754C\uFF0C`+`${S} \u7C7B\u578B\u957F\u5EA6\u5FC5\u987B\u5728 1..${wX} \u8303\u56F4\u5185`),J=!0}else if(S==="number"){if(E!==void 0&&E!==null&&typeof E!=="number")j.warn(`${X}${Y} \u6587\u4EF6 ${U} \u4E3A number \u7C7B\u578B\uFF0C`+`\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A\u6570\u5B57\u6216 null\uFF0C\u5F53\u524D\u4E3A "${E}"`),J=!0}}}catch(Y){j.error({msg:`${X}${Z.fileName} \u89E3\u6790\u5931\u8D25`,err:Y}),J=!0}}if(J)throw Error("\u8868\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var{SQL:TX,RedisClient:AH}=globalThis.Bun;class z${static sqlClient=null;static redisClient=null;static sqlConnectedAt=null;static redisConnectedAt=null;static sqlPoolMax=1;static async connectSql($){let J=$||{},Z=J.type||"mysql",G=J.host||"127.0.0.1",X=J.port||3306,Y=encodeURIComponent(J.username||"root"),H=encodeURIComponent(J.password||"root"),U=encodeURIComponent(J.database||"befly_demo"),z;if(Z==="sqlite")z=U;else{if(!G||!U)throw Error("\u6570\u636E\u5E93\u914D\u7F6E\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E\u53C2\u6570");z=`${Z}://${Y}:${H}@${G}:${X}/${U}`}let O;if(Z==="sqlite")O=new TX(z);else O=new TX({url:z,max:J.poolMax??1,bigint:!1});try{let I=(async()=>{let S="";if(Z==="sqlite")S=(await O`SELECT sqlite_version() AS version`)?.[0]?.version;else if(Z==="postgresql"||Z==="postgres")S=(await O`SELECT version() AS version`)?.[0]?.version;else S=(await O`SELECT VERSION() AS version`)?.[0]?.version;return S})(),B=new Promise((S,C)=>{setTimeout(()=>{C(Error(`\u6570\u636E\u5E93\u8FDE\u63A5\u8D85\u65F6 (${30000}ms)`))},30000)});return await Promise.race([I,B]),this.sqlClient=O,this.sqlConnectedAt=Date.now(),this.sqlPoolMax=J.poolMax??1,O}catch(_){j.error({err:_,msg:"[Connect] SQL \u8FDE\u63A5\u5931\u8D25"});try{await O?.close()}catch{}throw _}}static async disconnectSql(){if(this.sqlClient){try{await this.sqlClient.close()}catch($){j.error({err:$,msg:"[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",G=J.port||6379,X=J.username||"",Y=J.password||"",H=J.db||0,U="";if(X&&Y)U=`${X}:${Y}@`;else if(Y)U=`:${Y}@`;let z=`redis://${U}${Z}:${G}/${H}`,O=new AH(z,{connectionTimeout:30000,idleTimeout:0,autoReconnect:!0,maxRetries:3,enableOfflineQueue:!0,enableAutoPipelining:!0});return await O.ping(),this.redisClient=O,this.redisConnectedAt=Date.now(),O}catch(Z){throw j.error({err:Z,msg:"[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($){j.error({err:$,msg:"[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 j.error({env:$.nodeEnv,err:J,msg:"\u6570\u636E\u5E93\u8FDE\u63A5\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();async function NX($){let J=new Map;for(let Z of $){if(Object.hasOwn(Z,"type")&&Z.type!=="api")continue;try{J.set(Z.path,Z)}catch(G){throw j.error({err:G,api:Z.relativePath,file:Z.filePath,msg:"\u63A5\u53E3\u52A0\u8F7D\u5931\u8D25"}),G}}return J}a();n0();function qJ($,J={}){let Z=J.moduleLabel||"\u6A21\u5757",G=J.getName||((I)=>{let B=I.moduleName;if(typeof B==="string"&&B.trim()!=="")return B;return A$(I.fileName)}),X=J.getDeps||((I)=>I.deps),Y=[],H=new Set,U=new Set,z={},O=!0;for(let I of $){let B=G(I);if(typeof B!=="string"||B.trim()===""){j.error({item:I,msg:`${Z} \u540D\u79F0\u89E3\u6790\u5931\u8D25\uFF08getName \u8FD4\u56DE\u7A7A\u5B57\u7B26\u4E32\uFF09`}),O=!1;continue}if(z[B]){j.error({name:B,first:z[B],second:I,msg:`${Z} \u540D\u79F0\u91CD\u590D\uFF0C\u65E0\u6CD5\u6839\u636E deps \u552F\u4E00\u5B9A\u4F4D`}),O=!1;continue}z[B]=I}if(!O)return!1;for(let I of $){let B=G(I),S=X(I);if(!Array.isArray(S)){j.error({module:B,item:I,msg:`${Z} \u7684 deps \u5FC5\u987B\u662F\u6570\u7EC4`}),O=!1;continue}for(let C of S){if(typeof C!=="string"){j.error({module:B,dependency:C,item:I,msg:`${Z} \u7684 deps \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4`}),O=!1;continue}if(!z[C])j.error({module:B,dependency:C,msg:`${Z} \u4F9D\u8D56\u672A\u627E\u5230`}),O=!1}}if(!O)return!1;let _=(I)=>{if(H.has(I))return;if(U.has(I)){j.error({module:I,msg:`${Z} \u5FAA\u73AF\u4F9D\u8D56`}),O=!1;return}let B=z[I];if(!B)return;let S=X(B);U.add(I);for(let C of S)_(C);U.delete(I),H.add(I),Y.push(B)};for(let I of $){let B=G(I);_(B)}return O?Y:!1}async function vX($){let J=[],Z=$.filter((X)=>{let Y=X?.moduleName;if(typeof Y!=="string"||Y.trim()==="")return!1;if(X?.enable===!1)return!1;return!0}),G=qJ(Z,{moduleLabel:"\u94A9\u5B50"});if(G===!1)throw Error("\u94A9\u5B50\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let X of G){let Y=X.moduleName,H=X;J.push({name:Y,enable:!0,deps:Array.isArray(H.deps)?H.deps:[],handler:H.handler})}return J}a();async function DX($,J){let Z=[],G=$.filter((Y)=>{let H=Y?.moduleName;if(typeof H!=="string"||H.trim()==="")return!1;if(Y?.enable===!1)return!1;return!0}),X=qJ(G,{moduleLabel:"\u63D2\u4EF6"});if(X===!1)throw Error("\u63D2\u4EF6\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let Y of X){let H=Y.moduleName,U=Y;try{let z=typeof U.handler==="function"?await U.handler(J):{};J[H]=z,Z.push({name:H,enable:!0,deps:Array.isArray(U.deps)?U.deps:[],handler:U.handler})}catch(z){throw j.error({err:z,plugin:H,msg:"\u63D2\u4EF6\u521D\u59CB\u5316\u5931\u8D25"}),z}}return Z}KJ();a();function kX($,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 G=$.headers.get("x-real-ip");if(typeof G==="string"&&G.trim())return G.trim();let X=$.headers.get("cf-connecting-ip");if(typeof X==="string"&&X.trim())return X.trim();let Y=$.headers.get("x-client-ip");if(typeof Y==="string"&&Y.trim())return Y.trim();let H=$.headers.get("true-client-ip");if(typeof H==="string"&&H.trim())return H.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 P$($,J,Z=1,G=null,X=null,Y=null){if($.requestId)j.info({event:"request_blocked",reason:J,reasonCode:Y,code:Z,detail:X,msg:"request blocked"});return Response.json({code:Z,msg:J,data:G,detail:X},{headers:$.corsHeaders})}function yZ($){if($.api&&$.requestId)j.info({event:"request_done",msg:"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,(G,X)=>typeof X==="bigint"?X.toString():X);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})}n0();function yX($,J,Z){return async(G,X)=>{let Y=rG(),U=new URL(G.url).pathname||"/",z=kX(G,X),O=Date.now(),_={method:G.method,body:{},user:{},req:G,now:O,ip:z,headers:G.headers,route:U,requestId:Y,corsHeaders:{"X-Request-ID":Y}},I=$.get(U);if(I)_.api=I;return aG({requestId:Y,method:G.method,route:U,ip:z,now:O},async()=>{try{for(let B of J)if(await B.handler(Z,_),_.response)return _.response;if(_.api&&G.method!=="OPTIONS"){let B={event:"request",apiName:_.api.name};if(_.body&&Object.keys(_.body).length>0)B.body=_.body;B.msg="request",j.info(B)}if(!_.api){if(G.method!=="OPTIONS")_.response=Response.json({code:1,msg:"\u63A5\u53E3\u4E0D\u5B58\u5728"},{headers:_.corsHeaders})}else if(_.api.handler){let B=await _.api.handler(Z,_);if(B instanceof Response)_.response=B;else _.result=B}return yZ(_)}catch(B){let S=_.api?U:G.url;return j.error({err:B,path:S,msg:"\u8BF7\u6C42\u9519\u8BEF"}),_.result={code:1,msg:"\u5185\u90E8\u670D\u52A1\u9519\u8BEF"},yZ(_)}})}}j$();a();j$();import{fileURLToPath as FH}from"url";var RH=FH(import.meta.url),B$=RJ(RH);var E4=C$(B$).endsWith("/dist")?B$:m(B$,"dist"),T4=m(B$,"checks"),N4=m(B$,"plugins"),v4=m(B$,"hooks"),D4=m(B$,"apis"),k4=m(B$,"tables"),d0=process.cwd(),y4=m(d0,"checks"),x4=m(d0,"plugins"),f4=m(d0,"hooks"),g4=m(d0,"apis"),h4=m(d0,"tables"),xX=m(d0,"addons");function jJ($,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 fX($=void 0){return async(J)=>{let Z=jJ(J,$),G=new URL(J.url),X=m(d0,"public",G.pathname);try{if(J.method==="OPTIONS")return new Response(null,{status:204,headers:Z});let Y=Bun.file(X);if(await Y.exists())return new Response(Y,{headers:{"Content-Type":Y.type||"application/octet-stream",...Z}});else return Response.json({code:1,msg:"\u6587\u4EF6\u672A\u627E\u5230"},{headers:Z})}catch(Y){return j.error({err:Y,msg:"\u9759\u6001\u6587\u4EF6\u5904\u7406\u5931\u8D25"}),Response.json({code:1,msg:"\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25"},{headers:Z})}}}a();n0();var IH=($)=>{let J=$.split("/").map((Y)=>Y.trim()).filter((Y)=>Y.length>0),G=(J[1]||"")==="addon"?4:3,X=J.slice(0,Math.min(G,J.length));if(X.length===0)return"";return`/${X.join("/")}`};async function gX($,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){j.debug(`${"addon_admin_api"} \u8868\u4E0D\u5B58\u5728`);return}let X=(await $.db.getAll({table:"addon_admin_api",fields:["id","path","parentPath","name","addonName","auth","state"],where:{state$gte:0}})).data.lists||[],Y=lG(X,(_)=>_.path),H=[],U=[],z=[],O=new Set;for(let _ of J){if(_.type!=="api")continue;let I=_.auth===!1||_.auth===0?0:1,B=IH(_.path);O.add(_.path);let S=Y[_.path];if(S){if(_.name!==S.name||_.path!==S.path||_.addonName!==S.addonName||B!==S.parentPath||I!==S.auth)U.push({id:S.id,name:_.name,path:_.path,parentPath:B,addonName:_.addonName,auth:I})}else H.push({name:_.name,path:_.path,parentPath:B,addonName:_.addonName,auth:I})}for(let _ of X)if(!O.has(_.path))z.push(_.id);if(U.length>0)try{await $.db.updBatch("addon_admin_api",U.map((_)=>{return{id:_.id,data:{name:_.name,path:_.path,parentPath:_.parentPath,addonName:_.addonName,auth:_.auth}}}))}catch(_){j.error({err:_,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u66F4\u65B0\u5931\u8D25"})}if(H.length>0)try{await $.db.insBatch("addon_admin_api",H.map((_)=>{return{name:_.name,path:_.path,parentPath:_.parentPath,addonName:_.addonName,auth:_.auth}}))}catch(_){j.error({err:_,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u65B0\u589E\u5931\u8D25"})}if(z.length>0)try{await $.db.delForceBatch("addon_admin_api",z)}catch(_){j.error({err:_,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u5220\u9664\u5931\u8D25"})}}async function hX($){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 qH}from"crypto";class f${static md5($,J="hex"){let Z=new Bun.CryptoHasher("md5");return Z.update($),Z.digest(J)}static hmacMd5($,J,Z="hex"){let G=new Bun.CryptoHasher("md5",$);return G.update(J),G.digest(Z)}static sha1($,J="hex"){let Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest(J)}static hmacSha1($,J,Z="hex"){let G=new Bun.CryptoHasher("sha1",$);return G.update(J),G.digest(Z)}static sha256($,J="hex"){let Z=new Bun.CryptoHasher("sha256");return Z.update($),Z.digest(J)}static rsaSha256($,J,Z="hex"){let G=qH("RSA-SHA256");return G.update($),G.sign(J,Z)}static hmacSha256($,J,Z="hex"){let G=new Bun.CryptoHasher("sha256",$);return G.update(J),G.digest(Z)}static sha512($,J="hex"){let Z=new Bun.CryptoHasher("sha512");return Z.update($),Z.digest(J)}static hmacSha512($,J,Z="hex"){let G=new Bun.CryptoHasher("sha512",$);return G.update(J),G.digest(Z)}static hash($,J,Z="hex"){let G=new Bun.CryptoHasher($);return G.update(J),G.digest(Z)}static hmac($,J,Z,G="hex"){let X=new Bun.CryptoHasher($,J);return X.update(Z),X.digest(G)}static async hashFile($,J="sha256",Z="hex"){let G=Bun.file($),X=new Bun.CryptoHasher(J),H=G.stream().getReader();try{while(!0){let{done:U,value:z}=await H.read();if(U)break;X.update(z)}return X.digest(Z)}finally{H.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)),G="";for(let X=0;X<Z.length;X++)G+=Z[X].toString(16).padStart(2,"0");return G.slice(0,$)}static fastHash($,J=0){let Z=Bun.hash($,J);return typeof Z==="bigint"?Number(Z):Z}}a();async function bX($,J={}){if(!J.devPassword)return;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){j.debug("addon_admin_admin \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_role")).data){j.debug("addon_admin_role \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_menu")).data){j.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_api")).data){j.debug("addon_admin_api \u8868\u4E0D\u5B58\u5728");return}let Z=await $.db.getAll({table:"addon_admin_menu",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),G=await $.db.getAll({table:"addon_admin_api",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),X=await $.db.getOne({table:"addon_admin_role",where:{code:"dev"}}),Y={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:Z.data.lists.map((O)=>O.path).filter((O)=>O),apis:G.data.lists.map((O)=>O.path).filter((O)=>O),sort:0};if(typeof X.data.id==="number")await $.db.updData({table:"addon_admin_role",where:{code:"dev"},data:{name:Y.name,description:Y.description,menus:Y.menus,apis:Y.apis,sort:Y.sort}});else await $.db.insData({table:"addon_admin_role",data:Y});let H={nickname:"\u5F00\u53D1\u8005",email:J.devEmail||"dev@qq.com",username:"dev",password:await f$.hashPassword(f$.sha256(J.devPassword+"befly")),roleCode:"dev",roleType:"admin"};if(typeof(await $.db.getOne({table:"addon_admin_admin",where:{username:"dev"}})).data.id==="number")await $.db.updData({table:"addon_admin_admin",where:{username:"dev"},data:{nickname:H.nickname,email:H.email,username:H.username,password:H.password,roleCode:H.roleCode,roleType:H.roleType}});else await $.db.insData({table:"addon_admin_admin",data:H});let z=[{code:"user",name:"\u7528\u6237\u89D2\u8272",description:"\u666E\u901A\u7528\u6237\u89D2\u8272",sort:1},{code:"admin",name:"\u7BA1\u7406\u5458\u89D2\u8272",description:"\u7BA1\u7406\u5458\u89D2\u8272",sort:2},{code:"guest",name:"\u8BBF\u5BA2\u89D2\u8272",description:"\u8BBF\u5BA2\u89D2\u8272",sort:3}];for(let O of z)if((await $.db.getOne({table:"addon_admin_role",where:{code:O.code}})).data?.id)await $.db.updData({table:"addon_admin_role",where:{code:O.code},data:{name:O.name,description:O.description,sort:O.sort}});else await $.db.insData({table:"addon_admin_role",data:{code:O.code,name:O.name,description:O.description,sort:O.sort}})}a();kZ();function jH($){let J=$.config?.disableMenus,Z=Array.isArray(J)?J:[],G=[];for(let Y of Z){if(typeof Y!=="string")continue;let H=Y.trim();if(!H)continue;G.push(H)}if(G.length===0)return()=>!1;let X=G.map((Y)=>new Bun.Glob(Y));return(Y)=>{if(typeof Y!=="string")return!1;let H=Y.trim();if(!H)return!1;let U=[];if(U.push(H),H.startsWith("/"))U.push(H.slice(1));else U.push(`/${H}`);for(let z of X){let O=z.match;if(typeof O!=="function")throw Error("syncMenu: \u5F53\u524D Bun \u7248\u672C\u4E0D\u652F\u6301 Bun.Glob.match\uFF0C\u65E0\u6CD5\u6309 disableMenus \u505A glob \u5339\u914D");for(let _ of U)if(O.call(z,_))return!0}return!1}}function cX($,J){let Z=[];for(let G of $){if(G===null||typeof G!=="object")continue;let X=typeof G.path==="string"?String(G.path).trim():"";if(X&&J(X))continue;let Y=G.children,H=Array.isArray(Y)&&Y.length>0?cX(Y,J):[],U={};if(typeof G.name==="string")U.name=G.name;if(typeof G.path==="string")U.path=G.path;if(typeof G.sort==="number")U.sort=G.sort;if(typeof G.parentPath==="string")U.parentPath=G.parentPath;if(H.length>0)U.children=H;Z.push(U)}return Z}function PH($){let J=new Map,Z=[];for(let G of $)Z.push({menu:G,parentPathFromTree:""});while(Z.length>0){let G=Z.pop(),X=G?G.menu:null;if(!X)continue;let Y=typeof X.path==="string"?X.path:"",H=X.children;if(H&&Array.isArray(H)&&H.length>0){let I=typeof Y==="string"?Y:"";for(let B of H)Z.push({menu:B,parentPathFromTree:I})}if(!Y)continue;let U=typeof X.name==="string"?X.name:"";if(!U)continue;let z=typeof X.sort==="number"?X.sort:999999,_=typeof X.parentPath==="string"?X.parentPath:typeof G?.parentPathFromTree==="string"?G.parentPathFromTree:IX(Y);J.set(Y,{path:Y,name:U,sort:z,parentPath:_})}return J}async function pX($,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){j.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}let Z=jH($),G=cX(J,Z),X=PH(G),Y=new Set;for(let U of X.keys())Y.add(U);let H="addon_admin_menu";await $.db.trans(async(U)=>{let O=(await U.getAll({table:H,fields:["id","name","path","parentPath","sort","state"]})).data.lists||[],_=O.filter((w)=>typeof w?.state==="number"&&w.state>=0),I=new Map,B=new Set,S=new Map;for(let w of _){if(typeof w?.path!=="string"||!w.path)continue;if(typeof w?.id!=="number")continue;if(Z(w.path))continue;let N=I.get(w.path);if(!N){I.set(w.path,w);continue}let p=typeof N?.id==="number"?N.id:0,v=w.id;if(v>p){if(I.set(w.path,w),p>0)B.add(p);let b=S.get(w.path)||{keptId:v,removedIds:[]};if(b.keptId=v,p>0)b.removedIds.push(p);S.set(w.path,b)}else{if(v>0)B.add(v);let b=S.get(w.path)||{keptId:p,removedIds:[]};if(b.keptId=p,v>0)b.removedIds.push(v);S.set(w.path,b)}}if(S.size>0){let w=[];for(let N of S.entries()){let p=N[0],v=N[1];if(w.push({path:p,keptId:v.keptId,removedIds:v.removedIds}),w.length>=10)break}j.warn({table:H,duplicatePaths:S.size,duplicateIds:B.size,examples:w,msg:"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 C=[],T=[];for(let w of X.values()){let N=I.get(w.path);if(N){let p=typeof N.parentPath==="string"?N.parentPath:"";if(N.name!==w.name||N.sort!==w.sort||p!==w.parentPath)C.push({id:N.id,data:{name:w.name,path:w.path,parentPath:w.parentPath,sort:w.sort}})}else T.push({name:w.name,path:w.path,parentPath:w.parentPath,sort:w.sort})}if(C.length>0)await U.updBatch(H,C);if(T.length>0)await U.insBatch(H,T);let E=new Set;for(let w of _){if(typeof w?.path!=="string"||!w.path)continue;if(!Y.has(w.path)){if(typeof w?.id==="number")E.add(w.id)}}for(let w of B)if(typeof w==="number"&&w>0)E.add(w);for(let w of O){if(typeof w?.path!=="string"||!w.path)continue;if(!Z(w.path))continue;if(typeof w?.id==="number"&&w.id>0)E.add(w.id)}let D=Array.from(E);if(D.length>0)await U.delForceBatch(H,D)})}class G0{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 g$=null;function h$($){let J=Error(`\u672A\u77E5\u6570\u636E\u5E93\u65B9\u8A00: ${String($)}`);if($!=="mysql"&&$!=="postgresql"&&$!=="sqlite")throw J;if(!g$)g$=new Map,g$.set("mysql",new BJ),g$.set("postgresql",new uX),g$.set("sqlite",new nX);let Z=g$.get($);if(!Z)throw J;return Z}function PJ($){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 G=$.schema&&$.schema.trim()!==""?$.schema:"public",X={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:[G,$.table]},Y={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:[G,$.table]};return{columns:X,comments:Y}}return{columns:h$("sqlite").getTableColumnsQuery($.table)}}function xZ($){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 BJ{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 G=Z?.Field;if(typeof G==="string"&&G.length>0)J.push(G)}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 uX{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 G=Z?.column_name;if(typeof G==="string"&&G.length>0)J.push(G)}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 nX{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 G=Z?.name;if(typeof G==="string"&&G.length>0)J.push(G)}return J}tableExistsQuery($,J){return{sql:"SELECT COUNT(*) as count FROM sqlite_master WHERE type = 'table' AND name = ?",params:[$]}}}a();function W$($){return{name:$.name,type:$.type,detail:$.detail??"",min:$.min??null,max:$.max??null,default:$.default??null,index:$.index??!1,unique:$.unique??!1,nullable:$.nullable??!1,unsigned:$.unsigned??!1,regexp:$.regexp??null}}n0();var SJ=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 G=String($.config.db?.type||"mysql").toLowerCase(),X="mysql";if(G==="postgres"||G==="postgresql")X="postgresql";else if(G==="sqlite")X="sqlite";await BH(X,$.db);let Y=$.config.db?.database||"",H={dbDialect:X,db:$.db,dbName:Y};for(let U of J){if(!U||U.type!=="table")continue;if(U.source!=="app"&&U.source!=="addon"&&U.source!=="core"){j.warn(`syncTable \u8DF3\u8FC7\u672A\u77E5\u6765\u6E90\u8868\u5B9A\u4E49: source=${String(U.source)} fileName=${String(U.fileName)}`);continue}let z=f(U.fileName),O=z;if(U.source==="addon"){if(!U.addonName||String(U.addonName).trim()==="")throw Error(`syncTable addon \u8868\u7F3A\u5C11 addonName: fileName=${String(U.fileName)}`);O=`addon_${f(U.addonName)}_${z}`}let _=U.content;if(!_||typeof _!=="object")throw Error(`syncTable \u8868\u5B9A\u4E49\u65E0\u6548: table=${O}`);for(let B of Object.values(_))rX(B);if(await $Y(H,O))await CH(H,O,_);else await GY(H,O,_);Z.push(O)}if(Z.length>0){let U=Z.map((z)=>G0.tableColumns(z));await $.redis.delBatch(U)}}catch(Z){throw j.error({err:Z,msg:"\u6570\u636E\u5E93\u540C\u6B65\u5931\u8D25"}),Z}},w$={MYSQL_MIN_MAJOR:8,POSTGRES_MIN_MAJOR:17,SQLITE_MIN_VERSION:"3.50.0",SQLITE_MIN_VERSION_NUM:35000},dX={length:"\u957F\u5EA6",datatype:"\u7C7B\u578B",comment:"\u6CE8\u91CA",default:"\u9ED8\u8BA4\u503C",nullable:"\u53EF\u7A7A\u7EA6\u675F",unique:"\u552F\u4E00\u7EA6\u675F"},sX={ENGINE:"InnoDB",CHARSET:"utf8mb4",COLLATE:"utf8mb4_0900_ai_ci"},GJ=[{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"}],gZ=GJ.filter(($)=>$.needsIndex).map(($)=>$.name),oX={};for(let $ of GJ)oX[$.name]=$;var lX={DB_VERSION_REQUIREMENTS:w$,CHANGE_TYPE_LABELS:dX,MYSQL_TABLE_CONFIG:sX,SYSTEM_INDEX_FIELDS:gZ,getTypeMapping:CJ,quoteIdentifier:X0,escapeComment:wJ,applyFieldDefaults:rX,isStringOrArrayType:ZJ,getSqlType:hZ,resolveDefaultValue:XJ,generateDefaultSql:EJ,buildIndexSQL:LJ,buildSystemColumnDefs:tX,buildBusinessColumnDefs:aX,generateDDLClause:fZ,isCompatibleTypeChange:eX,compareFieldDefinition:ZY,tableExistsRuntime:$Y,getTableColumnsRuntime:JY,getTableIndexesRuntime:bZ,createRuntime:($,J,Z="")=>{return{dbDialect:$,db:J,dbName:Z}}};SJ.TestKit=lX;Object.defineProperty(SJ,"TestKit",{value:lX,writable:!1,enumerable:!0,configurable:!1});function CJ($){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 X0($,J){return h$($).quoteIdent(J)}function wJ($){return String($).replace(/"/g,"\\\"")}function rX($){if(!$||typeof $!=="object")return;let J=W$($);$.detail=J.detail,$.min=J.min,$.max=J.max,$.default=J.default,$.index=J.index,$.unique=J.unique,$.nullable=J.nullable,$.unsigned=J.unsigned,$.regexp=J.regexp}function ZJ($){return $==="string"||$==="array_string"||$==="array_number_string"}function hZ($,J,Z,G=!1){let X=CJ($);if(ZJ(J))return`${X[J]}(${Z})`;let Y=X[J]||"TEXT";if($==="mysql"&&J==="number"&&G)return`${Y} UNSIGNED`;return Y}function XJ($,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 EJ($,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 LJ($,J,Z,G,X){let Y=X0($,J),H=X0($,Z),U=X0($,G);if($==="mysql"){let z=[];if(X==="create")z.push(`ADD INDEX ${H} (${U})`);else z.push(`DROP INDEX ${H}`);return`ALTER TABLE ${Y} ALGORITHM=INPLACE, LOCK=NONE, ${z.join(", ")}`}if($==="postgresql"){if(X==="create")return`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${H} ON ${Y}(${U})`;return`DROP INDEX CONCURRENTLY IF EXISTS ${H}`}if(X==="create")return`CREATE INDEX IF NOT EXISTS ${H} ON ${Y}(${U})`;return`DROP INDEX IF EXISTS ${H}`}function iX($,J){let Z=oX[J];if(!Z)return null;let G=X0($,Z.name);if($==="mysql")return`${G} ${Z.mysqlDdl} COMMENT "${wJ(Z.comment)}"`;if($==="postgresql")return`${G} ${Z.pgDdl}`;return`${G} ${Z.sqliteDdl}`}function tX($){let J=[];for(let Z of GJ){let G=iX($,Z.name);if(G)J.push(G)}return J}function aX($,J){let Z=[];for(let[G,X]of Object.entries(J)){let Y=W$(X),H=f(G),U=X0($,H),z=hZ($,Y.type,Y.max,Y.unsigned),O=XJ(Y.default,Y.type),_=EJ(O,Y.type),I=Y.unique?" UNIQUE":"",B=Y.nullable?" NULL":" NOT NULL";if($==="mysql")Z.push(`${U} ${z}${I}${B}${_} COMMENT "${wJ(Y.name)}"`);else Z.push(`${U} ${z}${I}${B}${_}`)}return Z}function fZ($,J,Z,G=!1){let X=f(J),Y=X0($,X),H=W$(Z),U=hZ($,H.type,H.max,H.unsigned),z=XJ(H.default,H.type),O=EJ(z,H.type),_=H.unique?" UNIQUE":"",I=H.nullable?" NULL":" NOT NULL";if($==="mysql")return`${G?"ADD COLUMN":"MODIFY COLUMN"} ${Y} ${U}${_}${I}${O} COMMENT "${wJ(H.name)}"`;if($==="postgresql"){if(G)return`ADD COLUMN IF NOT EXISTS ${Y} ${U}${_}${I}${O}`;return`ALTER COLUMN ${Y} TYPE ${U}`}if(G)return`ADD COLUMN IF NOT EXISTS ${Y} ${U}${_}${I}${O}`;return""}async function mX($,J){try{return await $.unsafe(J),!0}catch(Z){if(J.includes("ALGORITHM=INSTANT")){let G=J.replace(/ALGORITHM=INSTANT/g,"ALGORITHM=INPLACE");try{return await $.unsafe(G),!0}catch{let X=J;return X=X.replace(/\bALGORITHM\s*=\s*(INPLACE|INSTANT)\b\s*,?\s*/g,"").replace(/\bLOCK\s*=\s*(NONE|SHARED|EXCLUSIVE)\b\s*,?\s*/g,""),X=X.replace(/,\s*,/g,", ").replace(/,\s*$/g,"").replace(/\s{2,}/g," ").trim(),await $.unsafe(X),!0}}else throw Z}}function eX($,J){let Z=String($||"").toLowerCase(),G=String(J||"").toLowerCase();if(Z===G)return!1;let X=Z.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),Y=G.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),H=["tinyint","smallint","mediumint","int","integer","bigint"],U=H.indexOf(X),z=H.indexOf(Y);if(U!==-1&&z!==-1&&z>U)return!0;if(X==="varchar"&&(Y==="text"||Y==="mediumtext"||Y==="longtext"))return!0;if(X==="character varying"&&Y==="text")return!0;return!1}async function $Y($,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 G=h$($.dbDialect).tableExistsQuery(J,Z);return((await $.db.unsafe(G.sql,G.params)).data?.[0]?.count||0)>0}catch(Z){let G=String(Z?.message||Z),X=Error(`runtime I/O \u5931\u8D25: op=tableExists table=${J} err=${G}`);if(Z?.sqlInfo)X.sqlInfo=Z.sqlInfo;throw X}}async function JY($,J){let Z={};try{if($.dbDialect==="mysql"){let G=PJ({dialect:"mysql",table:J,dbName:$.dbName}),X=await $.db.unsafe(G.columns.sql,G.columns.params);for(let Y of X.data){let H=Y.COLUMN_DEFAULT;Z[Y.COLUMN_NAME]={type:Y.DATA_TYPE,columnType:Y.COLUMN_TYPE,length:Y.CHARACTER_MAXIMUM_LENGTH,max:Y.CHARACTER_MAXIMUM_LENGTH,nullable:Y.IS_NULLABLE==="YES",defaultValue:H,comment:Y.COLUMN_COMMENT}}}else if($.dbDialect==="postgresql"){let G=PJ({dialect:"postgresql",table:J,dbName:$.dbName}),X=await $.db.unsafe(G.columns.sql,G.columns.params),Y=G.comments?(await $.db.unsafe(G.comments.sql,G.comments.params)).data:[],H={};for(let U of Y)H[U.column_name]=U.column_comment;for(let U of X.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:H[U.column_name]??null}}else if($.dbDialect==="sqlite"){let G=PJ({dialect:"sqlite",table:J,dbName:$.dbName}),X=await $.db.unsafe(G.columns.sql,G.columns.params);for(let Y of X.data){let H=String(Y.type||"").toUpperCase(),U=null,z=/^(\w+)\s*\((\d+)\)/.exec(H);if(z){let O=z[1],_=z[2];if(typeof O==="string")H=O;if(typeof _==="string")U=Number(_)}Z[Y.name]={type:H.toLowerCase(),columnType:H.toLowerCase(),length:U,max:U,nullable:Y.notnull===0,defaultValue:Y.dflt_value,comment:null}}}return Z}catch(G){let X=String(G?.message||G),Y=Error(`runtime I/O \u5931\u8D25: op=getTableColumns table=${J} err=${X}`);if(G?.sqlInfo)Y.sqlInfo=G.sqlInfo;throw Y}}async function bZ($,J){let Z={};try{if($.dbDialect==="mysql"){let G=xZ({dialect:"mysql",table:J,dbName:$.dbName}),X=await $.db.unsafe(G.sql,G.params);for(let Y of X.data){let H=Y.INDEX_NAME,U=Z[H];if(Array.isArray(U))U.push(Y.COLUMN_NAME);else Z[H]=[Y.COLUMN_NAME]}}else if($.dbDialect==="postgresql"){let G=xZ({dialect:"postgresql",table:J,dbName:$.dbName}),X=await $.db.unsafe(G.sql,G.params);for(let Y of X.data){let H=/\(([^)]+)\)/.exec(Y.indexdef);if(H){let U=H[1],z=typeof U==="string"?U.replace(/"/g,"").trim():"";Z[Y.indexname]=[z]}}}else if($.dbDialect==="sqlite"){let G=X0("sqlite",J),X=await $.db.unsafe(`PRAGMA index_list(${G})`);for(let Y of X.data){let H=X0("sqlite",Y.name),z=(await $.db.unsafe(`PRAGMA index_info(${H})`)).data.map((O)=>O.name);if(z.length===1)Z[Y.name]=z}}return Z}catch(G){let X=String(G?.message||G),Y=Error(`runtime I/O \u5931\u8D25: op=getTableIndexes table=${J} err=${X}`);if(G?.sqlInfo)Y.sqlInfo=G.sqlInfo;throw Y}}async function BH($,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 G=Z.data[0].version,X=String(G).split(".")[0]||"0",Y=parseInt(X,10);if(!Number.isFinite(Y)||Y<w$.MYSQL_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u4EC5\u652F\u6301 MySQL ${w$.MYSQL_MIN_MAJOR}.0+\uFF0C\u5F53\u524D\u7248\u672C: ${G}`);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 G=Z.data[0].version,X=/PostgreSQL\s+(\d+)/i.exec(G),Y=X?X[1]:void 0,H=typeof Y==="string"?parseInt(Y,10):NaN;if(!Number.isFinite(H)||H<w$.POSTGRES_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 PostgreSQL >= ${w$.POSTGRES_MIN_MAJOR}\uFF0C\u5F53\u524D: ${G}`);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 G=Z.data[0].version,X=String(G).split(".").map((O)=>parseInt(O,10)||0),Y=X[0]??0,H=X[1]??0,U=X[2]??0,z=Y*1e4+H*100+U;if(!Number.isFinite(z)||z<w$.SQLITE_MIN_VERSION_NUM)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 SQLite >= ${w$.SQLITE_MIN_VERSION}\uFF0C\u5F53\u524D: ${G}`);return}}function ZY($,J,Z){let G=[],X=W$(Z);if($!=="sqlite"&&ZJ(X.type)){let I=X.max;if(I!==null&&J.max!==I)G.push({type:"length",current:J.max,expected:I})}if($!=="sqlite"){let I=J.comment||"";if(I!==X.name)G.push({type:"comment",current:I,expected:X.name})}let H=CJ($)[X.type];if(typeof H!=="string")throw Error(`\u672A\u77E5\u5B57\u6BB5\u7C7B\u578B\u6620\u5C04\uFF1Adialect=${$} type=${String(X.type)}`);let U=H.toLowerCase(),z=J.type.toLowerCase();if(z!==U)G.push({type:"datatype",current:z,expected:U});let O=X.nullable;if(J.nullable!==O)G.push({type:"nullable",current:J.nullable,expected:O});let _=XJ(X.default,X.type);if(String(J.defaultValue)!==String(_))G.push({type:"default",current:J.defaultValue,expected:_});return G}async function LH($,J,Z){if($.dbDialect!=="sqlite")throw Error(`rebuildSqliteTable \u4EC5\u652F\u6301 sqlite \u65B9\u8A00\uFF0C\u5F53\u524D: ${String($.dbDialect)}`);let G=X0("sqlite",J),Y=(await $.db.unsafe(`PRAGMA table_info(${G})`)).data.map((I)=>I.name),U=["id","created_at","updated_at","deleted_at","state",...Object.keys(Z).map((I)=>f(I))],z=`${J}__tmp__${Date.now()}`;await GY($,z,Z);let O=U.filter((I)=>Y.includes(I));if(O.length>0){let I=O.map((S)=>X0("sqlite",S)).join(", "),B=X0("sqlite",z);await $.db.unsafe(`INSERT INTO ${B} (${I}) SELECT ${I} FROM ${G}`)}await $.db.unsafe(`DROP TABLE ${G}`);let _=X0("sqlite",z);await $.db.unsafe(`ALTER TABLE ${_} RENAME TO ${G}`)}async function SH($,J,Z,G){if(!G||!G.changed)return;if($.dbDialect==="sqlite")if(G.modifyClauses.length>0||G.defaultClauses.length>0)await LH($,J,Z);else for(let X of G.addClauses){let Y=`ALTER TABLE ${X0($.dbDialect,J)} ${X}`;await $.db.unsafe(Y)}else{let X=[...G.addClauses,...G.modifyClauses];if(X.length>0){let Y=X0($.dbDialect,J),H=$.dbDialect==="mysql"?`ALTER TABLE ${Y} ALGORITHM=INSTANT, LOCK=NONE, ${X.join(", ")}`:`ALTER TABLE ${Y} ${X.join(", ")}`;if($.dbDialect==="mysql")await mX($.db,H);else await $.db.unsafe(H)}}if(G.defaultClauses.length>0)if($.dbDialect==="sqlite")j.warn(`SQLite \u4E0D\u652F\u6301\u4FEE\u6539\u9ED8\u8BA4\u503C\uFF0C\u8868 ${J} \u7684\u9ED8\u8BA4\u503C\u53D8\u66F4\u5DF2\u8DF3\u8FC7`);else{let X=X0($.dbDialect,J),Y=$.dbDialect==="mysql"?`ALTER TABLE ${X} ALGORITHM=INSTANT, LOCK=NONE, ${G.defaultClauses.join(", ")}`:`ALTER TABLE ${X} ${G.defaultClauses.join(", ")}`;if($.dbDialect==="mysql")await mX($.db,Y);else await $.db.unsafe(Y)}for(let X of G.indexActions){let Y=LJ($.dbDialect,J,X.indexName,X.fieldName,X.action);try{if(await $.db.unsafe(Y),X.action==="create")j.debug(`[\u7D22\u5F15\u53D8\u5316] \u65B0\u5EFA\u7D22\u5F15 ${J}.${X.indexName} (${X.fieldName})`);else j.debug(`[\u7D22\u5F15\u53D8\u5316] \u5220\u9664\u7D22\u5F15 ${J}.${X.indexName} (${X.fieldName})`)}catch(H){throw j.error({err:H,table:J,index:X.indexName,field:X.fieldName,msg:`${X.action==="create"?"\u521B\u5EFA":"\u5220\u9664"}\u7D22\u5F15\u5931\u8D25`}),H}}if($.dbDialect==="postgresql"&&G.commentActions&&G.commentActions.length>0)for(let X of G.commentActions)await $.db.unsafe(X)}async function GY($,J,Z,G=gZ){let Y=[...tX($.dbDialect),...aX($.dbDialect,Z)].join(`,
7
+ `),H=X0($.dbDialect,J),{ENGINE:U,CHARSET:z,COLLATE:O}=sX,_=$.dbDialect==="mysql"?`CREATE TABLE ${H} (
8
8
  ${Y}
9
- ) ENGINE=${z} DEFAULT CHARSET=${V} COLLATE=${O}`:`CREATE TABLE ${H} (
9
+ ) ENGINE=${U} DEFAULT CHARSET=${z} COLLATE=${O}`:`CREATE TABLE ${H} (
10
10
  ${Y}
11
- )`;if(await $.db.unsafe(_),$.dbDialect==="postgresql"){for(let S of ZJ){let C=String(S.comment).replace(/'/g,"''"),T=G0($.dbDialect,S.name),E=`COMMENT ON COLUMN ${H}.${T} IS '${C}'`;await $.db.unsafe(E)}for(let[S,C]of Object.entries(Z)){let T=f(S),E=G0($.dbDialect,T),D=C.name&&C.name!=="null"?String(C.name):"",w=D.replace(/'/g,"''"),N=D?`'${w}'`:"NULL",p=`COMMENT ON COLUMN ${H}.${E} IS ${N}`;await $.db.unsafe(p)}}let I=[],B={};if($.dbDialect==="mysql")B=await bZ($,J);for(let S of X){let C=`idx_${S}`;if($.dbDialect==="mysql"&&B[C])continue;let T=LJ($.dbDialect,J,C,S,"create");I.push($.db.unsafe(T))}for(let[S,C]of Object.entries(Z)){let T=f(S);if(C.index===!0&&C.unique!==!0){let E=`idx_${T}`;if($.dbDialect==="mysql"&&B[E])continue;let D=LJ($.dbDialect,J,E,T,"create");I.push($.db.unsafe(D))}}if(I.length>0)await Promise.all(I)}async function wH($,J,Z){let X=await Z1($,J),G=await bZ($,J),Y=!1,H=[],z=[],V=[],O=[];for(let[S,C]of Object.entries(Z)){let T=f(S);if(X[T]){let E=X1($.dbDialect,X[T],C);if(E.length>0){for(let v of E){let b=sG[v.type]||"\u672A\u77E5";j.debug(` ~ \u4FEE\u6539 ${T} ${b}: ${v.current} -> ${v.expected}`)}if(JJ(C.type)&&X[T].max&&C.max!==null){if(X[T].max>C.max)j.warn(`[\u8DF3\u8FC7\u5371\u9669\u53D8\u66F4] ${J}.${T} \u957F\u5EA6\u6536\u7F29 ${X[T].max} -> ${C.max} \u5DF2\u88AB\u8DF3\u8FC7\uFF08\u9700\u624B\u52A8\u5904\u7406\uFF09`)}let D=E.some((v)=>v.type==="datatype"),w=E.some((v)=>v.type==="length"),N=E.every((v)=>v.type==="default"),p=E.some((v)=>v.type==="default");if(D){let v=E.find((u0)=>u0.type==="datatype"),b=String(v?.current||"").toLowerCase(),o=CJ($.dbDialect)[C.type]?.toLowerCase()||"";if(!$1(b,o)){let u0=[`\u7981\u6B62\u5B57\u6BB5\u7C7B\u578B\u53D8\u66F4: ${J}.${T}`,`\u5F53\u524D\u7C7B\u578B: ${v?.current}`,`\u76EE\u6807\u7C7B\u578B: ${v?.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(`
12
- `);throw Error(u0)}j.debug(`[\u517C\u5BB9\u7C7B\u578B\u53D8\u66F4] ${J}.${T} ${b} -> ${o}`)}if(p){let v=XJ(C.default,C.type),b=null;if(v!=="null")b=EJ(v,C.type).trim().replace(/^DEFAULT\s+/,"");if(b!==null&&b!==""){if($.dbDialect==="postgresql"){let r=G0($.dbDialect,T);V.push(`ALTER COLUMN ${r} SET DEFAULT ${b}`)}else if($.dbDialect==="mysql"&&N){if(C.type!=="text"){let r=G0($.dbDialect,T);V.push(`ALTER COLUMN ${r} SET DEFAULT ${b}`)}}}}if(!N){let v=!1;if(w&&JJ(C.type)&&X[T].max&&C.max!==null){if(X[T].max>C.max)v=!0}if(!v)z.push(fZ($.dbDialect,S,C,!1))}Y=!0}}else H.push(fZ($.dbDialect,S,C,!0)),Y=!0}let _=ZJ.filter((S)=>S.name!=="id").map((S)=>S.name);for(let S of _)if(!X[S]){let C=tG($.dbDialect,S);if(C)j.debug(` + \u65B0\u589E\u7CFB\u7EDF\u5B57\u6BB5 ${S}`),H.push(`ADD COLUMN ${C}`),Y=!0}for(let S of gZ){let C=`idx_${S}`;if((X[S]||_.includes(S))&&!G[C])O.push({action:"create",indexName:C,fieldName:S}),Y=!0}for(let[S,C]of Object.entries(Z)){let T=f(S),E=`idx_${T}`;if(C.index&&!C.unique&&!G[E])O.push({action:"create",indexName:E,fieldName:T}),Y=!0;else if(!C.index&&G[E]&&G[E].length===1)O.push({action:"drop",indexName:E,fieldName:T}),Y=!0}let I=[];if($.dbDialect==="postgresql"){let S=G0($.dbDialect,J);for(let[C,T]of Object.entries(Z)){let E=f(C),D=G0($.dbDialect,E);if(X[E]){let w=X[E].comment||"",N=T.name&&T.name!=="null"?String(T.name):"";if(N!==w){let p=N.replace(/'/g,"''");I.push(`COMMENT ON COLUMN ${S}.${D} IS ${N?`'${p}'`:"NULL"}`),Y=!0}}}}Y=H.length>0||z.length>0||V.length>0||O.length>0||I.length>0;let B={changed:Y,addClauses:H,modifyClauses:z,defaultClauses:V,indexActions:O,commentActions:I};if(B.changed)await CH($,J,Z,B);return B}var Y1=($,J=Bun.nanoseconds())=>{let Z=(J-$)/1e6;if(Z<1000)return`${Z.toFixed(2)} \u6BEB\u79D2`;else return`${(Z/1000).toFixed(2)} \u79D2`};function W1($){let J=$||{},Z=J.BUN_WORKER_ID,X=J.PM2_INSTANCE_ID;if(Z!==void 0)return{role:Z===""?"primary":"worker",instanceId:Z||"0",env:"bun-cluster"};if(X!==void 0)return{role:X==="0"?"primary":"worker",instanceId:X,env:"pm2-cluster"};return{role:"primary",instanceId:null,env:"standalone"}}q$();q$();import{existsSync as EH,readdirSync as TH}from"fs";DZ();n0();var H1=()=>{let $=new Map,J=(Z,X,G)=>{if(!EH(Z))return;let Y=TH(Z,{withFileTypes:!0});for(let H of Y){if(H.name.startsWith("_"))continue;if(!RJ(Z,H))continue;let z=a$(Z,H.name),V={source:X,sourceName:G,name:H.name,camelName:_$(H.name),rootDir:z,fullPath:z};$.set(H.name,V)}};return J(m(d0,"node_modules","@befly-addon"),"addon","\u7EC4\u4EF6"),J(fG,"app","\u9879\u76EE"),Array.from($.values())};OJ();var NH={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 G=await $.jwt.verify(X);J.user=G,$G(G.id,G.roleCode,G.nickname,G.roleType)}catch{J.user={}}}else J.user={}}},Q1=NH;var vH={name:"cors",enable:!0,deps:[],handler:async($,J)=>{let Z=J.req,G=Object.assign({},{origin:"*",methods:"GET, POST, 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:{}),Y=jJ(Z,G);if(J.corsHeaders=Y,Z.method==="OPTIONS"){J.response=new Response(null,{status:204,headers:Y});return}}},z1=vH;var DH=":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",kH="[: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]["+DH+"]*",xH=new RegExp("^"+kH+"$");function TJ($,J){let Z=[],X=J.exec($);while(X){let G=[];G.startIndex=J.lastIndex-X[0].length;let Y=X.length;for(let H=0;H<Y;H++)G.push(X[H]);Z.push(G),X=J.exec($)}return Z}var h$=function($){let J=xH.exec($);return!(J===null||typeof J>"u")};function U1($){return typeof $<"u"}var yH={allowBooleanAttributes:!1,unpairedTags:[]};function _1($,J){J=Object.assign({},yH,J);let Z=[],X=!1,G=!1;if($[0]==="\uFEFF")$=$.substr(1);for(let Y=0;Y<$.length;Y++)if($[Y]==="<"&&$[Y+1]==="?"){if(Y+=2,Y=O1($,Y),Y.err)return Y}else if($[Y]==="<"){let H=Y;if(Y++,$[Y]==="!"){Y=K1($,Y);continue}else{let z=!1;if($[Y]==="/")z=!0,Y++;let V="";for(;Y<$.length&&$[Y]!==">"&&$[Y]!==" "&&$[Y]!=="\t"&&$[Y]!==`
13
- `&&$[Y]!=="\r";Y++)V+=$[Y];if(V=V.trim(),V[V.length-1]==="/")V=V.substring(0,V.length-1),Y--;if(!nH(V)){let I;if(V.trim().length===0)I="Invalid space after '<'.";else I="Tag '"+V+"' is an invalid name.";return Y0("InvalidTag",I,s0($,Y))}let O=hH($,Y);if(O===!1)return Y0("InvalidAttr","Attributes for '"+V+"' have open quote.",s0($,Y));let _=O.value;if(Y=O.index,_[_.length-1]==="/"){let I=Y-_.length;_=_.substring(0,_.length-1);let B=M1(_,J);if(B===!0)X=!0;else return Y0(B.err.code,B.err.msg,s0($,I+B.err.line))}else if(z)if(!O.tagClosed)return Y0("InvalidTag","Closing tag '"+V+"' doesn't have proper closing.",s0($,Y));else if(_.trim().length>0)return Y0("InvalidTag","Closing tag '"+V+"' can't have attributes or invalid starting.",s0($,H));else if(Z.length===0)return Y0("InvalidTag","Closing tag '"+V+"' has not been opened.",s0($,H));else{let I=Z.pop();if(V!==I.tagName){let B=s0($,I.tagStartPos);return Y0("InvalidTag","Expected closing tag '"+I.tagName+"' (opened in line "+B.line+", col "+B.col+") instead of closing tag '"+V+"'.",s0($,H))}if(Z.length==0)G=!0}else{let I=M1(_,J);if(I!==!0)return Y0(I.err.code,I.err.msg,s0($,Y-_.length+I.err.line));if(G===!0)return Y0("InvalidXml","Multiple possible root nodes found.",s0($,Y));else if(J.unpairedTags.indexOf(V)!==-1);else Z.push({tagName:V,tagStartPos:H});X=!0}for(Y++;Y<$.length;Y++)if($[Y]==="<")if($[Y+1]==="!"){Y++,Y=K1($,Y);continue}else if($[Y+1]==="?"){if(Y=O1($,++Y),Y.err)return Y}else break;else if($[Y]==="&"){let I=pH($,Y);if(I==-1)return Y0("InvalidChar","char '&' is not expected.",s0($,Y));Y=I}else if(G===!0&&!V1($[Y]))return Y0("InvalidXml","Extra text at the end",s0($,Y));if($[Y]==="<")Y--}}else{if(V1($[Y]))continue;return Y0("InvalidChar","char '"+$[Y]+"' is not expected.",s0($,Y))}if(!X)return Y0("InvalidXml","Start tag expected.",1);else if(Z.length==1)return Y0("InvalidTag","Unclosed tag '"+Z[0].tagName+"'.",s0($,Z[0].tagStartPos));else if(Z.length>0)return Y0("InvalidXml","Invalid '"+JSON.stringify(Z.map((Y)=>Y.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function V1($){return $===" "||$==="\t"||$===`
14
- `||$==="\r"}function O1($,J){let Z=J;for(;J<$.length;J++)if($[J]=="?"||$[J]==" "){let X=$.substr(Z,J-Z);if(J>5&&X==="xml")return Y0("InvalidXml","XML declaration allowed only at the start of the document.",s0($,J));else if($[J]=="?"&&$[J+1]==">"){J++;break}else continue}return J}function K1($,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 fH='"',gH="'";function hH($,J){let Z="",X="",G=!1;for(;J<$.length;J++){if($[J]===fH||$[J]===gH)if(X==="")X=$[J];else if(X!==$[J]);else X="";else if($[J]===">"){if(X===""){G=!0;break}}Z+=$[J]}if(X!=="")return!1;return{value:Z,index:J,tagClosed:G}}var bH=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function M1($,J){let Z=TJ($,bH),X={};for(let G=0;G<Z.length;G++){if(Z[G][1].length===0)return Y0("InvalidAttr","Attribute '"+Z[G][2]+"' has no space in starting.",GJ(Z[G]));else if(Z[G][3]!==void 0&&Z[G][4]===void 0)return Y0("InvalidAttr","Attribute '"+Z[G][2]+"' is without value.",GJ(Z[G]));else if(Z[G][3]===void 0&&!J.allowBooleanAttributes)return Y0("InvalidAttr","boolean attribute '"+Z[G][2]+"' is not allowed.",GJ(Z[G]));let Y=Z[G][2];if(!uH(Y))return Y0("InvalidAttr","Attribute '"+Y+"' is an invalid name.",GJ(Z[G]));if(!X.hasOwnProperty(Y))X[Y]=1;else return Y0("InvalidAttr","Attribute '"+Y+"' is repeated.",GJ(Z[G]))}return!0}function cH($,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 pH($,J){if(J++,$[J]===";")return-1;if($[J]==="#")return J++,cH($,J);let Z=0;for(;J<$.length;J++,Z++){if($[J].match(/\w/)&&Z<20)continue;if($[J]===";")break;return-1}return J}function Y0($,J,Z){return{err:{code:$,msg:J,line:Z.line||Z,col:Z.col}}}function uH($){return h$($)}function nH($){return h$($)}function s0($,J){let Z=$.substring(0,J).split(/\r?\n/);return{line:Z.length,col:Z[Z.length-1].length+1}}function GJ($){return $.startIndex+$[1].length}var mH={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},A1=function($){return Object.assign({},mH,$)};var NJ;if(typeof Symbol!=="function")NJ="@@xmlMetadata";else NJ=Symbol("XML Node Metadata");class i0{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][NJ]={startIndex:J}}static getMetaDataSymbol(){return NJ}}class vJ{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,G=!1,Y=!1,H="";for(;J<$.length;J++)if($[J]==="<"&&!Y){if(G&&w$($,"!ENTITY",J)){J+=7;let z,V;if([z,V,J]=this.readEntityExp($,J+1,this.suppressValidationErr),V.indexOf("&")===-1)Z[z]={regx:RegExp(`&${z};`,"g"),val:V}}else if(G&&w$($,"!ELEMENT",J)){J+=8;let{index:z}=this.readElementExp($,J+1);J=z}else if(G&&w$($,"!ATTLIST",J))J+=8;else if(G&&w$($,"!NOTATION",J)){J+=9;let{index:z}=this.readNotationExp($,J+1,this.suppressValidationErr);J=z}else if(w$($,"!--",J))Y=!0;else throw Error("Invalid DOCTYPE");X++,H=""}else if($[J]===">"){if(Y){if($[J-1]==="-"&&$[J-2]==="-")Y=!1,X--}else X--;if(X===0)break}else if($[J]==="[")G=!0;else H+=$[J];if(X!==0)throw Error("Unclosed DOCTYPE")}else throw Error("Invalid Tag instead of DOCTYPE");return{entities:Z,i:J}}readEntityExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J])&&$[J]!=='"'&&$[J]!=="'")Z+=$[J],J++;if(YJ(Z),J=l0($,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=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;!this.suppressValidationErr&&YJ(Z),J=l0($,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=l0($,J);let G=null,Y=null;if(X==="PUBLIC"){if([J,G]=this.readIdentifierVal($,J,"publicIdentifier"),J=l0($,J),$[J]==='"'||$[J]==="'")[J,Y]=this.readIdentifierVal($,J,"systemIdentifier")}else if(X==="SYSTEM"){if([J,Y]=this.readIdentifierVal($,J,"systemIdentifier"),!this.suppressValidationErr&&!Y)throw Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:Z,publicIdentifier:G,systemIdentifier:Y,index:--J}}readIdentifierVal($,J,Z){let X="",G=$[J];if(G!=='"'&&G!=="'")throw Error(`Expected quoted string, found "${G}"`);J++;while(J<$.length&&$[J]!==G)X+=$[J],J++;if($[J]!==G)throw Error(`Unterminated ${Z} value`);return J++,[J,X]}readElementExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;if(!this.suppressValidationErr&&!h$(Z))throw Error(`Invalid element name: "${Z}"`);J=l0($,J);let X="";if($[J]==="E"&&w$($,"MPTY",J))J+=4;else if($[J]==="A"&&w$($,"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=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;YJ(Z),J=l0($,J);let X="";while(J<$.length&&!/\s/.test($[J]))X+=$[J],J++;if(!YJ(X))throw Error(`Invalid attribute name: "${X}"`);J=l0($,J);let G="";if($.substring(J,J+8).toUpperCase()==="NOTATION"){if(G="NOTATION",J+=8,J=l0($,J),$[J]!=="(")throw Error(`Expected '(', found "${$[J]}"`);J++;let H=[];while(J<$.length&&$[J]!==")"){let z="";while(J<$.length&&$[J]!=="|"&&$[J]!==")")z+=$[J],J++;if(z=z.trim(),!YJ(z))throw Error(`Invalid notation name: "${z}"`);if(H.push(z),$[J]==="|")J++,J=l0($,J)}if($[J]!==")")throw Error("Unterminated list of notations");J++,G+=" ("+H.join("|")+")"}else{while(J<$.length&&!/\s/.test($[J]))G+=$[J],J++;let H=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!H.includes(G.toUpperCase()))throw Error(`Invalid attribute type: "${G}"`)}J=l0($,J);let Y="";if($.substring(J,J+8).toUpperCase()==="#REQUIRED")Y="#REQUIRED",J+=8;else if($.substring(J,J+7).toUpperCase()==="#IMPLIED")Y="#IMPLIED",J+=7;else[J,Y]=this.readIdentifierVal($,J,"ATTLIST");return{elementName:Z,attributeName:X,attributeType:G,defaultValue:Y,index:J}}}var l0=($,J)=>{while(J<$.length&&/\s/.test($[J]))J++;return J};function w$($,J,Z){for(let X=0;X<J.length;X++)if(J[X]!==$[Z+X+1])return!1;return!0}function YJ($){if(h$($))return $;else throw Error(`Invalid entity name ${$}`)}var dH=/^[-+]?0x[a-fA-F0-9]+$/,sH=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,oH={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function cZ($,J={}){if(J=Object.assign({},oH,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&&dH.test(Z))return tH(Z,16);else if(Z.includes("e")||Z.includes("E"))return rH($,Z,J);else{let X=sH.exec(Z);if(X){let G=X[1]||"",Y=X[2],H=iH(X[3]),z=G?$[Y.length+1]===".":$[Y.length]===".";if(!J.leadingZeros&&(Y.length>1||Y.length===1&&!z))return $;else{let V=Number(Z),O=String(V);if(V===0)return V;if(O.search(/[eE]/)!==-1)if(J.eNotation)return V;else return $;else if(Z.indexOf(".")!==-1)if(O==="0")return V;else if(O===H)return V;else if(O===`${G}${H}`)return V;else return $;let _=Y?H:Z;if(Y)return _===O||G+_===O?V:$;else return _===O||_===G+O?V:$}}else return $}}var lH=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function rH($,J,Z){if(!Z.eNotation)return $;let X=J.match(lH);if(X){let G=X[1]||"",Y=X[3].indexOf("e")===-1?"E":"e",H=X[2],z=G?$[H.length+1]===Y:$[H.length]===Y;if(H.length>1&&z)return $;else if(H.length===1&&(X[3].startsWith(`.${Y}`)||X[3][0]===Y))return Number(J);else if(Z.leadingZeros&&!z)return J=(X[1]||"")+X[3],Number(J);else return $}else return $}function iH($){if($&&$.indexOf(".")!==-1){if($=$.replace(/0+$/,""),$===".")$="0";else if($[0]===".")$="0"+$;else if($[$.length-1]===".")$=$.substring(0,$.length-1);return $}return $}function tH($,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 pZ($){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 DJ{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=aH,this.parseXml=X9,this.parseTextData=eH,this.resolveNameSpace=$9,this.buildAttributesMap=Z9,this.isItStopNode=H9,this.replaceEntitiesValue=Y9,this.readStopNodeData=z9,this.saveTextToParentTag=W9,this.addChild=G9,this.ignoreAttributesFn=pZ(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 aH($){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 eH($,J,Z,X,G,Y,H){if($!==void 0){if(this.options.trimValues&&!X)$=$.trim();if($.length>0){if(!H)$=this.replaceEntitiesValue($);let z=this.options.tagValueProcessor(J,$,Z,G,Y);if(z===null||z===void 0)return $;else if(typeof z!==typeof $||z!==$)return z;else if(this.options.trimValues)return nZ($,this.options.parseTagValue,this.options.numberParseOptions);else if($.trim()===$)return nZ($,this.options.parseTagValue,this.options.numberParseOptions);else return $}}}function $9($){if(this.options.removeNSPrefix){let J=$.split(":"),Z=$.charAt(0)==="/"?"/":"";if(J[0]==="xmlns")return"";if(J.length===2)$=Z+J[1]}return $}var J9=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Z9($,J){if(this.options.ignoreAttributes!==!0&&typeof $==="string"){let Z=TJ($,J9),X=Z.length,G={};for(let Y=0;Y<X;Y++){let H=this.resolveNameSpace(Z[Y][1]);if(this.ignoreAttributesFn(H,J))continue;let z=Z[Y][4],V=this.options.attributeNamePrefix+H;if(H.length){if(this.options.transformAttributeName)V=this.options.transformAttributeName(V);if(V==="__proto__")V="#__proto__";if(z!==void 0){if(this.options.trimValues)z=z.trim();z=this.replaceEntitiesValue(z);let O=this.options.attributeValueProcessor(H,z,J);if(O===null||O===void 0)G[V]=z;else if(typeof O!==typeof z||O!==z)G[V]=O;else G[V]=nZ(z,this.options.parseAttributeValue,this.options.numberParseOptions)}else if(this.options.allowBooleanAttributes)G[V]=!0}}if(!Object.keys(G).length)return;if(this.options.attributesGroupName){let Y={};return Y[this.options.attributesGroupName]=G,Y}return G}}var X9=function($){$=$.replace(/\r\n?/g,`
15
- `);let J=new i0("!xml"),Z=J,X="",G="",Y=new vJ(this.options.processEntities);for(let H=0;H<$.length;H++)if($[H]==="<")if($[H+1]==="/"){let V=E$($,">",H,"Closing Tag is not closed."),O=$.substring(H+2,V).trim();if(this.options.removeNSPrefix){let B=O.indexOf(":");if(B!==-1)O=O.substr(B+1)}if(this.options.transformTagName)O=this.options.transformTagName(O);if(Z)X=this.saveTextToParentTag(X,Z,G);let _=G.substring(G.lastIndexOf(".")+1);if(O&&this.options.unpairedTags.indexOf(O)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${O}>`);let I=0;if(_&&this.options.unpairedTags.indexOf(_)!==-1)I=G.lastIndexOf(".",G.lastIndexOf(".")-1),this.tagsNodeStack.pop();else I=G.lastIndexOf(".");G=G.substring(0,I),Z=this.tagsNodeStack.pop(),X="",H=V}else if($[H+1]==="?"){let V=uZ($,H,!1,"?>");if(!V)throw Error("Pi Tag is not closed.");if(X=this.saveTextToParentTag(X,Z,G),this.options.ignoreDeclaration&&V.tagName==="?xml"||this.options.ignorePiTags);else{let O=new i0(V.tagName);if(O.add(this.options.textNodeName,""),V.tagName!==V.tagExp&&V.attrExpPresent)O[":@"]=this.buildAttributesMap(V.tagExp,G);this.addChild(Z,O,G,H)}H=V.closeIndex+1}else if($.substr(H+1,3)==="!--"){let V=E$($,"-->",H+4,"Comment is not closed.");if(this.options.commentPropName){let O=$.substring(H+4,V-2);X=this.saveTextToParentTag(X,Z,G),Z.add(this.options.commentPropName,[{[this.options.textNodeName]:O}])}H=V}else if($.substr(H+1,2)==="!D"){let V=Y.readDocType($,H);this.docTypeEntities=V.entities,H=V.i}else if($.substr(H+1,2)==="!["){let V=E$($,"]]>",H,"CDATA is not closed.")-2,O=$.substring(H+9,V);X=this.saveTextToParentTag(X,Z,G);let _=this.parseTextData(O,Z.tagname,G,!0,!1,!0,!0);if(_==null)_="";if(this.options.cdataPropName)Z.add(this.options.cdataPropName,[{[this.options.textNodeName]:O}]);else Z.add(this.options.textNodeName,_);H=V+2}else{let V=uZ($,H,this.options.removeNSPrefix),O=V.tagName,_=V.rawTagName,I=V.tagExp,B=V.attrExpPresent,S=V.closeIndex;if(this.options.transformTagName){let E=this.options.transformTagName(O);if(I===O)I=E;O=E}if(Z&&X){if(Z.tagname!=="!xml")X=this.saveTextToParentTag(X,Z,G,!1)}let C=Z;if(C&&this.options.unpairedTags.indexOf(C.tagname)!==-1)Z=this.tagsNodeStack.pop(),G=G.substring(0,G.lastIndexOf("."));if(O!==J.tagname)G+=G?"."+O:O;let T=H;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,G,O)){let E="";if(I.length>0&&I.lastIndexOf("/")===I.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),G=G.substr(0,G.length-1),I=O;else I=I.substr(0,I.length-1);H=V.closeIndex}else if(this.options.unpairedTags.indexOf(O)!==-1)H=V.closeIndex;else{let w=this.readStopNodeData($,_,S+1);if(!w)throw Error(`Unexpected end of ${_}`);H=w.i,E=w.tagContent}let D=new i0(O);if(O!==I&&B)D[":@"]=this.buildAttributesMap(I,G);if(E)E=this.parseTextData(E,O,G,!0,B,!0,!0);G=G.substr(0,G.lastIndexOf(".")),D.add(this.options.textNodeName,E),this.addChild(Z,D,G,T)}else{if(I.length>0&&I.lastIndexOf("/")===I.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),G=G.substr(0,G.length-1),I=O;else I=I.substr(0,I.length-1);if(this.options.transformTagName){let D=this.options.transformTagName(O);if(I===O)I=D;O=D}let E=new i0(O);if(O!==I&&B)E[":@"]=this.buildAttributesMap(I,G);this.addChild(Z,E,G,T),G=G.substr(0,G.lastIndexOf("."))}else{let E=new i0(O);if(this.tagsNodeStack.push(Z),O!==I&&B)E[":@"]=this.buildAttributesMap(I,G);this.addChild(Z,E,G,T),Z=E}X="",H=S}}else X+=$[H];return J.child};function G9($,J,Z,X){if(!this.options.captureMetaData)X=void 0;let G=this.options.updateTag(J.tagname,Z,J[":@"]);if(G===!1);else if(typeof G==="string")J.tagname=G,$.addChild(J,X);else $.addChild(J,X)}var Y9=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 W9($,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 H9($,J,Z,X){if(J&&J.has(X))return!0;if($&&$.has(Z))return!0;return!1}function Q9($,J,Z=">"){let X,G="";for(let Y=J;Y<$.length;Y++){let H=$[Y];if(X){if(H===X)X=""}else if(H==='"'||H==="'")X=H;else if(H===Z[0])if(Z[1]){if($[Y+1]===Z[1])return{data:G,index:Y}}else return{data:G,index:Y};else if(H==="\t")H=" ";G+=H}}function E$($,J,Z,X){let G=$.indexOf(J,Z);if(G===-1)throw Error(X);else return G+J.length-1}function uZ($,J,Z,X=">"){let G=Q9($,J+1,X);if(!G)return;let{data:Y,index:H}=G,z=Y.search(/\s/),V=Y,O=!0;if(z!==-1)V=Y.substring(0,z),Y=Y.substring(z+1).trimStart();let _=V;if(Z){let I=V.indexOf(":");if(I!==-1)V=V.substr(I+1),O=V!==G.data.substr(I+1)}return{tagName:V,tagExp:Y,closeIndex:H,attrExpPresent:O,rawTagName:_}}function z9($,J,Z){let X=Z,G=1;for(;Z<$.length;Z++)if($[Z]==="<")if($[Z+1]==="/"){let Y=E$($,">",Z,`${J} is not closed`);if($.substring(Z+2,Y).trim()===J){if(G--,G===0)return{tagContent:$.substring(X,Z),i:Y}}Z=Y}else if($[Z+1]==="?")Z=E$($,"?>",Z+1,"StopNode is not closed.");else if($.substr(Z+1,3)==="!--")Z=E$($,"-->",Z+3,"StopNode is not closed.");else if($.substr(Z+1,2)==="![")Z=E$($,"]]>",Z,"StopNode is not closed.")-2;else{let Y=uZ($,Z,">");if(Y){if((Y&&Y.tagName)===J&&Y.tagExp[Y.tagExp.length-1]!=="/")G++;Z=Y.closeIndex}}}function nZ($,J,Z){if(J&&typeof $==="string"){let X=$.trim();if(X==="true")return!0;else if(X==="false")return!1;else return cZ($,Z)}else if(U1($))return $;else return""}var mZ=i0.getMetaDataSymbol();function dZ($,J){return F1($,J)}function F1($,J,Z){let X,G={};for(let Y=0;Y<$.length;Y++){let H=$[Y],z=U9(H),V="";if(Z===void 0)V=z;else V=Z+"."+z;if(z===J.textNodeName)if(X===void 0)X=H[z];else X+=""+H[z];else if(z===void 0)continue;else if(H[z]){let O=F1(H[z],J,V),_=O9(O,J);if(H[mZ]!==void 0)O[mZ]=H[mZ];if(H[":@"])V9(O,H[":@"],V,J);else if(Object.keys(O).length===1&&O[J.textNodeName]!==void 0&&!J.alwaysCreateTextNode)O=O[J.textNodeName];else if(Object.keys(O).length===0)if(J.alwaysCreateTextNode)O[J.textNodeName]="";else O="";if(G[z]!==void 0&&G.hasOwnProperty(z)){if(!Array.isArray(G[z]))G[z]=[G[z]];G[z].push(O)}else if(J.isArray(z,V,_))G[z]=[O];else G[z]=O}}if(typeof X==="string"){if(X.length>0)G[J.textNodeName]=X}else if(X!==void 0)G[J.textNodeName]=X;return G}function U9($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X!==":@")return X}}function V9($,J,Z,X){if(J){let G=Object.keys(J),Y=G.length;for(let H=0;H<Y;H++){let z=G[H];if(X.isArray(z,Z+"."+z,!0,!0))$[z]=[J[z]];else $[z]=J[z]}}}function O9($,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 WJ{constructor($){this.externalEntities={},this.options=A1($)}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 G=_1($,J);if(G!==!0)throw Error(`${G.err.msg}:${G.err.line}:${G.err.col}`)}let Z=new DJ(this.options);Z.addExternalEntities(this.externalEntities);let X=Z.parseXml($);if(this.options.preserveOrder||X===void 0)return X;else return dZ(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 '&#xD;'");else if(J==="&")throw Error("An entity with value '&' is not permitted");else this.externalEntities[$]=J}static getMetaDataSymbol(){return i0.getMetaDataSymbol()}}var K9=new WJ,M9={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);J.body=X}else if(J.req.method==="POST"){let Z=J.req.headers.get("content-type")||"",X=new URL(J.req.url),G=Object.fromEntries(X.searchParams);try{if(Z.includes("application/json")){let Y=await J.req.json(),H={...G,...Y};J.body=H}else if(Z.includes("application/xml")||Z.includes("text/xml")){let Y=await J.req.text(),H=K9.parse(Y),z=Object.keys(H)[0],V=z&&typeof H[z]==="object"?H[z]:H,O={...G,...V};J.body=O}else{J.response=j$(J,"\u65E0\u6548\u7684\u8BF7\u6C42\u53C2\u6570\u683C\u5F0F",1,null,{location:"content-type",value:Z},"parser");return}}catch{J.response=j$(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}}}},R1=M9;a();var _9={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=j$(J,"\u672A\u767B\u5F55",1,null,null,"auth");return}if(J.user.roleCode==="dev")return;let Z=J.route,X=J.user.roleCode,G=!1;if(X&&$.redis)try{let Y=X0.roleApis(X);G=await $.redis.sismember(Y,Z)}catch(Y){j.error({event:"hook_permission_redis_error",apiPath:Z,roleCode:X,err:Y,msg:"hook permission redis error"}),G=!1}if(!G){let Y=typeof J.api.name==="string"&&J.api.name.length>0?J.api.name:null,H=typeof Z==="string"&&Z.length>0?Z:null,z=Y?Y:H?H:"\u672A\u77E5\u63A5\u53E3";J.response=j$(J,`\u65E0\u6743\u8BBF\u95EE ${z} \u63A5\u53E3`,1,null,{apiLabel:z},"permission");return}}},I1=_9;var sZ={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:".+"},q1=new Map;function A9($){if($.startsWith("@")){let J=$.slice(1);return sZ[J]||$}return $}function j1($,J){let Z=A9($),X=`${Z}:${J||""}`,G=q1.get(X);if(!G)G=new RegExp(Z,J),q1.set(X,G);return G}class oZ{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 G of Z){let Y=$[G];if(Y===void 0||Y===null){let H=J[G]?.name||G;X[G]=`${H}\u4E3A\u5FC5\u586B\u9879`}}for(let[G,Y]of Object.entries(J)){if(X[G])continue;if($[G]===void 0&&!Z.includes(G))continue;let H=this.checkField($[G],Y,G);if(H)X[G]=H}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 G=this.convert($,Z);if(G.error)return{value:null,error:G.error};let Y=this.checkRule(G.value,J);if(Y)return{value:null,error:Y};return{value:G.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:null,errors:J,errorFields:Z,fieldErrors:$}}static checkField($,J,Z){let X=J.name||Z,G=this.convert($,J.type);if(G.error)return`${X}${G.error}`;let Y=this.checkRule(G.value,J);return Y?`${X}${Y}`: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:G,regexp:Y}=J,H=this.resolveRegex(Y);switch(Z.toLowerCase()){case"number":if(X!==null&&$<X)return`\u4E0D\u80FD\u5C0F\u4E8E${X}`;if(G!==null&&G>0&&$>G)return`\u4E0D\u80FD\u5927\u4E8E${G}`;if(H&&!this.testRegex(H,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(G!==null&&G>0&&$.length>G)return`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7${G}\u4E2A\u5B57\u7B26`;if(H&&!this.testRegex(H,$))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(G!==null&&G>0&&$.length>G)return`\u6700\u591A\u53EA\u80FD\u6709${G}\u4E2A\u5143\u7D20`;if(H){for(let z of $)if(!this.testRegex(H,String(z)))return"\u5143\u7D20\u683C\u5F0F\u4E0D\u6B63\u786E"}break}return null}static resolveRegex($){if(!$)return null;if($.startsWith("@")){let J=$.substring(1);return sZ[J]||$}return $}static testRegex($,J){try{return j1($).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""}}}n0();var F9={name:"validator",enable:!0,deps:["parser"],handler:async($,J)=>{if(!J.api)return;if(!J.api.fields)return;if(i(J.api.fields)){let X=i(J.body)?J.body:{},G={};for(let[Y,H]of Object.entries(J.api.fields)){let z=X[Y];if(z===void 0){let V=f(Y);if(X[V]!==void 0)z=X[V]}if(z===void 0&&H?.default!==void 0&&H?.default!==null)z=H.default;if(z!==void 0)G[Y]=z}J.body=G}let Z=oZ.validate(J.body,J.api.fields,J.api.required||[]);if(Z.code!==0){J.response=j$(J,Z.firstError||"\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25",1,null,Z.fieldErrors,"validator");return}}},P1=F9;a();class lZ{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 G=Z.trim();if(G===""||G==="null")return[];if(G.startsWith("[")&&G.endsWith("]"))try{Z=JSON.parse(G)}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 G of Z)X.push(this.assertApiPathname(G,`\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){j.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)j.warn("\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5931\u8D25")}catch($){j.error({err:$,msg:"\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5F02\u5E38"})}}async cacheMenus(){try{if(!(await this.db.tableExists("addon_admin_menu")).data){j.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)j.warn("\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5931\u8D25")}catch($){j.warn({err:$,msg:"\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5F02\u5E38"})}}async rebuildRoleApiPermissions(){try{if(!(await this.db.tableExists("addon_admin_role")).data){j.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 H of J.data.lists){if(!H?.code)continue;let z=this.assertApiPathList(H.apis,H.code);Z.set(H.code,z)}let X=Array.from(Z.keys());if(X.length===0){j.info("\u2705 \u6CA1\u6709\u9700\u8981\u7F13\u5B58\u7684\u89D2\u8272\u6743\u9650");return}let G=X.map((H)=>X0.roleApis(H));await this.redis.delBatch(G);let Y=[];for(let H of X){let z=Z.get(H)||[],V=Array.from(new Set(z)).sort();if(V.length>0)Y.push({key:X0.roleApis(H),members:V})}if(Y.length>0)await this.redis.saddBatch(Y)}catch($){throw j.error({err:$,msg:"\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((Y)=>this.assertApiPathname(Y,`refreshRoleApiPermissions: apiPaths \u5143\u7D20\uFF0CroleCode=${$}`)),X=X0.roleApis($);if(Z.length===0){await this.redis.del(X);return}let G=Array.from(new Set(Z));if(await this.redis.del(X),G.length>0)await this.redis.sadd(X,G)}async cacheAll(){await this.cacheApis(),await this.cacheMenus(),await this.rebuildRoleApiPermissions()}async getApis(){try{return await this.redis.getObject(X0.apisAll())||[]}catch($){return j.error({err:$,msg:"\u83B7\u53D6\u63A5\u53E3\u7F13\u5B58\u5931\u8D25"}),[]}}async getMenus(){try{return await this.redis.getObject(X0.menusAll())||[]}catch($){return j.error({err:$,msg:"\u83B7\u53D6\u83DC\u5355\u7F13\u5B58\u5931\u8D25"}),[]}}async getRolePermissions($){try{return await this.redis.smembers(X0.roleApis($))||[]}catch(J){return j.error({err:J,roleCode:$,msg:"\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 j.error({err:Z,roleCode:$,msg:"\u68C0\u67E5\u89D2\u8272\u6743\u9650\u5931\u8D25"}),!1}}async deleteRolePermissions($){try{if(await this.redis.del(X0.roleApis($))>0)return j.info(`\u2705 \u5DF2\u5220\u9664\u89D2\u8272 ${$} \u7684\u6743\u9650\u7F13\u5B58`),!0;return!1}catch(J){return j.error({err:J,roleCode:$,msg:"\u5220\u9664\u89D2\u8272\u6743\u9650\u7F13\u5B58\u5931\u8D25"}),!1}}}var R9={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 lZ({db:$.db,redis:$.redis})}},B1=R9;var I9={name:"cipher",enable:!0,deps:[],handler:()=>{return y$}},L1=I9;var q9={name:"config",enable:!0,deps:[],handler:($)=>{return $.config}},S1=q9;function kJ($,J=["id","pid","sort"]){if(!$||!Array.isArray($))return $;return $.map((Z)=>{let X={};for(let[G,Y]of Object.entries(Z))X[G]=Y;for(let[G,Y]of Object.entries(X)){if(Y===void 0||Y===null)continue;if((J.includes(G)||G.endsWith("Id")||G.endsWith("_id")||G.endsWith("At")||G.endsWith("_at"))&&typeof Y==="string"){let z=Number(Y);if(!isNaN(z))X[G]=z}}return X})}function rZ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function j9($){return Array.isArray($)}function T$($,J={}){let{pickKeys:Z,omitKeys:X,keepValues:G,excludeValues:Y,keepMap:H}=J,z=(V)=>{let O={},_=Object.keys(V);if(Z&&Z.length)_=_.filter((I)=>Z.includes(I));if(X&&X.length)_=_.filter((I)=>!X.includes(I));for(let I of _){let B=V[I];if(H&&I in H){if(Object.is(H[I],B)){O[I]=B;continue}}if(G&&G.length&&!G.includes(B))continue;if(Y&&Y.length&&Y.includes(B))continue;O[I]=B}return O};if(j9($))return $.map((V)=>rZ(V)?z(V):V).filter((V)=>{if(rZ(V))return Object.keys(V).length>0;return!0});if(rZ($))return z($);return $}n0();n0();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((z)=>z.length>0);if(Z.length===0)throw Error("tableRef \u4E0D\u80FD\u4E3A\u7A7A");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];if(typeof X!=="string"||X.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1A\u7F3A\u5C11\u8868\u540D (tableRef: ${J})`);let G=null;if(Z.length===2){let z=Z[1];if(typeof z!=="string"||z.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1A\u7F3A\u5C11 alias (tableRef: ${J})`);G=z}let Y=X.split(".");if(Y.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09 (tableRef: ${J})`);if(Y.length===2){let z=Y[0],V=Y[1];if(typeof z!=="string"||z.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Aschema \u4E3A\u7A7A (tableRef: ${J})`);if(typeof V!=="string"||V.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Atable \u4E3A\u7A7A (tableRef: ${J})`);return{schema:z,table:V,alias:G}}let H=Y[0];if(typeof H!=="string"||H.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Atable \u4E3A\u7A7A (tableRef: ${J})`);return{schema:null,table:H,alias:G}}static normalizeTableRef($){let J=h.parseTableRef($),Z=J.schema?f(J.schema):null,X=f(J.table),G=Z?`${Z}.${X}`:X;if(J.alias)G=`${G} ${J.alias}`;return G}static getJoinMainQualifier($){let J=h.parseTableRef($);if(J.alias)return J.alias;return f(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((G)=>{if(G.includes("(")||G.includes(" "))return G;return f(G)});if(X.type==="exclude"){let G=await Z($),Y=X.fields.map((z)=>f(z)),H=G.filter((z)=>!Y.includes(z));if(H.length===0)throw Error(`\u6392\u9664\u5B57\u6BB5\u540E\u6CA1\u6709\u5269\u4F59\u5B57\u6BB5\u53EF\u67E5\u8BE2\u3002\u8868: ${$}, \u6392\u9664: ${Y.join(", ")}`);return H}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((G)=>G.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
11
+ )`;if(await $.db.unsafe(_),$.dbDialect==="postgresql"){for(let S of GJ){let C=String(S.comment).replace(/'/g,"''"),T=X0($.dbDialect,S.name),E=`COMMENT ON COLUMN ${H}.${T} IS '${C}'`;await $.db.unsafe(E)}for(let[S,C]of Object.entries(Z)){let T=f(S),E=X0($.dbDialect,T),D=C.name&&C.name!=="null"?String(C.name):"",w=D.replace(/'/g,"''"),N=D?`'${w}'`:"NULL",p=`COMMENT ON COLUMN ${H}.${E} IS ${N}`;await $.db.unsafe(p)}}let I=[],B={};if($.dbDialect==="mysql")B=await bZ($,J);for(let S of G){let C=`idx_${S}`;if($.dbDialect==="mysql"&&B[C])continue;let T=LJ($.dbDialect,J,C,S,"create");I.push($.db.unsafe(T))}for(let[S,C]of Object.entries(Z)){let T=f(S);if(C.index===!0&&C.unique!==!0){let E=`idx_${T}`;if($.dbDialect==="mysql"&&B[E])continue;let D=LJ($.dbDialect,J,E,T,"create");I.push($.db.unsafe(D))}}if(I.length>0)await Promise.all(I)}async function CH($,J,Z){let G=await JY($,J),X=await bZ($,J),Y=!1,H=[],U=[],z=[],O=[];for(let[S,C]of Object.entries(Z)){let T=f(S);if(G[T]){let E=ZY($.dbDialect,G[T],C);if(E.length>0){for(let v of E){let b=dX[v.type]||"\u672A\u77E5";j.debug(` ~ \u4FEE\u6539 ${T} ${b}: ${v.current} -> ${v.expected}`)}if(ZJ(C.type)&&G[T].max&&typeof C.max==="number"){if(G[T].max>C.max)j.warn(`[\u8DF3\u8FC7\u5371\u9669\u53D8\u66F4] ${J}.${T} \u957F\u5EA6\u6536\u7F29 ${G[T].max} -> ${C.max} \u5DF2\u88AB\u8DF3\u8FC7\uFF08\u9700\u624B\u52A8\u5904\u7406\uFF09`)}let D=E.some((v)=>v.type==="datatype"),w=E.some((v)=>v.type==="length"),N=E.every((v)=>v.type==="default"),p=E.some((v)=>v.type==="default");if(D){let v=E.find((u0)=>u0.type==="datatype"),b=String(v?.current||"").toLowerCase(),o=CJ($.dbDialect)[C.type]?.toLowerCase()||"";if(!eX(b,o)){let u0=[`\u7981\u6B62\u5B57\u6BB5\u7C7B\u578B\u53D8\u66F4: ${J}.${T}`,`\u5F53\u524D\u7C7B\u578B: ${v?.current}`,`\u76EE\u6807\u7C7B\u578B: ${v?.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(`
12
+ `);throw Error(u0)}j.debug(`[\u517C\u5BB9\u7C7B\u578B\u53D8\u66F4] ${J}.${T} ${b} -> ${o}`)}if(p){let v=XJ(C.default??null,C.type),b=null;if(v!=="null")b=EJ(v,C.type).trim().replace(/^DEFAULT\s+/,"");if(b!==null&&b!==""){if($.dbDialect==="postgresql"){let r=X0($.dbDialect,T);z.push(`ALTER COLUMN ${r} SET DEFAULT ${b}`)}else if($.dbDialect==="mysql"&&N){if(C.type!=="text"){let r=X0($.dbDialect,T);z.push(`ALTER COLUMN ${r} SET DEFAULT ${b}`)}}}}if(!N){let v=!1;if(w&&ZJ(C.type)&&G[T].max&&typeof C.max==="number"){if(G[T].max>C.max)v=!0}if(!v)U.push(fZ($.dbDialect,S,C,!1))}Y=!0}}else H.push(fZ($.dbDialect,S,C,!0)),Y=!0}let _=GJ.filter((S)=>S.name!=="id").map((S)=>S.name);for(let S of _)if(!G[S]){let C=iX($.dbDialect,S);if(C)j.debug(` + \u65B0\u589E\u7CFB\u7EDF\u5B57\u6BB5 ${S}`),H.push(`ADD COLUMN ${C}`),Y=!0}for(let S of gZ){let C=`idx_${S}`;if((G[S]||_.includes(S))&&!X[C])O.push({action:"create",indexName:C,fieldName:S}),Y=!0}for(let[S,C]of Object.entries(Z)){let T=f(S),E=`idx_${T}`;if(C.index&&!C.unique&&!X[E])O.push({action:"create",indexName:E,fieldName:T}),Y=!0;else if(!C.index&&X[E]&&X[E].length===1)O.push({action:"drop",indexName:E,fieldName:T}),Y=!0}let I=[];if($.dbDialect==="postgresql"){let S=X0($.dbDialect,J);for(let[C,T]of Object.entries(Z)){let E=f(C),D=X0($.dbDialect,E);if(G[E]){let w=G[E].comment||"",N=T.name&&T.name!=="null"?String(T.name):"";if(N!==w){let p=N.replace(/'/g,"''");I.push(`COMMENT ON COLUMN ${S}.${D} IS ${N?`'${p}'`:"NULL"}`),Y=!0}}}}Y=H.length>0||U.length>0||z.length>0||O.length>0||I.length>0;let B={changed:Y,addClauses:H,modifyClauses:U,defaultClauses:z,indexActions:O,commentActions:I};if(B.changed)await SH($,J,Z,B);return B}var XY=($,J=Bun.nanoseconds())=>{let Z=(J-$)/1e6;if(Z<1000)return`${Z.toFixed(2)} \u6BEB\u79D2`;else return`${(Z/1000).toFixed(2)} \u79D2`};function YY($){let J=$||{},Z=J.BUN_WORKER_ID,G=J.PM2_INSTANCE_ID;if(Z!==void 0)return{role:Z===""?"primary":"worker",instanceId:Z||"0",env:"bun-cluster"};if(G!==void 0)return{role:G==="0"?"primary":"worker",instanceId:G,env:"pm2-cluster"};return{role:"primary",instanceId:null,env:"standalone"}}j$();j$();import{existsSync as wH,readdirSync as EH}from"fs";DZ();n0();var WY=()=>{let $=new Map,J=(Z,G,X)=>{if(!wH(Z))return;let Y=EH(Z,{withFileTypes:!0});for(let H of Y){if(H.name.startsWith("_"))continue;if(!IJ(Z,H))continue;let U=e$(Z,H.name),z={source:G,sourceName:X,name:H.name,camelName:A$(H.name),rootDir:U,fullPath:U};$.set(H.name,z)}};return J(m(d0,"node_modules","@befly-addon"),"addon","\u7EC4\u4EF6"),J(xX,"app","\u9879\u76EE"),Array.from($.values())};KJ();var TH={name:"auth",enable:!0,deps:["cors"],handler:async($,J)=>{let Z=J.req.headers.get("authorization");if(Z&&Z.startsWith("Bearer ")){let G=Z.substring(7);try{let X=await $.jwt.verify(G);J.user=X,$X(X.id,X.roleCode,X.nickname,X.roleType)}catch{J.user={}}}else J.user={}}},HY=TH;var NH={name:"cors",enable:!0,deps:[],handler:async($,J)=>{let Z=J.req,X=Object.assign({},{origin:"*",methods:"GET, POST, 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:{}),Y=jJ(Z,X);if(J.corsHeaders=Y,Z.method==="OPTIONS"){J.response=new Response(null,{status:204,headers:Y});return}}},QY=NH;var vH=":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",DH="[: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]["+vH+"]*",kH=new RegExp("^"+DH+"$");function TJ($,J){let Z=[],G=J.exec($);while(G){let X=[];X.startIndex=J.lastIndex-G[0].length;let Y=G.length;for(let H=0;H<Y;H++)X.push(G[H]);Z.push(X),G=J.exec($)}return Z}var b$=function($){let J=kH.exec($);return!(J===null||typeof J>"u")};function UY($){return typeof $<"u"}var yH={allowBooleanAttributes:!1,unpairedTags:[]};function MY($,J){J=Object.assign({},yH,J);let Z=[],G=!1,X=!1;if($[0]==="\uFEFF")$=$.substr(1);for(let Y=0;Y<$.length;Y++)if($[Y]==="<"&&$[Y+1]==="?"){if(Y+=2,Y=zY($,Y),Y.err)return Y}else if($[Y]==="<"){let H=Y;if(Y++,$[Y]==="!"){Y=OY($,Y);continue}else{let U=!1;if($[Y]==="/")U=!0,Y++;let z="";for(;Y<$.length&&$[Y]!==">"&&$[Y]!==" "&&$[Y]!=="\t"&&$[Y]!==`
13
+ `&&$[Y]!=="\r";Y++)z+=$[Y];if(z=z.trim(),z[z.length-1]==="/")z=z.substring(0,z.length-1),Y--;if(!uH(z)){let I;if(z.trim().length===0)I="Invalid space after '<'.";else I="Tag '"+z+"' is an invalid name.";return Y0("InvalidTag",I,s0($,Y))}let O=gH($,Y);if(O===!1)return Y0("InvalidAttr","Attributes for '"+z+"' have open quote.",s0($,Y));let _=O.value;if(Y=O.index,_[_.length-1]==="/"){let I=Y-_.length;_=_.substring(0,_.length-1);let B=KY(_,J);if(B===!0)G=!0;else return Y0(B.err.code,B.err.msg,s0($,I+B.err.line))}else if(U)if(!O.tagClosed)return Y0("InvalidTag","Closing tag '"+z+"' doesn't have proper closing.",s0($,Y));else if(_.trim().length>0)return Y0("InvalidTag","Closing tag '"+z+"' can't have attributes or invalid starting.",s0($,H));else if(Z.length===0)return Y0("InvalidTag","Closing tag '"+z+"' has not been opened.",s0($,H));else{let I=Z.pop();if(z!==I.tagName){let B=s0($,I.tagStartPos);return Y0("InvalidTag","Expected closing tag '"+I.tagName+"' (opened in line "+B.line+", col "+B.col+") instead of closing tag '"+z+"'.",s0($,H))}if(Z.length==0)X=!0}else{let I=KY(_,J);if(I!==!0)return Y0(I.err.code,I.err.msg,s0($,Y-_.length+I.err.line));if(X===!0)return Y0("InvalidXml","Multiple possible root nodes found.",s0($,Y));else if(J.unpairedTags.indexOf(z)!==-1);else Z.push({tagName:z,tagStartPos:H});G=!0}for(Y++;Y<$.length;Y++)if($[Y]==="<")if($[Y+1]==="!"){Y++,Y=OY($,Y);continue}else if($[Y+1]==="?"){if(Y=zY($,++Y),Y.err)return Y}else break;else if($[Y]==="&"){let I=cH($,Y);if(I==-1)return Y0("InvalidChar","char '&' is not expected.",s0($,Y));Y=I}else if(X===!0&&!VY($[Y]))return Y0("InvalidXml","Extra text at the end",s0($,Y));if($[Y]==="<")Y--}}else{if(VY($[Y]))continue;return Y0("InvalidChar","char '"+$[Y]+"' is not expected.",s0($,Y))}if(!G)return Y0("InvalidXml","Start tag expected.",1);else if(Z.length==1)return Y0("InvalidTag","Unclosed tag '"+Z[0].tagName+"'.",s0($,Z[0].tagStartPos));else if(Z.length>0)return Y0("InvalidXml","Invalid '"+JSON.stringify(Z.map((Y)=>Y.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function VY($){return $===" "||$==="\t"||$===`
14
+ `||$==="\r"}function zY($,J){let Z=J;for(;J<$.length;J++)if($[J]=="?"||$[J]==" "){let G=$.substr(Z,J-Z);if(J>5&&G==="xml")return Y0("InvalidXml","XML declaration allowed only at the start of the document.",s0($,J));else if($[J]=="?"&&$[J+1]==">"){J++;break}else continue}return J}function OY($,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 xH='"',fH="'";function gH($,J){let Z="",G="",X=!1;for(;J<$.length;J++){if($[J]===xH||$[J]===fH)if(G==="")G=$[J];else if(G!==$[J]);else G="";else if($[J]===">"){if(G===""){X=!0;break}}Z+=$[J]}if(G!=="")return!1;return{value:Z,index:J,tagClosed:X}}var hH=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function KY($,J){let Z=TJ($,hH),G={};for(let X=0;X<Z.length;X++){if(Z[X][1].length===0)return Y0("InvalidAttr","Attribute '"+Z[X][2]+"' has no space in starting.",YJ(Z[X]));else if(Z[X][3]!==void 0&&Z[X][4]===void 0)return Y0("InvalidAttr","Attribute '"+Z[X][2]+"' is without value.",YJ(Z[X]));else if(Z[X][3]===void 0&&!J.allowBooleanAttributes)return Y0("InvalidAttr","boolean attribute '"+Z[X][2]+"' is not allowed.",YJ(Z[X]));let Y=Z[X][2];if(!pH(Y))return Y0("InvalidAttr","Attribute '"+Y+"' is an invalid name.",YJ(Z[X]));if(!G.hasOwnProperty(Y))G[Y]=1;else return Y0("InvalidAttr","Attribute '"+Y+"' is repeated.",YJ(Z[X]))}return!0}function bH($,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 cH($,J){if(J++,$[J]===";")return-1;if($[J]==="#")return J++,bH($,J);let Z=0;for(;J<$.length;J++,Z++){if($[J].match(/\w/)&&Z<20)continue;if($[J]===";")break;return-1}return J}function Y0($,J,Z){return{err:{code:$,msg:J,line:Z.line||Z,col:Z.col}}}function pH($){return b$($)}function uH($){return b$($)}function s0($,J){let Z=$.substring(0,J).split(/\r?\n/);return{line:Z.length,col:Z[Z.length-1].length+1}}function YJ($){return $.startIndex+$[1].length}var nH={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},_Y=function($){return Object.assign({},nH,$)};var NJ;if(typeof Symbol!=="function")NJ="@@xmlMetadata";else NJ=Symbol("XML Node Metadata");class i0{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][NJ]={startIndex:J}}static getMetaDataSymbol(){return NJ}}class vJ{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 G=1,X=!1,Y=!1,H="";for(;J<$.length;J++)if($[J]==="<"&&!Y){if(X&&E$($,"!ENTITY",J)){J+=7;let U,z;if([U,z,J]=this.readEntityExp($,J+1,this.suppressValidationErr),z.indexOf("&")===-1)Z[U]={regx:RegExp(`&${U};`,"g"),val:z}}else if(X&&E$($,"!ELEMENT",J)){J+=8;let{index:U}=this.readElementExp($,J+1);J=U}else if(X&&E$($,"!ATTLIST",J))J+=8;else if(X&&E$($,"!NOTATION",J)){J+=9;let{index:U}=this.readNotationExp($,J+1,this.suppressValidationErr);J=U}else if(E$($,"!--",J))Y=!0;else throw Error("Invalid DOCTYPE");G++,H=""}else if($[J]===">"){if(Y){if($[J-1]==="-"&&$[J-2]==="-")Y=!1,G--}else G--;if(G===0)break}else if($[J]==="[")X=!0;else H+=$[J];if(G!==0)throw Error("Unclosed DOCTYPE")}else throw Error("Invalid Tag instead of DOCTYPE");return{entities:Z,i:J}}readEntityExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J])&&$[J]!=='"'&&$[J]!=="'")Z+=$[J],J++;if(WJ(Z),J=l0($,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 G="";return[J,G]=this.readIdentifierVal($,J,"entity"),J--,[Z,G,J]}readNotationExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;!this.suppressValidationErr&&WJ(Z),J=l0($,J);let G=$.substring(J,J+6).toUpperCase();if(!this.suppressValidationErr&&G!=="SYSTEM"&&G!=="PUBLIC")throw Error(`Expected SYSTEM or PUBLIC, found "${G}"`);J+=G.length,J=l0($,J);let X=null,Y=null;if(G==="PUBLIC"){if([J,X]=this.readIdentifierVal($,J,"publicIdentifier"),J=l0($,J),$[J]==='"'||$[J]==="'")[J,Y]=this.readIdentifierVal($,J,"systemIdentifier")}else if(G==="SYSTEM"){if([J,Y]=this.readIdentifierVal($,J,"systemIdentifier"),!this.suppressValidationErr&&!Y)throw Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:Z,publicIdentifier:X,systemIdentifier:Y,index:--J}}readIdentifierVal($,J,Z){let G="",X=$[J];if(X!=='"'&&X!=="'")throw Error(`Expected quoted string, found "${X}"`);J++;while(J<$.length&&$[J]!==X)G+=$[J],J++;if($[J]!==X)throw Error(`Unterminated ${Z} value`);return J++,[J,G]}readElementExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;if(!this.suppressValidationErr&&!b$(Z))throw Error(`Invalid element name: "${Z}"`);J=l0($,J);let G="";if($[J]==="E"&&E$($,"MPTY",J))J+=4;else if($[J]==="A"&&E$($,"NY",J))J+=2;else if($[J]==="("){J++;while(J<$.length&&$[J]!==")")G+=$[J],J++;if($[J]!==")")throw Error("Unterminated content model")}else if(!this.suppressValidationErr)throw Error(`Invalid Element Expression, found "${$[J]}"`);return{elementName:Z,contentModel:G.trim(),index:J}}readAttlistExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;WJ(Z),J=l0($,J);let G="";while(J<$.length&&!/\s/.test($[J]))G+=$[J],J++;if(!WJ(G))throw Error(`Invalid attribute name: "${G}"`);J=l0($,J);let X="";if($.substring(J,J+8).toUpperCase()==="NOTATION"){if(X="NOTATION",J+=8,J=l0($,J),$[J]!=="(")throw Error(`Expected '(', found "${$[J]}"`);J++;let H=[];while(J<$.length&&$[J]!==")"){let U="";while(J<$.length&&$[J]!=="|"&&$[J]!==")")U+=$[J],J++;if(U=U.trim(),!WJ(U))throw Error(`Invalid notation name: "${U}"`);if(H.push(U),$[J]==="|")J++,J=l0($,J)}if($[J]!==")")throw Error("Unterminated list of notations");J++,X+=" ("+H.join("|")+")"}else{while(J<$.length&&!/\s/.test($[J]))X+=$[J],J++;let H=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!H.includes(X.toUpperCase()))throw Error(`Invalid attribute type: "${X}"`)}J=l0($,J);let Y="";if($.substring(J,J+8).toUpperCase()==="#REQUIRED")Y="#REQUIRED",J+=8;else if($.substring(J,J+7).toUpperCase()==="#IMPLIED")Y="#IMPLIED",J+=7;else[J,Y]=this.readIdentifierVal($,J,"ATTLIST");return{elementName:Z,attributeName:G,attributeType:X,defaultValue:Y,index:J}}}var l0=($,J)=>{while(J<$.length&&/\s/.test($[J]))J++;return J};function E$($,J,Z){for(let G=0;G<J.length;G++)if(J[G]!==$[Z+G+1])return!1;return!0}function WJ($){if(b$($))return $;else throw Error(`Invalid entity name ${$}`)}var mH=/^[-+]?0x[a-fA-F0-9]+$/,dH=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,sH={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function cZ($,J={}){if(J=Object.assign({},sH,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&&mH.test(Z))return iH(Z,16);else if(Z.includes("e")||Z.includes("E"))return lH($,Z,J);else{let G=dH.exec(Z);if(G){let X=G[1]||"",Y=G[2],H=rH(G[3]),U=X?$[Y.length+1]===".":$[Y.length]===".";if(!J.leadingZeros&&(Y.length>1||Y.length===1&&!U))return $;else{let z=Number(Z),O=String(z);if(z===0)return z;if(O.search(/[eE]/)!==-1)if(J.eNotation)return z;else return $;else if(Z.indexOf(".")!==-1)if(O==="0")return z;else if(O===H)return z;else if(O===`${X}${H}`)return z;else return $;let _=Y?H:Z;if(Y)return _===O||X+_===O?z:$;else return _===O||_===X+O?z:$}}else return $}}var oH=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function lH($,J,Z){if(!Z.eNotation)return $;let G=J.match(oH);if(G){let X=G[1]||"",Y=G[3].indexOf("e")===-1?"E":"e",H=G[2],U=X?$[H.length+1]===Y:$[H.length]===Y;if(H.length>1&&U)return $;else if(H.length===1&&(G[3].startsWith(`.${Y}`)||G[3][0]===Y))return Number(J);else if(Z.leadingZeros&&!U)return J=(G[1]||"")+G[3],Number(J);else return $}else return $}function rH($){if($&&$.indexOf(".")!==-1){if($=$.replace(/0+$/,""),$===".")$="0";else if($[0]===".")$="0"+$;else if($[$.length-1]===".")$=$.substring(0,$.length-1);return $}return $}function iH($,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 pZ($){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 DJ{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=tH,this.parseXml=ZQ,this.parseTextData=aH,this.resolveNameSpace=eH,this.buildAttributesMap=JQ,this.isItStopNode=WQ,this.replaceEntitiesValue=XQ,this.readStopNodeData=QQ,this.saveTextToParentTag=YQ,this.addChild=GQ,this.ignoreAttributesFn=pZ(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 tH($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let G=J[Z];this.lastEntities[G]={regex:new RegExp("&"+G+";","g"),val:$[G]}}}function aH($,J,Z,G,X,Y,H){if($!==void 0){if(this.options.trimValues&&!G)$=$.trim();if($.length>0){if(!H)$=this.replaceEntitiesValue($);let U=this.options.tagValueProcessor(J,$,Z,X,Y);if(U===null||U===void 0)return $;else if(typeof U!==typeof $||U!==$)return U;else if(this.options.trimValues)return nZ($,this.options.parseTagValue,this.options.numberParseOptions);else if($.trim()===$)return nZ($,this.options.parseTagValue,this.options.numberParseOptions);else return $}}}function eH($){if(this.options.removeNSPrefix){let J=$.split(":"),Z=$.charAt(0)==="/"?"/":"";if(J[0]==="xmlns")return"";if(J.length===2)$=Z+J[1]}return $}var $Q=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function JQ($,J){if(this.options.ignoreAttributes!==!0&&typeof $==="string"){let Z=TJ($,$Q),G=Z.length,X={};for(let Y=0;Y<G;Y++){let H=this.resolveNameSpace(Z[Y][1]);if(this.ignoreAttributesFn(H,J))continue;let U=Z[Y][4],z=this.options.attributeNamePrefix+H;if(H.length){if(this.options.transformAttributeName)z=this.options.transformAttributeName(z);if(z==="__proto__")z="#__proto__";if(U!==void 0){if(this.options.trimValues)U=U.trim();U=this.replaceEntitiesValue(U);let O=this.options.attributeValueProcessor(H,U,J);if(O===null||O===void 0)X[z]=U;else if(typeof O!==typeof U||O!==U)X[z]=O;else X[z]=nZ(U,this.options.parseAttributeValue,this.options.numberParseOptions)}else if(this.options.allowBooleanAttributes)X[z]=!0}}if(!Object.keys(X).length)return;if(this.options.attributesGroupName){let Y={};return Y[this.options.attributesGroupName]=X,Y}return X}}var ZQ=function($){$=$.replace(/\r\n?/g,`
15
+ `);let J=new i0("!xml"),Z=J,G="",X="",Y=new vJ(this.options.processEntities);for(let H=0;H<$.length;H++)if($[H]==="<")if($[H+1]==="/"){let z=T$($,">",H,"Closing Tag is not closed."),O=$.substring(H+2,z).trim();if(this.options.removeNSPrefix){let B=O.indexOf(":");if(B!==-1)O=O.substr(B+1)}if(this.options.transformTagName)O=this.options.transformTagName(O);if(Z)G=this.saveTextToParentTag(G,Z,X);let _=X.substring(X.lastIndexOf(".")+1);if(O&&this.options.unpairedTags.indexOf(O)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${O}>`);let I=0;if(_&&this.options.unpairedTags.indexOf(_)!==-1)I=X.lastIndexOf(".",X.lastIndexOf(".")-1),this.tagsNodeStack.pop();else I=X.lastIndexOf(".");X=X.substring(0,I),Z=this.tagsNodeStack.pop(),G="",H=z}else if($[H+1]==="?"){let z=uZ($,H,!1,"?>");if(!z)throw Error("Pi Tag is not closed.");if(G=this.saveTextToParentTag(G,Z,X),this.options.ignoreDeclaration&&z.tagName==="?xml"||this.options.ignorePiTags);else{let O=new i0(z.tagName);if(O.add(this.options.textNodeName,""),z.tagName!==z.tagExp&&z.attrExpPresent)O[":@"]=this.buildAttributesMap(z.tagExp,X);this.addChild(Z,O,X,H)}H=z.closeIndex+1}else if($.substr(H+1,3)==="!--"){let z=T$($,"-->",H+4,"Comment is not closed.");if(this.options.commentPropName){let O=$.substring(H+4,z-2);G=this.saveTextToParentTag(G,Z,X),Z.add(this.options.commentPropName,[{[this.options.textNodeName]:O}])}H=z}else if($.substr(H+1,2)==="!D"){let z=Y.readDocType($,H);this.docTypeEntities=z.entities,H=z.i}else if($.substr(H+1,2)==="!["){let z=T$($,"]]>",H,"CDATA is not closed.")-2,O=$.substring(H+9,z);G=this.saveTextToParentTag(G,Z,X);let _=this.parseTextData(O,Z.tagname,X,!0,!1,!0,!0);if(_==null)_="";if(this.options.cdataPropName)Z.add(this.options.cdataPropName,[{[this.options.textNodeName]:O}]);else Z.add(this.options.textNodeName,_);H=z+2}else{let z=uZ($,H,this.options.removeNSPrefix),O=z.tagName,_=z.rawTagName,I=z.tagExp,B=z.attrExpPresent,S=z.closeIndex;if(this.options.transformTagName){let E=this.options.transformTagName(O);if(I===O)I=E;O=E}if(Z&&G){if(Z.tagname!=="!xml")G=this.saveTextToParentTag(G,Z,X,!1)}let C=Z;if(C&&this.options.unpairedTags.indexOf(C.tagname)!==-1)Z=this.tagsNodeStack.pop(),X=X.substring(0,X.lastIndexOf("."));if(O!==J.tagname)X+=X?"."+O:O;let T=H;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,X,O)){let E="";if(I.length>0&&I.lastIndexOf("/")===I.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),X=X.substr(0,X.length-1),I=O;else I=I.substr(0,I.length-1);H=z.closeIndex}else if(this.options.unpairedTags.indexOf(O)!==-1)H=z.closeIndex;else{let w=this.readStopNodeData($,_,S+1);if(!w)throw Error(`Unexpected end of ${_}`);H=w.i,E=w.tagContent}let D=new i0(O);if(O!==I&&B)D[":@"]=this.buildAttributesMap(I,X);if(E)E=this.parseTextData(E,O,X,!0,B,!0,!0);X=X.substr(0,X.lastIndexOf(".")),D.add(this.options.textNodeName,E),this.addChild(Z,D,X,T)}else{if(I.length>0&&I.lastIndexOf("/")===I.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),X=X.substr(0,X.length-1),I=O;else I=I.substr(0,I.length-1);if(this.options.transformTagName){let D=this.options.transformTagName(O);if(I===O)I=D;O=D}let E=new i0(O);if(O!==I&&B)E[":@"]=this.buildAttributesMap(I,X);this.addChild(Z,E,X,T),X=X.substr(0,X.lastIndexOf("."))}else{let E=new i0(O);if(this.tagsNodeStack.push(Z),O!==I&&B)E[":@"]=this.buildAttributesMap(I,X);this.addChild(Z,E,X,T),Z=E}G="",H=S}}else G+=$[H];return J.child};function GQ($,J,Z,G){if(!this.options.captureMetaData)G=void 0;let X=this.options.updateTag(J.tagname,Z,J[":@"]);if(X===!1);else if(typeof X==="string")J.tagname=X,$.addChild(J,G);else $.addChild(J,G)}var XQ=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 YQ($,J,Z,G){if($){if(G===void 0)G=J.child.length===0;if($=this.parseTextData($,J.tagname,Z,!1,J[":@"]?Object.keys(J[":@"]).length!==0:!1,G),$!==void 0&&$!=="")J.add(this.options.textNodeName,$);$=""}return $}function WQ($,J,Z,G){if(J&&J.has(G))return!0;if($&&$.has(Z))return!0;return!1}function HQ($,J,Z=">"){let G,X="";for(let Y=J;Y<$.length;Y++){let H=$[Y];if(G){if(H===G)G=""}else if(H==='"'||H==="'")G=H;else if(H===Z[0])if(Z[1]){if($[Y+1]===Z[1])return{data:X,index:Y}}else return{data:X,index:Y};else if(H==="\t")H=" ";X+=H}}function T$($,J,Z,G){let X=$.indexOf(J,Z);if(X===-1)throw Error(G);else return X+J.length-1}function uZ($,J,Z,G=">"){let X=HQ($,J+1,G);if(!X)return;let{data:Y,index:H}=X,U=Y.search(/\s/),z=Y,O=!0;if(U!==-1)z=Y.substring(0,U),Y=Y.substring(U+1).trimStart();let _=z;if(Z){let I=z.indexOf(":");if(I!==-1)z=z.substr(I+1),O=z!==X.data.substr(I+1)}return{tagName:z,tagExp:Y,closeIndex:H,attrExpPresent:O,rawTagName:_}}function QQ($,J,Z){let G=Z,X=1;for(;Z<$.length;Z++)if($[Z]==="<")if($[Z+1]==="/"){let Y=T$($,">",Z,`${J} is not closed`);if($.substring(Z+2,Y).trim()===J){if(X--,X===0)return{tagContent:$.substring(G,Z),i:Y}}Z=Y}else if($[Z+1]==="?")Z=T$($,"?>",Z+1,"StopNode is not closed.");else if($.substr(Z+1,3)==="!--")Z=T$($,"-->",Z+3,"StopNode is not closed.");else if($.substr(Z+1,2)==="![")Z=T$($,"]]>",Z,"StopNode is not closed.")-2;else{let Y=uZ($,Z,">");if(Y){if((Y&&Y.tagName)===J&&Y.tagExp[Y.tagExp.length-1]!=="/")X++;Z=Y.closeIndex}}}function nZ($,J,Z){if(J&&typeof $==="string"){let G=$.trim();if(G==="true")return!0;else if(G==="false")return!1;else return cZ($,Z)}else if(UY($))return $;else return""}var mZ=i0.getMetaDataSymbol();function dZ($,J){return AY($,J)}function AY($,J,Z){let G,X={};for(let Y=0;Y<$.length;Y++){let H=$[Y],U=UQ(H),z="";if(Z===void 0)z=U;else z=Z+"."+U;if(U===J.textNodeName)if(G===void 0)G=H[U];else G+=""+H[U];else if(U===void 0)continue;else if(H[U]){let O=AY(H[U],J,z),_=zQ(O,J);if(H[mZ]!==void 0)O[mZ]=H[mZ];if(H[":@"])VQ(O,H[":@"],z,J);else if(Object.keys(O).length===1&&O[J.textNodeName]!==void 0&&!J.alwaysCreateTextNode)O=O[J.textNodeName];else if(Object.keys(O).length===0)if(J.alwaysCreateTextNode)O[J.textNodeName]="";else O="";if(X[U]!==void 0&&X.hasOwnProperty(U)){if(!Array.isArray(X[U]))X[U]=[X[U]];X[U].push(O)}else if(J.isArray(U,z,_))X[U]=[O];else X[U]=O}}if(typeof G==="string"){if(G.length>0)X[J.textNodeName]=G}else if(G!==void 0)X[J.textNodeName]=G;return X}function UQ($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let G=J[Z];if(G!==":@")return G}}function VQ($,J,Z,G){if(J){let X=Object.keys(J),Y=X.length;for(let H=0;H<Y;H++){let U=X[H];if(G.isArray(U,Z+"."+U,!0,!0))$[U]=[J[U]];else $[U]=J[U]}}}function zQ($,J){let{textNodeName:Z}=J,G=Object.keys($).length;if(G===0)return!0;if(G===1&&($[Z]||typeof $[Z]==="boolean"||$[Z]===0))return!0;return!1}class HJ{constructor($){this.externalEntities={},this.options=_Y($)}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 X=MY($,J);if(X!==!0)throw Error(`${X.err.msg}:${X.err.line}:${X.err.col}`)}let Z=new DJ(this.options);Z.addExternalEntities(this.externalEntities);let G=Z.parseXml($);if(this.options.preserveOrder||G===void 0)return G;else return dZ(G,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 '&#xD;'");else if(J==="&")throw Error("An entity with value '&' is not permitted");else this.externalEntities[$]=J}static getMetaDataSymbol(){return i0.getMetaDataSymbol()}}var OQ=new HJ,KQ={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),G=Object.fromEntries(Z.searchParams);J.body=G}else if(J.req.method==="POST"){let Z=J.req.headers.get("content-type")||"",G=new URL(J.req.url),X=Object.fromEntries(G.searchParams);try{if(Z.includes("application/json")){let Y=await J.req.json(),H={...X,...Y};J.body=H}else if(Z.includes("application/xml")||Z.includes("text/xml")){let Y=await J.req.text(),H=OQ.parse(Y),U=Object.keys(H)[0],z=U&&typeof H[U]==="object"?H[U]:H,O={...X,...z};J.body=O}else{J.response=P$(J,"\u65E0\u6548\u7684\u8BF7\u6C42\u53C2\u6570\u683C\u5F0F",1,null,{location:"content-type",value:Z},"parser");return}}catch{J.response=P$(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}}}},FY=KQ;a();var MQ={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=P$(J,"\u672A\u767B\u5F55",1,null,null,"auth");return}if(J.user.roleCode==="dev")return;let Z=J.route,G=J.user.roleCode,X=!1;if(G&&$.redis)try{let Y=G0.roleApis(G);X=await $.redis.sismember(Y,Z)}catch(Y){j.error({event:"hook_permission_redis_error",apiPath:Z,roleCode:G,err:Y,msg:"hook permission redis error"}),X=!1}if(!X){let Y=typeof J.api.name==="string"&&J.api.name.length>0?J.api.name:null,H=typeof Z==="string"&&Z.length>0?Z:null,U=Y?Y:H?H:"\u672A\u77E5\u63A5\u53E3";J.response=P$(J,`\u65E0\u6743\u8BBF\u95EE ${U} \u63A5\u53E3`,1,null,{apiLabel:U},"permission");return}}},RY=MQ;var sZ={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:".+"},IY=new Map;function _Q($){if($.startsWith("@")){let J=$.slice(1);return sZ[J]||$}return $}function qY($,J){let Z=_Q($),G=`${Z}:${J||""}`,X=IY.get(G);if(!X)X=new RegExp(Z,J),IY.set(G,X);return X}class oZ{static validate($,J,Z=[]){let G={};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 X of Z){let Y=$[X];if(Y===void 0||Y===null){let H=J[X]?.name||X;G[X]=`${H}\u4E3A\u5FC5\u586B\u9879`}}for(let[X,Y]of Object.entries(J)){if(G[X])continue;if($[X]===void 0&&!Z.includes(X))continue;let H=this.checkField($[X],Y,X);if(H)G[X]=H}return this.buildResult(G)}static single($,J){let Z=W$(J),G=Z.type,X=Z.default;if($===void 0||$===null||$==="")return{value:this.defaultFor(G,X),error:null};let Y=this.convert($,G);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($),G=J.length>0;return{code:G?1:0,failed:G,firstError:G?J[0]??null:null,errors:J,errorFields:Z,fieldErrors:$}}static checkField($,J,Z){let G=J.name||Z,X=this.convert($,J.type);if(X.error)return`${G}${X.error}`;let Y=this.checkRule(X.value,J);return Y?`${G}${Y}`: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 Z=W$(J),G=Z.type,X=Z.min,Y=Z.max,H=Z.regexp,U=this.resolveRegex(H);switch(G.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(U&&!this.testRegex(U,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(U&&!this.testRegex(U,$))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(U){for(let z of $)if(!this.testRegex(U,String(z)))return"\u5143\u7D20\u683C\u5F0F\u4E0D\u6B63\u786E"}break}return null}static resolveRegex($){if(!$)return null;if($.startsWith("@")){let J=$.substring(1);return sZ[J]||$}return $}static testRegex($,J){try{return qY($).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""}}}n0();var AQ={name:"validator",enable:!0,deps:["parser"],handler:async($,J)=>{if(!J.api)return;if(!J.api.fields)return;if(i(J.api.fields)){let G=i(J.body)?J.body:{},X={};for(let[Y,H]of Object.entries(J.api.fields)){let U=W$(H),z=G[Y];if(z===void 0){let O=f(Y);if(G[O]!==void 0)z=G[O]}if(z===void 0&&U.default!==null)z=U.default;if(z!==void 0)X[Y]=z}J.body=X}let Z=oZ.validate(J.body,J.api.fields,J.api.required||[]);if(Z.code!==0){J.response=P$(J,Z.firstError||"\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25",1,null,Z.fieldErrors,"validator");return}}},jY=AQ;a();class lZ{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 X=Z.trim();if(X===""||X==="null")return[];if(X.startsWith("[")&&X.endsWith("]"))try{Z=JSON.parse(X)}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 G=[];for(let X of Z)G.push(this.assertApiPathname(X,`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5143\u7D20\uFF0CroleCode=${J}`));return G}async cacheApis(){try{if(!(await this.db.tableExists("addon_admin_api")).data){j.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(G0.apisAll(),J.data.lists)===null)j.warn("\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5931\u8D25")}catch($){j.error({err:$,msg:"\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5F02\u5E38"})}}async cacheMenus(){try{if(!(await this.db.tableExists("addon_admin_menu")).data){j.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(G0.menusAll(),J.data.lists)===null)j.warn("\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5931\u8D25")}catch($){j.warn({err:$,msg:"\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5F02\u5E38"})}}async rebuildRoleApiPermissions(){try{if(!(await this.db.tableExists("addon_admin_role")).data){j.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 H of J.data.lists){if(!H?.code)continue;let U=this.assertApiPathList(H.apis,H.code);Z.set(H.code,U)}let G=Array.from(Z.keys());if(G.length===0){j.info("\u2705 \u6CA1\u6709\u9700\u8981\u7F13\u5B58\u7684\u89D2\u8272\u6743\u9650");return}let X=G.map((H)=>G0.roleApis(H));await this.redis.delBatch(X);let Y=[];for(let H of G){let U=Z.get(H)||[],z=Array.from(new Set(U)).sort();if(z.length>0)Y.push({key:G0.roleApis(H),members:z})}if(Y.length>0)await this.redis.saddBatch(Y)}catch($){throw j.error({err:$,msg:"\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((Y)=>this.assertApiPathname(Y,`refreshRoleApiPermissions: apiPaths \u5143\u7D20\uFF0CroleCode=${$}`)),G=G0.roleApis($);if(Z.length===0){await this.redis.del(G);return}let X=Array.from(new Set(Z));if(await this.redis.del(G),X.length>0)await this.redis.sadd(G,X)}async cacheAll(){await this.cacheApis(),await this.cacheMenus(),await this.rebuildRoleApiPermissions()}async getApis(){try{return await this.redis.getObject(G0.apisAll())||[]}catch($){return j.error({err:$,msg:"\u83B7\u53D6\u63A5\u53E3\u7F13\u5B58\u5931\u8D25"}),[]}}async getMenus(){try{return await this.redis.getObject(G0.menusAll())||[]}catch($){return j.error({err:$,msg:"\u83B7\u53D6\u83DC\u5355\u7F13\u5B58\u5931\u8D25"}),[]}}async getRolePermissions($){try{return await this.redis.smembers(G0.roleApis($))||[]}catch(J){return j.error({err:J,roleCode:$,msg:"\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(G0.roleApis($),Z)}catch(Z){return j.error({err:Z,roleCode:$,msg:"\u68C0\u67E5\u89D2\u8272\u6743\u9650\u5931\u8D25"}),!1}}async deleteRolePermissions($){try{if(await this.redis.del(G0.roleApis($))>0)return j.info(`\u2705 \u5DF2\u5220\u9664\u89D2\u8272 ${$} \u7684\u6743\u9650\u7F13\u5B58`),!0;return!1}catch(J){return j.error({err:J,roleCode:$,msg:"\u5220\u9664\u89D2\u8272\u6743\u9650\u7F13\u5B58\u5931\u8D25"}),!1}}}var FQ={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 lZ({db:$.db,redis:$.redis})}},PY=FQ;var RQ={name:"cipher",enable:!0,deps:[],handler:()=>{return f$}},BY=RQ;var IQ={name:"config",enable:!0,deps:[],handler:($)=>{return $.config}},LY=IQ;function kJ($,J=["id","pid","sort"]){if(!$||!Array.isArray($))return $;return $.map((Z)=>{let G={};for(let[X,Y]of Object.entries(Z))G[X]=Y;for(let[X,Y]of Object.entries(G)){if(Y===void 0||Y===null)continue;if((J.includes(X)||X.endsWith("Id")||X.endsWith("_id")||X.endsWith("At")||X.endsWith("_at"))&&typeof Y==="string"){let U=Number(Y);if(!isNaN(U))G[X]=U}}return G})}function rZ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function qQ($){return Array.isArray($)}function N$($,J={}){let{pickKeys:Z,omitKeys:G,keepValues:X,excludeValues:Y,keepMap:H}=J,U=(z)=>{let O={},_=Object.keys(z);if(Z&&Z.length)_=_.filter((I)=>Z.includes(I));if(G&&G.length)_=_.filter((I)=>!G.includes(I));for(let I of _){let B=z[I];if(H&&I in H){if(Object.is(H[I],B)){O[I]=B;continue}}if(X&&X.length&&!X.includes(B))continue;if(Y&&Y.length&&Y.includes(B))continue;O[I]=B}return O};if(qQ($))return $.map((z)=>rZ(z)?U(z):z).filter((z)=>{if(rZ(z))return Object.keys(z).length>0;return!0});if(rZ($))return U($);return $}n0();n0();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((U)=>U.length>0);if(Z.length===0)throw Error("tableRef \u4E0D\u80FD\u4E3A\u7A7A");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 G=Z[0];if(typeof G!=="string"||G.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1A\u7F3A\u5C11\u8868\u540D (tableRef: ${J})`);let X=null;if(Z.length===2){let U=Z[1];if(typeof U!=="string"||U.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1A\u7F3A\u5C11 alias (tableRef: ${J})`);X=U}let Y=G.split(".");if(Y.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09 (tableRef: ${J})`);if(Y.length===2){let U=Y[0],z=Y[1];if(typeof U!=="string"||U.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Aschema \u4E3A\u7A7A (tableRef: ${J})`);if(typeof z!=="string"||z.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Atable \u4E3A\u7A7A (tableRef: ${J})`);return{schema:U,table:z,alias:X}}let H=Y[0];if(typeof H!=="string"||H.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Atable \u4E3A\u7A7A (tableRef: ${J})`);return{schema:null,table:H,alias:X}}static normalizeTableRef($){let J=h.parseTableRef($),Z=J.schema?f(J.schema):null,G=f(J.table),X=Z?`${Z}.${G}`:G;if(J.alias)X=`${X} ${J.alias}`;return X}static getJoinMainQualifier($){let J=h.parseTableRef($);if(J.alias)return J.alias;return f(J.table)}static async fieldsToSnake($,J,Z){if(!J||!Array.isArray(J))return["*"];let G=h.validateAndClassifyFields(J);if(G.type==="all")return["*"];if(G.type==="include")return G.fields.map((X)=>{if(X.includes("(")||X.includes(" "))return X;return f(X)});if(G.type==="exclude"){let X=await Z($),Y=G.fields.map((U)=>f(U)),H=X.filter((U)=>!Y.includes(U));if(H.length===0)throw Error(`\u6392\u9664\u5B57\u6BB5\u540E\u6CA1\u6709\u5269\u4F59\u5B57\u6BB5\u53EF\u67E5\u8BE2\u3002\u8868: ${$}, \u6392\u9664: ${Y.join(", ")}`);return H}return["*"]}static validateAndClassifyFields($){if(!$||$.length===0)return{type:"all",fields:[]};if($.some((G)=>G==="*"))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((G)=>!G||typeof G!=="string"||G.trim()===""))throw Error("fields \u4E0D\u80FD\u5305\u542B\u7A7A\u5B57\u7B26\u4E32\u6216\u65E0\u6548\u503C");let J=$.filter((G)=>!G.startsWith("!")),Z=$.filter((G)=>G.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((X)=>X.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
16
16
  1. \u7A7A\u6570\u7EC4 [] \u6216\u4E0D\u4F20\uFF08\u67E5\u8BE2\u6240\u6709\uFF09
17
17
  2. \u5168\u90E8\u6307\u5B9A\u5B57\u6BB5 ["id", "name"]
18
- 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=J.split("#");if(Z.length!==2)return J;let X=Z[0],G=Z[1];if(typeof X!=="string"||typeof G!=="string")return J;return`${f(X.trim())}#${G.trim()}`})}static processJoinField($){if($.includes("(")||$==="*"||$.startsWith("`"))return $;if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i),Z=J[0],X=J[1];if(typeof Z!=="string"||typeof X!=="string")return $;return`${h.processJoinField(Z.trim())} AS ${X.trim()}`}if($.includes(".")){let J=$.split(".");if(J.length<2)return f($);if(J.some((G)=>G.trim()===""))return $;let Z=J[J.length-1],X=J.slice(0,J.length-1).join(".");if(typeof Z!=="string"||typeof X!=="string")return f($);return`${X.trim()}.${f(Z)}`}return f($)}static processJoinWhereKey($){if($==="$or"||$==="$and")return $;if($.includes("$")){let J=$.lastIndexOf("$"),Z=$.substring(0,J),X=$.substring(J);if(Z.includes(".")){let G=Z.split(".");if(G.length<2)return`${f(Z)}${X}`;if(G.some((z)=>z.trim()===""))return`${f(Z)}${X}`;let Y=G[G.length-1],H=G.slice(0,G.length-1).join(".");if(typeof Y!=="string"||typeof H!=="string")return`${f(Z)}${X}`;return`${H.trim()}.${f(Y)}${X}`}return`${f(Z)}${X}`}if($.includes(".")){let J=$.split(".");if(J.length<2)return f($);if(J.some((G)=>G.trim()===""))return f($);let Z=J[J.length-1],X=J.slice(0,J.length-1).join(".");if(typeof Z!=="string"||typeof X!=="string")return f($);return`${X.trim()}.${f(Z)}`}return f($)}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 G=h.processJoinWhereKey(Z);if(Z==="$or"||Z==="$and")J[G]=X.map((Y)=>h.processJoinWhere(Y));else if(typeof X==="object"&&X!==null&&!Array.isArray(X))J[G]=h.processJoinWhere(X);else J[G]=X}return J}static processJoinOrderBy($){if(!$||!Array.isArray($))return $;return $.map((J)=>{if(typeof J!=="string"||!J.includes("#"))return J;let Z=J.split("#");if(Z.length!==2)return J;let X=Z[0],G=Z[1];if(typeof X!=="string"||typeof G!=="string")return J;return`${h.processJoinField(X.trim())}#${G.trim()}`})}static addDefaultStateFilter($={},J,Z=!1){if(Object.keys($).some((Y)=>Y.startsWith("state")||Y.includes(".state")))return $;if(Z&&J){let Y={};for(let[H,z]of Object.entries($))Y[H]=z;return Y[`${J}.state$gt`]=0,Y}let G={};for(let[Y,H]of Object.entries($))G[Y]=H;return G.state$gt=0,G}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((Y)=>h.whereKeysToSnake(Y));continue}if(Z.includes("$")){let Y=Z.lastIndexOf("$"),H=Z.substring(0,Y),z=Z.substring(Y),V=f(H)+z;J[V]=X;continue}let G=f(Z);if(typeof X==="object"&&X!==null&&!Array.isArray(X))J[G]=h.whereKeysToSnake(X);else J[G]=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 G=JSON.parse(X);if(Array.isArray(G))J[Z]=G}catch{}}return J}static cleanAndSnakeAndSerializeWriteData($,J=[null,void 0]){let Z=T$($,{excludeValues:J}),X=oX(Z);return h.serializeArrayFields(X)}static stripSystemFieldsForWrite($,J){let Z={};for(let[X,G]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]=G}return Z}static buildInsertRow($){let J=h.cleanAndSnakeAndSerializeWriteData($.data),Z=h.stripSystemFieldsForWrite(J,{allowState:!1}),X={};for(let[G,Y]of Object.entries(Z))X[G]=Y;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[G,Y]of Object.entries(Z))X[G]=Y;return X.updated_at=$.now,X}static buildPartialUpdateData($){let J=h.cleanAndSnakeAndSerializeWriteData($.data);return h.stripSystemFieldsForWrite(J,{allowState:$.allowState})}}a();class W0{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(W0.startsWithQuote($)&&!W0.isQuotedIdentPaired($))throw Error(`${J} \u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (value: ${$})`)}static assertSafeIdentifierPart($,J){if(!W0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684 ${J} \u6807\u8BC6\u7B26: ${$}`)}static assertSafeAlias($){if(W0.isQuotedIdentPaired($))return;if(!W0.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 G=new Set(X);for(let Y=0;Y<$.length;Y++){let H=$[Y];if(!H||typeof H!=="object"||Array.isArray(H))throw Error(`\u6279\u91CF\u63D2\u5165\u7684\u6BCF\u4E00\u884C\u5FC5\u987B\u662F\u5BF9\u8C61 (table: ${J.table}, rowIndex: ${Y})`);let z=Object.keys(H);if(z.length!==X.length)throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${Y})`);for(let V of z)if(!G.has(V))throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${Y}, extraField: ${V})`);for(let V of X){if(!(V in H))throw Error(`\u6279\u91CF\u63D2\u5165\u7F3A\u5C11\u5B57\u6BB5 (table: ${J.table}, rowIndex: ${Y}, field: ${V})`);W0.assertNoUndefinedParam(H[V],`\u6279\u91CF\u63D2\u5165\u5B57\u6BB5\u503C (table: ${J.table}, rowIndex: ${Y}, field: ${V})`)}}return X}}var g={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: ${$})`,FIELD_INVALID:($)=>`\u5B57\u6BB5\u683C\u5F0F\u975E\u6CD5\uFF0C\u8BF7\u4F7F\u7528\u7B80\u5355\u5B57\u6BB5\u540D\u6216\u5B89\u5168\u5F15\u7528\uFF0C\u590D\u6742\u8868\u8FBE\u5F0F\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(g.QUOTE_IDENT_NEED_STRING(J));let Z=J.trim();if(!Z)throw Error(g.IDENT_EMPTY);return`\`${Z.replace(/`/g,"``")}\``}}_isQuotedIdent($){return W0.isQuotedIdentPaired($)}_startsWithQuote($){return W0.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(),W0.assertPairedQuotedIdentIfStartsWithQuote($,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),$==="*"||this._isQuotedIdent($))return $;try{W0.assertNoExprField($)}catch{throw Error(g.FIELD_EXPR_NOT_ALLOWED($))}if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i);if(J.length!==2)throw Error(g.FIELD_INVALID($));let Z=J[0],X=J[1];if(typeof Z!=="string"||typeof X!=="string")throw Error(g.FIELD_INVALID($));let G=Z.trim(),Y=X.trim();return W0.assertSafeAlias(Y),`${this._escapeField(G)} AS ${Y}`}if($.includes("."))return $.split(".").map((Z)=>{if(Z=Z.trim(),Z==="*"||this._isQuotedIdent(Z))return Z;return W0.assertPairedQuotedIdentIfStartsWithQuote(Z,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),this._quoteIdent(Z)}).join(".");return this._quoteIdent($)}_validateIdentifierPart($,J){W0.assertSafeIdentifierPart($,J)}_escapeTable($){if(typeof $!=="string")return $;if($=$.trim(),this._startsWithQuote($)&&!this._isQuotedIdent($));if(this._isQuotedIdent($))return $;let J=$.split(/\s+/).filter((V)=>V.length>0);if(J.length===0)throw Error(g.FROM_EMPTY);if(J.length>2)throw Error(g.TABLE_REF_TOO_MANY_PARTS($));let Z=J[0];if(typeof Z!=="string"||Z.trim()==="")throw Error(g.FROM_EMPTY);let X=Z.trim(),G=J.length===2?J[1]:null,Y=typeof G==="string"?G.trim():null,H=X.split(".");if(H.length>2)throw Error(g.TABLE_REF_SCHEMA_TOO_DEEP($));let z="";if(H.length===2){let V=H[0],O=H[1];if(typeof V!=="string"||typeof O!=="string")throw Error(g.TABLE_REF_SCHEMA_TOO_DEEP($));let _=V.trim(),I=O.trim(),B=this._isQuotedIdent(_)?_:(()=>{if(this._startsWithQuote(_)&&!this._isQuotedIdent(_))throw Error(g.SCHEMA_QUOTE_NOT_PAIRED(_));return this._validateIdentifierPart(_,"schema"),this._quoteIdent(_)})(),S=this._isQuotedIdent(I)?I:(()=>{if(this._startsWithQuote(I)&&!this._isQuotedIdent(I))throw Error(g.TABLE_QUOTE_NOT_PAIRED(I));return this._validateIdentifierPart(I,"table"),this._quoteIdent(I)})();z=`${B}.${S}`}else{let V=H[0];if(typeof V!=="string")throw Error(g.FROM_EMPTY);let O=V.trim();if(this._isQuotedIdent(O))z=O;else{if(this._startsWithQuote(O)&&!this._isQuotedIdent(O))throw Error(g.TABLE_QUOTE_NOT_PAIRED(O));this._validateIdentifierPart(O,"table"),z=this._quoteIdent(O)}}if(Y)return this._validateIdentifierPart(Y,"alias"),`${z} ${Y}`;return z}_validateParam($){W0.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 G=Z.map(()=>"?").join(",");this._where.push(`${X} IN (${G})`),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 Y=Z.map(()=>"?").join(",");this._where.push(`${X} NOT IN (${Y})`),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=[],G=[];if(Z.forEach((Y)=>{let H=new b$({quoteIdent:this._quoteIdent});if(H._processWhereConditions(Y),H._where.length>0)X.push(`(${H._where.join(" AND ")})`),G.push(...H._params)}),X.length>0)this._where.push(`(${X.join(" OR ")})`),this._params.push(...G)}}else if(J.includes("$")){let X=J.lastIndexOf("$"),G=J.substring(0,X),Y="$"+J.substring(X+1);this._applyOperator(G,Y,Z)}else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))for(let[X,G]of Object.entries(Z))this._applyOperator(J,X,G);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(g.SELECT_FIELDS_INVALID);return this}selectRaw($){if(typeof $!=="string"||!$.trim())throw Error(g.SELECT_RAW_NEED_NON_EMPTY($));return this._select.push($),this}from($){if(typeof $!=="string"||!$.trim())throw Error(g.FROM_NEED_NON_EMPTY($));return this._from=this._escapeTable($.trim()),this}fromRaw($){if(typeof $!=="string"||!$.trim())throw Error(g.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(g.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(g.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(g.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(g.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(g.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`INNER JOIN ${Z} ON ${J}`),this}orderBy($){if(!Array.isArray($))throw Error(g.ORDER_BY_NEED_ARRAY);return $.forEach((J)=>{if(typeof J!=="string"||!J.includes("#"))throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let Z=J.split("#");if(Z.length!==2)throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let X=Z[0],G=Z[1];if(typeof X!=="string"||typeof G!=="string")throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let Y=X.trim(),H=G.trim().toUpperCase();if(!Y)throw Error(g.ORDER_BY_FIELD_EMPTY(J));if(!["ASC","DESC"].includes(H))throw Error(g.ORDER_BY_DIR_INVALID(H));let z=this._escapeField(Y);this._orderBy.push(`${z} ${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(g.LIMIT_MUST_NON_NEGATIVE($));if(this._limit=Math.floor($),J!==void 0&&J!==null){if(typeof J!=="number"||J<0)throw Error(g.OFFSET_MUST_NON_NEGATIVE(J));this._offset=Math.floor(J)}return this}offset($){if(typeof $!=="number"||$<0)throw Error(g.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(g.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(g.INSERT_NEED_TABLE($));if(!J||typeof J!=="object")throw Error(g.INSERT_NEED_DATA($,J));let Z=this._escapeTable($);if(Array.isArray(J)){let X=W0.assertBatchInsertRowsConsistent(J,{table:$}),G=X.map((O)=>this._escapeField(O)),Y=X.map(()=>"?").join(", "),H=J.map(()=>`(${Y})`).join(", "),z=`INSERT INTO ${Z} (${G.join(", ")}) VALUES ${H}`,V=[];for(let O=0;O<J.length;O++){let _=J[O];for(let I of X){let B=_[I];this._validateParam(B),V.push(B)}}return{sql:z,params:V}}else{let X=Object.keys(J);if(X.length===0)throw Error(g.INSERT_NEED_AT_LEAST_ONE_FIELD($));for(let V of X)this._validateParam(J[V]);let G=X.map((V)=>this._escapeField(V)),Y=X.map(()=>"?").join(", "),H=`INSERT INTO ${Z} (${G.join(", ")}) VALUES (${Y})`,z=[];for(let V of X){let O=J[V];this._validateParam(O),z.push(O)}return{sql:H,params:z}}}toUpdateSql($,J){if(!$||typeof $!=="string")throw Error(g.UPDATE_NEED_TABLE);if(!J||typeof J!=="object"||Array.isArray(J))throw Error(g.UPDATE_NEED_OBJECT);let Z=Object.keys(J);if(Z.length===0)throw Error(g.UPDATE_NEED_AT_LEAST_ONE_FIELD);let X=this._escapeTable($),G=Z.map((z)=>`${this._escapeField(z)} = ?`),Y=[...Object.values(J),...this._params],H=`UPDATE ${X} SET ${G.join(", ")}`;if(this._where.length>0)H+=" WHERE "+this._where.join(" AND ");else throw Error(g.UPDATE_NEED_WHERE);return{sql:H,params:Y}}toDeleteSql($){if(!$||typeof $!=="string")throw Error(g.DELETE_NEED_TABLE);let Z=`DELETE FROM ${this._escapeTable($)}`;if(this._where.length>0)Z+=" WHERE "+this._where.join(" AND ");else throw Error(g.DELETE_NEED_WHERE);return{sql:Z,params:[...this._params]}}toCountSql(){let $="SELECT COUNT(*) as total";if(!this._from)throw Error(g.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(g.TO_DELETE_IN_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(g.TO_DELETE_IN_NEED_ID_FIELD($.idField));if(!Array.isArray($.ids))throw Error(g.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(g.TO_UPDATE_CASE_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(g.TO_UPDATE_CASE_NEED_ID_FIELD($.idField));if(!Array.isArray($.rows))throw Error(g.TO_UPDATE_CASE_NEED_ROWS);if($.rows.length===0)return{sql:"",params:[]};if(!Array.isArray($.fields))throw Error(g.TO_UPDATE_CASE_NEED_FIELDS);if($.fields.length===0)return{sql:"",params:[]};let J=$.rows.map((z)=>z.id),Z=J.map(()=>"?").join(","),X=[],G=[],Y=$.quoteIdent($.idField);for(let z of $.fields){let V=[];for(let _ of $.rows){if(!(z in _.data))continue;V.push("WHEN ? THEN ?"),G.push(_.id);let I=_.data[z];W0.assertNoUndefinedParam(I,"SQL \u53C2\u6570\u503C"),G.push(I)}if(V.length===0)continue;let O=$.quoteIdent(z);X.push(`${O} = CASE ${Y} ${V.join(" ")} ELSE ${O} END`)}X.push(`${$.quoteIdent($.updatedAtField)} = ?`),G.push($.updatedAtValue);for(let z of J)G.push(z);let H=`UPDATE ${$.quoteIdent($.table)} SET ${X.join(", ")} WHERE ${Y} IN (${Z})`;if($.stateGtZero&&$.stateField)H+=` AND ${$.quoteIdent($.stateField)} > 0`;return{sql:H,params:G}}}var P9=3600;class xJ{redis;dialect;sql=null;isTransaction=!1;constructor($){this.redis=$.redis,this.sql=$.sql||null,this.isTransaction=Boolean($.sql),this.dialect=$.dialect?$.dialect:new BJ}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($),Y=(await this.executeWithConn(X.sql,X.params)).data;if(!Y||Y.length===0)throw Error(`\u8868 ${$} \u4E0D\u5B58\u5728\u6216\u6CA1\u6709\u5B57\u6BB5`);let H=this.dialect.getTableColumnsFromResult(Y);if(await this.redis.setObject(J,H,P9)===null)j.warn({table:$,cacheKey:J,msg:"\u8868\u5B57\u6BB5\u7F13\u5B58\u5199\u5165 Redis \u5931\u8D25"});return H}async prepareQueryOptions($){let J=T$($.where||{},{excludeValues:[null,void 0]});if($.joins&&$.joins.length>0){let G=($.fields||[]).map((z)=>h.processJoinField(z)),Y=h.normalizeTableRef($.table),H=h.getJoinMainQualifier($.table);return{table:Y,tableQualifier:H,fields:G.length>0?G:["*"],where:h.processJoinWhere(J),joins:$.joins,orderBy:h.processJoinOrderBy($.orderBy||[]),page:$.page||1,limit:$.limit||10}}let X=await h.fieldsToSnake(f($.table),$.fields||[],this.getTableColumns.bind(this));return{table:f($.table),tableQualifier:f($.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 G;if(X.length>0)G=await this.sql.unsafe($,X);else G=await this.sql.unsafe($);let Y=Date.now()-Z;return{data:G,sql:{sql:$,params:X,duration:Y}}}catch(G){let Y=Date.now()-Z,H=Error(`SQL\u6267\u884C\u5931\u8D25: ${G.message}`);throw H.originalError=G,H.params=X,H.duration=Y,H.sqlInfo={sql:$,params:X,duration:Y},H}}async unsafe($,J){return await this.executeWithConn($,J)}async tableExists($){let J=f($),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:G}=await this.prepareQueryOptions($),Y=Array.isArray(X)&&X.length>0,H=this.createSqlBuilder().selectRaw("COUNT(*) as count").from(J).where(h.addDefaultStateFilter(Z,G,Y));this.applyJoins(H,X);let{sql:z,params:V}=H.toSelectSql(),O=await this.executeWithConn(z,V);return{data:O.data?.[0]?.count||0,sql:O.sql}}async getOne($){let{table:J,fields:Z,where:X,joins:G,tableQualifier:Y}=await this.prepareQueryOptions($),H=Array.isArray(G)&&G.length>0,z=this.createSqlBuilder().select(Z).from(J).where(h.addDefaultStateFilter(X,Y,H));this.applyJoins(z,G);let{sql:V,params:O}=z.toSelectSql(),_=await this.executeWithConn(V,O),B=_.data?.[0]||null;if(!B)return{data:null,sql:_.sql};let S=RZ(B),C=h.deserializeArrayFields(S);if(!C)return{data:null,sql:_.sql};return{data:kJ([C])[0]??C,sql:_.sql}}async getDetail($){return await this.getOne($)}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,Array.isArray(J.joins)&&J.joins.length>0),X=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(J.table).where(Z);this.applyJoins(X,J.joins);let{sql:G,params:Y}=X.toSelectSql(),H=await this.executeWithConn(G,Y),z=H.data?.[0]?.total||0;if(z===0)return{data:{lists:[],total:0,page:J.page,limit:J.limit,pages:0},sql:{count:H.sql}};let V=(J.page-1)*J.limit,O=this.createSqlBuilder().select(J.fields).from(J.table).where(Z).limit(J.limit).offset(V);if(this.applyJoins(O,J.joins),J.orderBy&&J.orderBy.length>0)O.orderBy(J.orderBy);let{sql:_,params:I}=O.toSelectSql(),B=await this.executeWithConn(_,I),S=B.data||[],T=IZ(S).map((E)=>h.deserializeArrayFields(E)).filter((E)=>E!==null);return{data:{lists:kJ(T),total:z,page:J.page,limit:J.limit,pages:Math.ceil(z/J.limit)},sql:{count:H.sql,data:B.sql}}}async getAll($){let X={table:$.table,page:1,limit:10};if($.fields!==void 0)X.fields=$.fields;if($.where!==void 0)X.where=$.where;if($.joins!==void 0)X.joins=$.joins;if($.orderBy!==void 0)X.orderBy=$.orderBy;let G=await this.prepareQueryOptions(X),Y=h.addDefaultStateFilter(G.where,G.tableQualifier,Array.isArray(G.joins)&&G.joins.length>0),H=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(G.table).where(Y);this.applyJoins(H,G.joins);let{sql:z,params:V}=H.toSelectSql(),O=await this.executeWithConn(z,V),_=O.data?.[0]?.total||0;if(_===0)return{data:{lists:[],total:0},sql:{count:O.sql}};let I=this.createSqlBuilder().select(G.fields).from(G.table).where(Y).limit(1e4);if(this.applyJoins(I,G.joins),G.orderBy&&G.orderBy.length>0)I.orderBy(G.orderBy);let{sql:B,params:S}=I.toSelectSql(),C=await this.executeWithConn(B,S),T=C.data||[];if(T.length>=1000)j.warn({table:$.table,count:T.length,total:_,msg:"getAll \u8FD4\u56DE\u6570\u636E\u8FC7\u591A\uFF0C\u5EFA\u8BAE\u4F7F\u7528 getList \u5206\u9875\u67E5\u8BE2"});if(T.length>=1e4)j.warn({table:$.table,limit:1e4,total:_,msg:`getAll \u8FBE\u5230\u6700\u5927\u9650\u5236 ${1e4}\uFF0C\u5B9E\u9645\u603B\u6570 ${_}\uFF0C\u53EA\u8FD4\u56DE\u524D ${1e4} \u6761`});let D=IZ(T).map((N)=>h.deserializeArrayFields(N)).filter((N)=>N!==null);return{data:{lists:kJ(D),total:_},sql:{count:O.sql,data:C.sql}}}async insData($){let{table:J,data:Z}=$,X=f(J),G=Date.now(),Y;try{Y=await this.redis.genTimeID()}catch(B){throw Error(`\u751F\u6210 ID \u5931\u8D25\uFF0CRedis \u53EF\u80FD\u4E0D\u53EF\u7528 (table: ${J})`,{cause:B})}let H=h.buildInsertRow({data:Z,id:Y,now:G});W0.assertNoUndefinedInRecord(H,`insData \u63D2\u5165\u6570\u636E (table: ${X})`);let z=this.createSqlBuilder(),{sql:V,params:O}=z.toInsertSql(X,H),_=await this.executeWithConn(V,O);return{data:H.id||_.data?.lastInsertRowid||0,sql:_.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=f($),G=[];for(let I=0;I<J.length;I++)G.push(await this.redis.genTimeID());let Y=Date.now(),H=J.map((I,B)=>{let S=G[B];if(typeof S!=="number")throw Error(`\u6279\u91CF\u63D2\u5165\u751F\u6210 ID \u5931\u8D25\uFF1Aids[${B}] \u4E0D\u662F number (table: ${X})`);return h.buildInsertRow({data:I,id:S,now:Y})}),z=W0.assertBatchInsertRowsConsistent(H,{table:X}),V=this.createSqlBuilder(),{sql:O,params:_}=V.toInsertSql(X,H);try{let I=await this.executeWithConn(O,_);return{data:G,sql:I.sql}}catch(I){throw j.error({err:I,table:$,snakeTable:X,count:J.length,fields:z,msg:"\u6279\u91CF\u63D2\u5165\u5931\u8D25"}),I}}async delForceBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=f($),X=b$.toDeleteInSql({table:Z,idField:"id",ids:J,quoteIdent:this.dialect.quoteIdent.bind(this.dialect)}),G=await this.executeWithConn(X.sql,X.params);return{data:G.data?.changes||0,sql:G.sql}}async updBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=f($),X=Date.now(),G=[],Y=new Set;for(let _ of J){let I=h.buildPartialUpdateData({data:_.data,allowState:!0});for(let B of Object.keys(I))Y.add(B);G.push({id:_.id,data:I})}let H=Array.from(Y).sort();if(H.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let z=b$.toUpdateCaseByIdSql({table:Z,idField:"id",rows:G,fields:H,quoteIdent:this.dialect.quoteIdent.bind(this.dialect),updatedAtField:"updated_at",updatedAtValue:X,stateField:"state",stateGtZero:!0}),V=await this.executeWithConn(z.sql,z.params);return{data:V.data?.changes||0,sql:V.sql}}async updData($){let{table:J,data:Z,where:X}=$,G=T$(X,{excludeValues:[null,void 0]}),Y=f(J),H=h.whereKeysToSnake(G),z=h.buildUpdateRow({data:Z,now:Date.now(),allowState:!0}),V=h.addDefaultStateFilter(H,Y,!1),O=this.createSqlBuilder().where(V),{sql:_,params:I}=O.toUpdateSql(Y,z),B=await this.executeWithConn(_,I);return{data:B.data?.changes||0,sql:B.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=f(J),G=T$(Z,{excludeValues:[null,void 0]}),Y=h.whereKeysToSnake(G),H=this.createSqlBuilder().where(Y),{sql:z,params:V}=H.toDeleteSql(X),O=await this.executeWithConn(z,V);return{data:O.data?.changes||0,sql:O.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 xJ({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}),G=this.createSqlBuilder().selectRaw("COUNT(1) as cnt").from(J).where(h.addDefaultStateFilter(Z,X,!1)).limit(1),{sql:Y,params:H}=G.toSelectSql(),z=await this.executeWithConn(Y,H);return{data:(z.data?.[0]?.cnt||0)>0,sql:z.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]}),G=X.data;if(!G)return{data:null,sql:X.sql};if(J in G)return{data:G[J],sql:X.sql};let Y=J.replace(/_([a-z])/g,(z,V)=>V.toUpperCase());if(Y!==J&&Y in G)return{data:G[Y],sql:X.sql};let H=J.replace(/[A-Z]/g,(z)=>`_${z.toLowerCase()}`);if(H!==J&&H in G)return{data:G[H],sql:X.sql};return{data:null,sql:X.sql}}async increment($,J,Z,X=1){let G=f($),Y=f(J);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(G))throw Error(`\u65E0\u6548\u7684\u8868\u540D: ${G}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(Y))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 H=T$(Z,{excludeValues:[null,void 0]}),z=h.whereKeysToSnake(H),V=h.addDefaultStateFilter(z,G,!1),O=this.createSqlBuilder().where(V),{sql:_,params:I}=O.getWhereConditions(),B=this.dialect.quoteIdent(G),S=this.dialect.quoteIdent(Y),C=_?`UPDATE ${B} SET ${S} = ${S} + ? WHERE ${_}`:`UPDATE ${B} SET ${S} = ${S} + ?`,T=await this.executeWithConn(C,[X,...I]);return{data:T.data?.changes||0,sql:T.sql}}async decrement($,J,Z,X=1){return await this.increment($,J,Z,-X)}}a();var B9={name:"db",enable:!0,deps:["logger","redis"],async handler($){let J=$.config?.nodeEnv;if(!$.redis)throw Error("Redis \u672A\u521D\u59CB\u5316");try{let Z=U$.getSql(),X=$.config?.db?.type,G=X==="postgres"?"postgresql":X,Y=g$(G==="postgresql"||G==="sqlite"?G:"mysql");return new xJ({redis:$.redis,sql:Z,dialect:Y})}catch(Z){throw j.error({env:J,err:Z,msg:"\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25"}),Z}}},C1=B9;var v$=EW(_W(),1);class CX{config;constructor($={}){this.config={secret:$.secret||"befly-secret",expiresIn:$.expiresIn||"7d",algorithm:$.algorithm||"HS256"}}sign($,J={}){let Z=J.secret||this.config.secret,X=J.algorithm||this.config.algorithm||"HS256",G={key:Z,algorithm:X,expiresIn:J.expiresIn??this.config.expiresIn};if(J.issuer!==void 0)G.iss=J.issuer;if(J.audience!==void 0)G.aud=J.audience;if(J.subject!==void 0)G.sub=J.subject;if(J.jwtId!==void 0)G.jti=J.jwtId;if(typeof J.notBefore==="number")G.notBefore=J.notBefore;return v$.createSigner(G)($)}verify($,J={}){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let Z=J.secret||this.config.secret,X=this.config.algorithm||"HS256",G=J.algorithms?J.algorithms:[X],Y={key:Z,algorithms:G,cache:!0,cacheTTL:600000};if(J.issuer!==void 0)Y.allowedIss=J.issuer;if(J.audience!==void 0)Y.allowedAud=J.audience;if(J.subject!==void 0)Y.allowedSub=J.subject;if(typeof J.ignoreExpiration==="boolean")Y.ignoreExpiration=J.ignoreExpiration;if(typeof J.ignoreNotBefore==="boolean")Y.ignoreNotBefore=J.ignoreNotBefore;return v$.createVerifier(Y)($)}decode($,J=!1){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(J){let G=v$.createDecoder({complete:!0})($);return{header:G.header,payload:G.payload,signature:G.signature}}return v$.createDecoder()($)}}var mz={name:"jwt",enable:!0,deps:[],handler:($)=>{return new CX($.config?$.config.auth:void 0)}},AW=mz;a();var dz={name:"logger",enable:!0,deps:[],async handler($){if($.config&&$.config.logger)j.configure($.config.logger);return j}},FW=dz;a();a();class wX{client;prefix;slowThresholdMs=500;constructor($=""){let J=U$.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;j.warn({subsystem:"redis",event:"slow",duration:Z,cmd:$,key:J,extra:X,msg:"\uD83D\uDC0C Redis \u6162\u64CD\u4F5C"})}async setObject($,J,Z=null){try{let X=JSON.stringify(J),G=`${this.prefix}${$}`,Y=Date.now();if(Z){let V=await this.client.setex(G,Z,X),O=Date.now()-Y;return this.logSlow("SETEX",G,O,{ttl:Z}),V}let H=await this.client.set(G,X),z=Date.now()-Y;return this.logSlow("SET",G,z),H}catch(X){return j.error({err:X,msg:"Redis setObject \u9519\u8BEF"}),null}}async getObject($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.get(J),G=Date.now()-Z;return this.logSlow("GET",J,G),X?JSON.parse(X):null}catch(J){return j.error({err:J,msg:"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){j.error({err:J,msg:"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 G=Date.now()-Z;this.logSlow("INCR",J,G,{expireSeconds:1});let Y=100+($%900+X-1)%900;return Number(`${$}${Y}`)}async setString($,J,Z=null){try{let X=`${this.prefix}${$}`,G=Date.now();if(Z){let z=await this.client.setex(X,Z,J),V=Date.now()-G;return this.logSlow("SETEX",X,V,{ttl:Z}),z}let Y=await this.client.set(X,J),H=Date.now()-G;return this.logSlow("SET",X,H),Y}catch(X){return j.error({err:X,msg:"Redis setString \u9519\u8BEF"}),null}}async getString($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.get(J),G=Date.now()-Z;return this.logSlow("GET",J,G),X}catch(J){return j.error({err:J,msg:"Redis getString \u9519\u8BEF"}),null}}async exists($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.exists(J),G=Date.now()-Z;return this.logSlow("EXISTS",J,G),X}catch(J){return j.error({err:J,msg:"Redis exists \u9519\u8BEF"}),!1}}async incr($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.incr(J),G=Date.now()-Z;return this.logSlow("INCR",J,G),X}catch(J){return j.error({err:J,msg:"Redis incr \u9519\u8BEF"}),0}}async incrWithExpire($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),G=await this.client.incr(Z);if(G===1)await this.client.expire(Z,J);let Y=Date.now()-X;return this.logSlow("INCR",Z,Y,{expireSeconds:J}),G}catch(Z){return j.error({err:Z,msg:"Redis incrWithExpire \u9519\u8BEF"}),0}}async expire($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),G=await this.client.expire(Z,J),Y=Date.now()-X;return this.logSlow("EXPIRE",Z,Y,{seconds:J}),G}catch(Z){return j.error({err:Z,msg:"Redis expire \u9519\u8BEF"}),0}}async ttl($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.ttl(J),G=Date.now()-Z;return this.logSlow("TTL",J,G),X}catch(J){return j.error({err:J,msg:"Redis ttl \u9519\u8BEF"}),-1}}async ttlBatch($){if($.length===0)return[];try{return await Promise.all($.map((Z)=>this.ttl(Z)))}catch(J){return j.error({err:J,msg:"Redis ttlBatch \u9519\u8BEF"}),$.map(()=>-1)}}async sadd($,J){try{if(J.length===0)return 0;let Z=`${this.prefix}${$}`,X=Date.now(),G=await this.client.sadd(Z,...J),Y=Date.now()-X;return this.logSlow("SADD",Z,Y,{membersCount:J.length}),G}catch(Z){return j.error({err:Z,msg:"Redis sadd \u9519\u8BEF"}),0}}async sismember($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),G=await this.client.sismember(Z,J),Y=Date.now()-X;return this.logSlow("SISMEMBER",Z,Y),G}catch(Z){return j.error({err:Z,msg:"Redis sismember \u9519\u8BEF"}),!1}}async scard($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.scard(J),G=Date.now()-Z;return this.logSlow("SCARD",J,G),X}catch(J){return j.error({err:J,msg:"Redis scard \u9519\u8BEF"}),0}}async smembers($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.smembers(J),G=Date.now()-Z;return this.logSlow("SMEMBERS",J,G),X}catch(J){return j.error({err:J,msg:"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 j.error({err:J,msg:"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 j.error({err:J,msg:"Redis sismemberBatch \u9519\u8BEF"}),$.map(()=>!1)}}async del($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.del(J),G=Date.now()-Z;return this.logSlow("DEL",J,G),X}catch(J){return j.error({err:J,msg:"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 j.error({err:J,msg:"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 j.error({err:J,msg:"Redis setBatch \u9519\u8BEF"}),0}}async getBatch($){if($.length===0)return[];try{return await Promise.all($.map((Z)=>this.getObject(Z)))}catch(J){return j.error({err:J,msg:"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 j.error({err:J,msg:"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 j.error({err:J,msg:"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 j.error({err:$,msg:"Redis ping \u9519\u8BEF"}),$}}}var sz={name:"redis",enable:!0,deps:["logger"],async handler($){let J=$.config?.nodeEnv,Z=$.config?.redis?.prefix;try{return U$.getRedis(),new wX(Z)}catch(X){throw j.error({env:J,err:X,msg:"Redis \u521D\u59CB\u5316\u5931\u8D25"}),X}}},RW=sz;function oz($,J={},Z={}){return{code:0,msg:$,data:J,...Z}}function lz($,J=null,Z={}){return{code:1,msg:$,data:J,...Z}}function rz($,J,Z={}){let{status:X=200,contentType:G,headers:Y={}}=Z,H=G,z;if(typeof J==="string"){if(z=J,!H)H=J.trim().startsWith("<")?"application/xml":"text/plain"}else z=JSON.stringify(J),H=H||"application/json";let V={...$.corsHeaders,"Content-Type":H,...Y};return new Response(z,{status:X,headers:V})}var iz={name:"tool",enable:!0,deps:[],handler:()=>{return{Yes:oz,No:lz,Raw:rz}}},IW=iz;n0();function qW($,J){let Z=J.name,X=i(J)?Object.keys(J):[];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,customKeys:X}}function jW(){let $=[],J=[FW,RW,C1,B1,IW,L1,AW,S1];for(let Z of J)$.push(qW("plugin",Z));return $}function PW(){let $=[],J=[Q1,z1,R1,P1,I1];for(let Z of J)$.push(qW("hook",Z));return $}q$();AJ();n0();import{existsSync as tz}from"fs";function az($){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 ez($){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 O$($,J,Z,X){if(!tz($))return[];let G=S$($),Y=new Bun.Glob(X),H=[];try{let z=await Y.scan({cwd:$,onlyFiles:!0,absolute:!0,followSymlinks:!0});for await(let V of z){if(V.endsWith(".d.ts"))continue;let O=S$(V),_=$J(O).name,I=vZ(G,O),B=$J(I),S=B.dir?m(B.dir,B.name):B.name;if(_.startsWith("_"))continue;if(S.split("/").some((N)=>N.startsWith("_")))continue;let C=await R$(O,{}),T=_$(_),E="",D="";if(J==="core")E="",D=_;else if(J==="app")D=`app_${T}`;else{let N=az(O)||ez(O);if(!N)throw Error(`scanFiles addon moduleName \u89E3\u6790\u5931\u8D25\uFF1A\u672A\u627E\u5230 @befly-addon/<addon>/ \u6BB5\u843D\uFF1A${O}`);E=N,D=`addon_${_$(E)}_${T}`}let w={source:J,type:Z,sourceName:J==="core"?"\u6838\u5FC3":J==="addon"?"\u7EC4\u4EF6":"\u9879\u76EE",filePath:O,relativePath:S,fileName:_,moduleName:D,addonName:E,fileBaseName:$J(O).base,fileDir:$,customKeys:i(C)?Object.keys(C):[]};if(Z==="table"){w.content=C,H.push(w);continue}if(Z==="api")w.auth=!0,w.rawBody=!1,w.method="POST",w.fields={},w.required=[];if(Z==="plugin"||Z==="hook")w.deps=[],w.name="",w.handler=null;if(sX(C,(N,p)=>{w[p]=N}),Z==="api")w.routePrefix=J==="app"?"/app":`/addon/${E}`,w.path=`/api${w.routePrefix}/${S}`;H.push(w)}}catch(z){let V=Error(`scanFiles failed: source=${J} type=${Z} dir=${G} pattern=${X}`);throw V.cause=z,V}return H}var BW=async()=>{let $=[],J=[],Z=[],X=[],G=await H1();X.push(...await O$(m(d0,"tables"),"app","table","*.json"));for(let Y of G)X.push(...await O$(m(Y.fullPath,"tables"),"addon","table","*.json"));J.push(...jW()),J.push(...await O$(m(d0,"plugins"),"app","plugin","*.{ts,js}"));for(let Y of G)J.push(...await O$(m(Y.fullPath,"plugins"),"addon","plugin","*.{ts,js}"));Z.push(...PW()),Z.push(...await O$(m(d0,"hooks"),"app","hook","*.{ts,js}"));for(let Y of G)Z.push(...await O$(m(Y.fullPath,"hooks"),"addon","hook","*.{ts,js}"));$.push(...await O$(m(d0,"apis"),"app","api","**/*.{ts,js}"));for(let Y of G)$.push(...await O$(m(Y.fullPath,"apis"),"addon","api","**/*.{ts,js}"));return{hooks:Z,plugins:J,apis:$,tables:X,addons:G}};class $8{apis=new Map;plugins=[];hooks=[];context={};config=null;async start($={}){try{let J=Bun.nanoseconds();this.config=await zG($.NODE_ENV||"development"),this.context.config=this.config,this.context.env=$;let{apis:Z,tables:X,plugins:G,hooks:Y,addons:H}=await BW();this.context.addons=H,await UG(Z),await EG(X),await BG(G),await OG(Y);let z=await jG(H);if(await U$.connect({db:this.config.db||{},redis:this.config.redis||{}}),this.plugins=await kG(G,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 SJ(this.context,X),await hG(this.context,Z),await uG(this.context,z);let V=this.config.devEmail,O=this.config.devPassword;if(typeof V==="string"&&V.length>0&&typeof O==="string"&&O.length>0)await cG(this.context,{devEmail:V,devPassword:O});else j.debug("\u8DF3\u8FC7 syncDev\uFF1A\u672A\u914D\u7F6E devEmail/devPassword");await bG(this.context),this.hooks=await DG(Y),this.apis=await vG(Z);let _=yG(this.apis,this.hooks,this.context),I=gG(this.config.cors),B=typeof this.config.appPort==="number"?this.config.appPort:3000,S=typeof this.config.appHost==="string"&&this.config.appHost.length>0?this.config.appHost:"0.0.0.0",C=Bun.serve({port:B,hostname:S,development:this.config.nodeEnv==="development",idleTimeout:30,fetch:async(N,p)=>{let v=new URL(N.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 _(N,p);return I(N)},error:(N)=>{if(j.error({err:N,msg:"\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:N.message,stack:N.stack},{status:200});return Response.json({code:1,msg:"\u5185\u90E8\u670D\u52A1\u5668\u9519\u8BEF"},{status:200})}}),T=Y1(J),E=W1($),D=E.role==="primary"?"\u4E3B\u8FDB\u7A0B":`\u5DE5\u4F5C\u8FDB\u7A0B #${E.instanceId}`,w=E.env==="standalone"?"":` [${E.env}]`;return j.info(`${this.config.appName} \u542F\u52A8\u6210\u529F! (${D}${w})`),j.info(`\u670D\u52A1\u5668\u542F\u52A8\u8017\u65F6: ${T}`),j.info(`\u670D\u52A1\u5668\u76D1\u542C\u5730\u5740: ${C.url}`),C}catch(J){j.error({err:J,msg:"\u9879\u76EE\u542F\u52A8\u5931\u8D25"});try{await j.flush()}catch{}try{await j.shutdown()}catch{}if(J instanceof Error)throw J;throw Error(String(J))}}}export{$8 as Befly};
18
+ 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=J.split("#");if(Z.length!==2)return J;let G=Z[0],X=Z[1];if(typeof G!=="string"||typeof X!=="string")return J;return`${f(G.trim())}#${X.trim()}`})}static processJoinField($){if($.includes("(")||$==="*"||$.startsWith("`"))return $;if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i),Z=J[0],G=J[1];if(typeof Z!=="string"||typeof G!=="string")return $;return`${h.processJoinField(Z.trim())} AS ${G.trim()}`}if($.includes(".")){let J=$.split(".");if(J.length<2)return f($);if(J.some((X)=>X.trim()===""))return $;let Z=J[J.length-1],G=J.slice(0,J.length-1).join(".");if(typeof Z!=="string"||typeof G!=="string")return f($);return`${G.trim()}.${f(Z)}`}return f($)}static processJoinWhereKey($){if($==="$or"||$==="$and")return $;if($.includes("$")){let J=$.lastIndexOf("$"),Z=$.substring(0,J),G=$.substring(J);if(Z.includes(".")){let X=Z.split(".");if(X.length<2)return`${f(Z)}${G}`;if(X.some((U)=>U.trim()===""))return`${f(Z)}${G}`;let Y=X[X.length-1],H=X.slice(0,X.length-1).join(".");if(typeof Y!=="string"||typeof H!=="string")return`${f(Z)}${G}`;return`${H.trim()}.${f(Y)}${G}`}return`${f(Z)}${G}`}if($.includes(".")){let J=$.split(".");if(J.length<2)return f($);if(J.some((X)=>X.trim()===""))return f($);let Z=J[J.length-1],G=J.slice(0,J.length-1).join(".");if(typeof Z!=="string"||typeof G!=="string")return f($);return`${G.trim()}.${f(Z)}`}return f($)}static processJoinWhere($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>h.processJoinWhere(Z));let J={};for(let[Z,G]of Object.entries($)){let X=h.processJoinWhereKey(Z);if(Z==="$or"||Z==="$and")J[X]=G.map((Y)=>h.processJoinWhere(Y));else if(typeof G==="object"&&G!==null&&!Array.isArray(G))J[X]=h.processJoinWhere(G);else J[X]=G}return J}static processJoinOrderBy($){if(!$||!Array.isArray($))return $;return $.map((J)=>{if(typeof J!=="string"||!J.includes("#"))return J;let Z=J.split("#");if(Z.length!==2)return J;let G=Z[0],X=Z[1];if(typeof G!=="string"||typeof X!=="string")return J;return`${h.processJoinField(G.trim())}#${X.trim()}`})}static addDefaultStateFilter($={},J,Z=!1){if(Object.keys($).some((Y)=>Y.startsWith("state")||Y.includes(".state")))return $;if(Z&&J){let Y={};for(let[H,U]of Object.entries($))Y[H]=U;return Y[`${J}.state$gt`]=0,Y}let X={};for(let[Y,H]of Object.entries($))X[Y]=H;return X.state$gt=0,X}static whereKeysToSnake($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>h.whereKeysToSnake(Z));let J={};for(let[Z,G]of Object.entries($)){if(Z==="$or"||Z==="$and"){J[Z]=G.map((Y)=>h.whereKeysToSnake(Y));continue}if(Z.includes("$")){let Y=Z.lastIndexOf("$"),H=Z.substring(0,Y),U=Z.substring(Y),z=f(H)+U;J[z]=G;continue}let X=f(Z);if(typeof G==="object"&&G!==null&&!Array.isArray(G))J[X]=h.whereKeysToSnake(G);else J[X]=G}return J}static serializeArrayFields($){let J={};for(let[Z,G]of Object.entries($)){if(G===null||G===void 0){J[Z]=G;continue}if(Array.isArray(G)){J[Z]=JSON.stringify(G);continue}J[Z]=G}return J}static deserializeArrayFields($){if(!$)return null;let J={};for(let[Z,G]of Object.entries($))J[Z]=G;for(let[Z,G]of Object.entries(J)){if(typeof G!=="string")continue;if(G.startsWith("[")&&G.endsWith("]"))try{let X=JSON.parse(G);if(Array.isArray(X))J[Z]=X}catch{}}return J}static cleanAndSnakeAndSerializeWriteData($,J=[null,void 0]){let Z=N$($,{excludeValues:J}),G=oG(Z);return h.serializeArrayFields(G)}static stripSystemFieldsForWrite($,J){let Z={};for(let[G,X]of Object.entries($)){if(G==="id")continue;if(G==="created_at")continue;if(G==="updated_at")continue;if(G==="deleted_at")continue;if(!J.allowState&&G==="state")continue;Z[G]=X}return Z}static buildInsertRow($){let J=h.cleanAndSnakeAndSerializeWriteData($.data),Z=h.stripSystemFieldsForWrite(J,{allowState:!1}),G={};for(let[X,Y]of Object.entries(Z))G[X]=Y;return G.id=$.id,G.created_at=$.now,G.updated_at=$.now,G.state=1,G}static buildUpdateRow($){let J=h.cleanAndSnakeAndSerializeWriteData($.data),Z=h.stripSystemFieldsForWrite(J,{allowState:$.allowState}),G={};for(let[X,Y]of Object.entries(Z))G[X]=Y;return G.updated_at=$.now,G}static buildPartialUpdateData($){let J=h.cleanAndSnakeAndSerializeWriteData($.data);return h.stripSystemFieldsForWrite(J,{allowState:$.allowState})}}a();class W0{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],G=J[J.length-1];if(Z==="`"&&G==="`")return!0;if(Z==='"'&&G==='"')return!0;return!1}static assertPairedQuotedIdentIfStartsWithQuote($,J){if(W0.startsWithQuote($)&&!W0.isQuotedIdentPaired($))throw Error(`${J} \u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (value: ${$})`)}static assertSafeIdentifierPart($,J){if(!W0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684 ${J} \u6807\u8BC6\u7B26: ${$}`)}static assertSafeAlias($){if(W0.isQuotedIdentPaired($))return;if(!W0.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,G]of Object.entries($))if(G===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 G=Object.keys(Z);if(G.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${J.table})`);let X=new Set(G);for(let Y=0;Y<$.length;Y++){let H=$[Y];if(!H||typeof H!=="object"||Array.isArray(H))throw Error(`\u6279\u91CF\u63D2\u5165\u7684\u6BCF\u4E00\u884C\u5FC5\u987B\u662F\u5BF9\u8C61 (table: ${J.table}, rowIndex: ${Y})`);let U=Object.keys(H);if(U.length!==G.length)throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${Y})`);for(let z of U)if(!X.has(z))throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${Y}, extraField: ${z})`);for(let z of G){if(!(z in H))throw Error(`\u6279\u91CF\u63D2\u5165\u7F3A\u5C11\u5B57\u6BB5 (table: ${J.table}, rowIndex: ${Y}, field: ${z})`);W0.assertNoUndefinedParam(H[z],`\u6279\u91CF\u63D2\u5165\u5B57\u6BB5\u503C (table: ${J.table}, rowIndex: ${Y}, field: ${z})`)}}return G}}var g={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: ${$})`,FIELD_INVALID:($)=>`\u5B57\u6BB5\u683C\u5F0F\u975E\u6CD5\uFF0C\u8BF7\u4F7F\u7528\u7B80\u5355\u5B57\u6BB5\u540D\u6216\u5B89\u5168\u5F15\u7528\uFF0C\u590D\u6742\u8868\u8FBE\u5F0F\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 c${_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(g.QUOTE_IDENT_NEED_STRING(J));let Z=J.trim();if(!Z)throw Error(g.IDENT_EMPTY);return`\`${Z.replace(/`/g,"``")}\``}}_isQuotedIdent($){return W0.isQuotedIdentPaired($)}_startsWithQuote($){return W0.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(),W0.assertPairedQuotedIdentIfStartsWithQuote($,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),$==="*"||this._isQuotedIdent($))return $;try{W0.assertNoExprField($)}catch{throw Error(g.FIELD_EXPR_NOT_ALLOWED($))}if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i);if(J.length!==2)throw Error(g.FIELD_INVALID($));let Z=J[0],G=J[1];if(typeof Z!=="string"||typeof G!=="string")throw Error(g.FIELD_INVALID($));let X=Z.trim(),Y=G.trim();return W0.assertSafeAlias(Y),`${this._escapeField(X)} AS ${Y}`}if($.includes("."))return $.split(".").map((Z)=>{if(Z=Z.trim(),Z==="*"||this._isQuotedIdent(Z))return Z;return W0.assertPairedQuotedIdentIfStartsWithQuote(Z,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),this._quoteIdent(Z)}).join(".");return this._quoteIdent($)}_validateIdentifierPart($,J){W0.assertSafeIdentifierPart($,J)}_escapeTable($){if(typeof $!=="string")return $;if($=$.trim(),this._startsWithQuote($)&&!this._isQuotedIdent($));if(this._isQuotedIdent($))return $;let J=$.split(/\s+/).filter((z)=>z.length>0);if(J.length===0)throw Error(g.FROM_EMPTY);if(J.length>2)throw Error(g.TABLE_REF_TOO_MANY_PARTS($));let Z=J[0];if(typeof Z!=="string"||Z.trim()==="")throw Error(g.FROM_EMPTY);let G=Z.trim(),X=J.length===2?J[1]:null,Y=typeof X==="string"?X.trim():null,H=G.split(".");if(H.length>2)throw Error(g.TABLE_REF_SCHEMA_TOO_DEEP($));let U="";if(H.length===2){let z=H[0],O=H[1];if(typeof z!=="string"||typeof O!=="string")throw Error(g.TABLE_REF_SCHEMA_TOO_DEEP($));let _=z.trim(),I=O.trim(),B=this._isQuotedIdent(_)?_:(()=>{if(this._startsWithQuote(_)&&!this._isQuotedIdent(_))throw Error(g.SCHEMA_QUOTE_NOT_PAIRED(_));return this._validateIdentifierPart(_,"schema"),this._quoteIdent(_)})(),S=this._isQuotedIdent(I)?I:(()=>{if(this._startsWithQuote(I)&&!this._isQuotedIdent(I))throw Error(g.TABLE_QUOTE_NOT_PAIRED(I));return this._validateIdentifierPart(I,"table"),this._quoteIdent(I)})();U=`${B}.${S}`}else{let z=H[0];if(typeof z!=="string")throw Error(g.FROM_EMPTY);let O=z.trim();if(this._isQuotedIdent(O))U=O;else{if(this._startsWithQuote(O)&&!this._isQuotedIdent(O))throw Error(g.TABLE_QUOTE_NOT_PAIRED(O));this._validateIdentifierPart(O,"table"),U=this._quoteIdent(O)}}if(Y)return this._validateIdentifierPart(Y,"alias"),`${U} ${Y}`;return U}_validateParam($){W0.assertNoUndefinedParam($,"SQL \u53C2\u6570\u503C")}_applyOperator($,J,Z){let G=this._escapeField($);switch(J){case"$ne":case"$not":this._validateParam(Z),this._where.push(`${G} != ?`),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 X=Z.map(()=>"?").join(",");this._where.push(`${G} IN (${X})`),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 Y=Z.map(()=>"?").join(",");this._where.push(`${G} NOT IN (${Y})`),this._params.push(...Z);break;case"$like":this._validateParam(Z),this._where.push(`${G} LIKE ?`),this._params.push(Z);break;case"$notLike":this._validateParam(Z),this._where.push(`${G} NOT LIKE ?`),this._params.push(Z);break;case"$gt":this._validateParam(Z),this._where.push(`${G} > ?`),this._params.push(Z);break;case"$gte":this._validateParam(Z),this._where.push(`${G} >= ?`),this._params.push(Z);break;case"$lt":this._validateParam(Z),this._where.push(`${G} < ?`),this._params.push(Z);break;case"$lte":this._validateParam(Z),this._where.push(`${G} <= ?`),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(`${G} 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(`${G} NOT BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$null":if(Z===!0)this._where.push(`${G} IS NULL`);break;case"$notNull":if(Z===!0)this._where.push(`${G} IS NOT NULL`);break;default:this._validateParam(Z),this._where.push(`${G} = ?`),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((G)=>this._processWhereConditions(G))}else if(J==="$or"){if(Array.isArray(Z)){let G=[],X=[];if(Z.forEach((Y)=>{let H=new c$({quoteIdent:this._quoteIdent});if(H._processWhereConditions(Y),H._where.length>0)G.push(`(${H._where.join(" AND ")})`),X.push(...H._params)}),G.length>0)this._where.push(`(${G.join(" OR ")})`),this._params.push(...X)}}else if(J.includes("$")){let G=J.lastIndexOf("$"),X=J.substring(0,G),Y="$"+J.substring(G+1);this._applyOperator(X,Y,Z)}else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))for(let[G,X]of Object.entries(Z))this._applyOperator(J,G,X);else{this._validateParam(Z);let G=this._escapeField(J);this._where.push(`${G} = ?`),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(g.SELECT_FIELDS_INVALID);return this}selectRaw($){if(typeof $!=="string"||!$.trim())throw Error(g.SELECT_RAW_NEED_NON_EMPTY($));return this._select.push($),this}from($){if(typeof $!=="string"||!$.trim())throw Error(g.FROM_NEED_NON_EMPTY($));return this._from=this._escapeTable($.trim()),this}fromRaw($){if(typeof $!=="string"||!$.trim())throw Error(g.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(g.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(g.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(g.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(g.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(g.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`INNER JOIN ${Z} ON ${J}`),this}orderBy($){if(!Array.isArray($))throw Error(g.ORDER_BY_NEED_ARRAY);return $.forEach((J)=>{if(typeof J!=="string"||!J.includes("#"))throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let Z=J.split("#");if(Z.length!==2)throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let G=Z[0],X=Z[1];if(typeof G!=="string"||typeof X!=="string")throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let Y=G.trim(),H=X.trim().toUpperCase();if(!Y)throw Error(g.ORDER_BY_FIELD_EMPTY(J));if(!["ASC","DESC"].includes(H))throw Error(g.ORDER_BY_DIR_INVALID(H));let U=this._escapeField(Y);this._orderBy.push(`${U} ${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(g.LIMIT_MUST_NON_NEGATIVE($));if(this._limit=Math.floor($),J!==void 0&&J!==null){if(typeof J!=="number"||J<0)throw Error(g.OFFSET_MUST_NON_NEGATIVE(J));this._offset=Math.floor(J)}return this}offset($){if(typeof $!=="number"||$<0)throw Error(g.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(g.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(g.INSERT_NEED_TABLE($));if(!J||typeof J!=="object")throw Error(g.INSERT_NEED_DATA($,J));let Z=this._escapeTable($);if(Array.isArray(J)){let G=W0.assertBatchInsertRowsConsistent(J,{table:$}),X=G.map((O)=>this._escapeField(O)),Y=G.map(()=>"?").join(", "),H=J.map(()=>`(${Y})`).join(", "),U=`INSERT INTO ${Z} (${X.join(", ")}) VALUES ${H}`,z=[];for(let O=0;O<J.length;O++){let _=J[O];for(let I of G){let B=_[I];this._validateParam(B),z.push(B)}}return{sql:U,params:z}}else{let G=Object.keys(J);if(G.length===0)throw Error(g.INSERT_NEED_AT_LEAST_ONE_FIELD($));for(let z of G)this._validateParam(J[z]);let X=G.map((z)=>this._escapeField(z)),Y=G.map(()=>"?").join(", "),H=`INSERT INTO ${Z} (${X.join(", ")}) VALUES (${Y})`,U=[];for(let z of G){let O=J[z];this._validateParam(O),U.push(O)}return{sql:H,params:U}}}toUpdateSql($,J){if(!$||typeof $!=="string")throw Error(g.UPDATE_NEED_TABLE);if(!J||typeof J!=="object"||Array.isArray(J))throw Error(g.UPDATE_NEED_OBJECT);let Z=Object.keys(J);if(Z.length===0)throw Error(g.UPDATE_NEED_AT_LEAST_ONE_FIELD);let G=this._escapeTable($),X=Z.map((U)=>`${this._escapeField(U)} = ?`),Y=[...Object.values(J),...this._params],H=`UPDATE ${G} SET ${X.join(", ")}`;if(this._where.length>0)H+=" WHERE "+this._where.join(" AND ");else throw Error(g.UPDATE_NEED_WHERE);return{sql:H,params:Y}}toDeleteSql($){if(!$||typeof $!=="string")throw Error(g.DELETE_NEED_TABLE);let Z=`DELETE FROM ${this._escapeTable($)}`;if(this._where.length>0)Z+=" WHERE "+this._where.join(" AND ");else throw Error(g.DELETE_NEED_WHERE);return{sql:Z,params:[...this._params]}}toCountSql(){let $="SELECT COUNT(*) as total";if(!this._from)throw Error(g.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(g.TO_DELETE_IN_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(g.TO_DELETE_IN_NEED_ID_FIELD($.idField));if(!Array.isArray($.ids))throw Error(g.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(g.TO_UPDATE_CASE_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(g.TO_UPDATE_CASE_NEED_ID_FIELD($.idField));if(!Array.isArray($.rows))throw Error(g.TO_UPDATE_CASE_NEED_ROWS);if($.rows.length===0)return{sql:"",params:[]};if(!Array.isArray($.fields))throw Error(g.TO_UPDATE_CASE_NEED_FIELDS);if($.fields.length===0)return{sql:"",params:[]};let J=$.rows.map((U)=>U.id),Z=J.map(()=>"?").join(","),G=[],X=[],Y=$.quoteIdent($.idField);for(let U of $.fields){let z=[];for(let _ of $.rows){if(!(U in _.data))continue;z.push("WHEN ? THEN ?"),X.push(_.id);let I=_.data[U];W0.assertNoUndefinedParam(I,"SQL \u53C2\u6570\u503C"),X.push(I)}if(z.length===0)continue;let O=$.quoteIdent(U);G.push(`${O} = CASE ${Y} ${z.join(" ")} ELSE ${O} END`)}G.push(`${$.quoteIdent($.updatedAtField)} = ?`),X.push($.updatedAtValue);for(let U of J)X.push(U);let H=`UPDATE ${$.quoteIdent($.table)} SET ${G.join(", ")} WHERE ${Y} IN (${Z})`;if($.stateGtZero&&$.stateField)H+=` AND ${$.quoteIdent($.stateField)} > 0`;return{sql:H,params:X}}}var jQ=3600;class yJ{redis;dialect;sql=null;isTransaction=!1;constructor($){this.redis=$.redis,this.sql=$.sql||null,this.isTransaction=Boolean($.sql),this.dialect=$.dialect?$.dialect:new BJ}createSqlBuilder(){return new c$({quoteIdent:this.dialect.quoteIdent.bind(this.dialect)})}async getTableColumns($){let J=G0.tableColumns($),Z=await this.redis.getObject(J);if(Z&&Z.length>0)return Z;let G=this.dialect.getTableColumnsQuery($),Y=(await this.executeWithConn(G.sql,G.params)).data;if(!Y||Y.length===0)throw Error(`\u8868 ${$} \u4E0D\u5B58\u5728\u6216\u6CA1\u6709\u5B57\u6BB5`);let H=this.dialect.getTableColumnsFromResult(Y);if(await this.redis.setObject(J,H,jQ)===null)j.warn({table:$,cacheKey:J,msg:"\u8868\u5B57\u6BB5\u7F13\u5B58\u5199\u5165 Redis \u5931\u8D25"});return H}async prepareQueryOptions($){let J=N$($.where||{},{excludeValues:[null,void 0]});if($.joins&&$.joins.length>0){let X=($.fields||[]).map((U)=>h.processJoinField(U)),Y=h.normalizeTableRef($.table),H=h.getJoinMainQualifier($.table);return{table:Y,tableQualifier:H,fields:X.length>0?X:["*"],where:h.processJoinWhere(J),joins:$.joins,orderBy:h.processJoinOrderBy($.orderBy||[]),page:$.page||1,limit:$.limit||10}}let G=await h.fieldsToSnake(f($.table),$.fields||[],this.getTableColumns.bind(this));return{table:f($.table),tableQualifier:f($.table),fields:G,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 G=h.normalizeTableRef(Z.table);switch(Z.type||"left"){case"inner":$.innerJoin(G,Z.on);break;case"right":$.rightJoin(G,Z.on);break;case"left":default:$.leftJoin(G,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(),G=Array.isArray(J)?J:[];try{let X;if(G.length>0)X=await this.sql.unsafe($,G);else X=await this.sql.unsafe($);let Y=Date.now()-Z;return{data:X,sql:{sql:$,params:G,duration:Y}}}catch(X){let Y=Date.now()-Z,H=Error(`SQL\u6267\u884C\u5931\u8D25: ${X.message}`);throw H.originalError=X,H.params=G,H.duration=Y,H.sqlInfo={sql:$,params:G,duration:Y},H}}async unsafe($,J){return await this.executeWithConn($,J)}async tableExists($){let J=f($),Z=this.dialect.tableExistsQuery(J),G=await this.executeWithConn(Z.sql,Z.params);return{data:(G.data?.[0]?.count||0)>0,sql:G.sql}}async getCount($){let{table:J,where:Z,joins:G,tableQualifier:X}=await this.prepareQueryOptions($),Y=Array.isArray(G)&&G.length>0,H=this.createSqlBuilder().selectRaw("COUNT(*) as count").from(J).where(h.addDefaultStateFilter(Z,X,Y));this.applyJoins(H,G);let{sql:U,params:z}=H.toSelectSql(),O=await this.executeWithConn(U,z);return{data:O.data?.[0]?.count||0,sql:O.sql}}async getOne($){let{table:J,fields:Z,where:G,joins:X,tableQualifier:Y}=await this.prepareQueryOptions($),H=Array.isArray(X)&&X.length>0,U=this.createSqlBuilder().select(Z).from(J).where(h.addDefaultStateFilter(G,Y,H));this.applyJoins(U,X);let{sql:z,params:O}=U.toSelectSql(),_=await this.executeWithConn(z,O),B=_.data?.[0]||null;if(!B)return{data:{},sql:_.sql};let S=RZ(B),C=h.deserializeArrayFields(S);if(!C)return{data:{},sql:_.sql};return{data:kJ([C])[0]??C,sql:_.sql}}async getDetail($){return await this.getOne($)}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,Array.isArray(J.joins)&&J.joins.length>0),G=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(J.table).where(Z);this.applyJoins(G,J.joins);let{sql:X,params:Y}=G.toSelectSql(),H=await this.executeWithConn(X,Y),U=H.data?.[0]?.total||0;if(U===0)return{data:{lists:[],total:0,page:J.page,limit:J.limit,pages:0},sql:{count:H.sql}};let z=(J.page-1)*J.limit,O=this.createSqlBuilder().select(J.fields).from(J.table).where(Z).limit(J.limit).offset(z);if(this.applyJoins(O,J.joins),J.orderBy&&J.orderBy.length>0)O.orderBy(J.orderBy);let{sql:_,params:I}=O.toSelectSql(),B=await this.executeWithConn(_,I),S=B.data||[],T=IZ(S).map((E)=>h.deserializeArrayFields(E)).filter((E)=>E!==null);return{data:{lists:kJ(T),total:U,page:J.page,limit:J.limit,pages:Math.ceil(U/J.limit)},sql:{count:H.sql,data:B.sql}}}async getAll($){let G={table:$.table,page:1,limit:10};if($.fields!==void 0)G.fields=$.fields;if($.where!==void 0)G.where=$.where;if($.joins!==void 0)G.joins=$.joins;if($.orderBy!==void 0)G.orderBy=$.orderBy;let X=await this.prepareQueryOptions(G),Y=h.addDefaultStateFilter(X.where,X.tableQualifier,Array.isArray(X.joins)&&X.joins.length>0),H=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(X.table).where(Y);this.applyJoins(H,X.joins);let{sql:U,params:z}=H.toSelectSql(),O=await this.executeWithConn(U,z),_=O.data?.[0]?.total||0;if(_===0)return{data:{lists:[],total:0},sql:{count:O.sql}};let I=this.createSqlBuilder().select(X.fields).from(X.table).where(Y).limit(1e4);if(this.applyJoins(I,X.joins),X.orderBy&&X.orderBy.length>0)I.orderBy(X.orderBy);let{sql:B,params:S}=I.toSelectSql(),C=await this.executeWithConn(B,S),T=C.data||[];if(T.length>=1000)j.warn({table:$.table,count:T.length,total:_,msg:"getAll \u8FD4\u56DE\u6570\u636E\u8FC7\u591A\uFF0C\u5EFA\u8BAE\u4F7F\u7528 getList \u5206\u9875\u67E5\u8BE2"});if(T.length>=1e4)j.warn({table:$.table,limit:1e4,total:_,msg:`getAll \u8FBE\u5230\u6700\u5927\u9650\u5236 ${1e4}\uFF0C\u5B9E\u9645\u603B\u6570 ${_}\uFF0C\u53EA\u8FD4\u56DE\u524D ${1e4} \u6761`});let D=IZ(T).map((N)=>h.deserializeArrayFields(N)).filter((N)=>N!==null);return{data:{lists:kJ(D),total:_},sql:{count:O.sql,data:C.sql}}}async insData($){let{table:J,data:Z}=$,G=f(J),X=Date.now(),Y;try{Y=await this.redis.genTimeID()}catch(B){throw Error(`\u751F\u6210 ID \u5931\u8D25\uFF0CRedis \u53EF\u80FD\u4E0D\u53EF\u7528 (table: ${J})`,{cause:B})}let H=h.buildInsertRow({data:Z,id:Y,now:X});W0.assertNoUndefinedInRecord(H,`insData \u63D2\u5165\u6570\u636E (table: ${G})`);let U=this.createSqlBuilder(),{sql:z,params:O}=U.toInsertSql(G,H),_=await this.executeWithConn(z,O);return{data:H.id||_.data?.lastInsertRowid||0,sql:_.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 G=f($),X=[];for(let I=0;I<J.length;I++)X.push(await this.redis.genTimeID());let Y=Date.now(),H=J.map((I,B)=>{let S=X[B];if(typeof S!=="number")throw Error(`\u6279\u91CF\u63D2\u5165\u751F\u6210 ID \u5931\u8D25\uFF1Aids[${B}] \u4E0D\u662F number (table: ${G})`);return h.buildInsertRow({data:I,id:S,now:Y})}),U=W0.assertBatchInsertRowsConsistent(H,{table:G}),z=this.createSqlBuilder(),{sql:O,params:_}=z.toInsertSql(G,H);try{let I=await this.executeWithConn(O,_);return{data:X,sql:I.sql}}catch(I){throw j.error({err:I,table:$,snakeTable:G,count:J.length,fields:U,msg:"\u6279\u91CF\u63D2\u5165\u5931\u8D25"}),I}}async delForceBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=f($),G=c$.toDeleteInSql({table:Z,idField:"id",ids:J,quoteIdent:this.dialect.quoteIdent.bind(this.dialect)}),X=await this.executeWithConn(G.sql,G.params);return{data:X.data?.changes||0,sql:X.sql}}async updBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=f($),G=Date.now(),X=[],Y=new Set;for(let _ of J){let I=h.buildPartialUpdateData({data:_.data,allowState:!0});for(let B of Object.keys(I))Y.add(B);X.push({id:_.id,data:I})}let H=Array.from(Y).sort();if(H.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let U=c$.toUpdateCaseByIdSql({table:Z,idField:"id",rows:X,fields:H,quoteIdent:this.dialect.quoteIdent.bind(this.dialect),updatedAtField:"updated_at",updatedAtValue:G,stateField:"state",stateGtZero:!0}),z=await this.executeWithConn(U.sql,U.params);return{data:z.data?.changes||0,sql:z.sql}}async updData($){let{table:J,data:Z,where:G}=$,X=N$(G,{excludeValues:[null,void 0]}),Y=f(J),H=h.whereKeysToSnake(X),U=h.buildUpdateRow({data:Z,now:Date.now(),allowState:!0}),z=h.addDefaultStateFilter(H,Y,!1),O=this.createSqlBuilder().where(z),{sql:_,params:I}=O.toUpdateSql(Y,U),B=await this.executeWithConn(_,I);return{data:B.data?.changes||0,sql:B.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}=$,G=f(J),X=N$(Z,{excludeValues:[null,void 0]}),Y=h.whereKeysToSnake(X),H=this.createSqlBuilder().where(Y),{sql:U,params:z}=H.toDeleteSql(G),O=await this.executeWithConn(U,z);return{data:O.data?.changes||0,sql:O.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 yJ({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:G}=await this.prepareQueryOptions({...$,page:1,limit:1}),X=this.createSqlBuilder().selectRaw("COUNT(1) as cnt").from(J).where(h.addDefaultStateFilter(Z,G,!1)).limit(1),{sql:Y,params:H}=X.toSelectSql(),U=await this.executeWithConn(Y,H);return{data:(U.data?.[0]?.cnt||0)>0,sql:U.sql}}async getFieldValue($){let J=$.field;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 Z={table:$.table};if($.where!==void 0)Z.where=$.where;if($.joins!==void 0)Z.joins=$.joins;if($.orderBy!==void 0)Z.orderBy=$.orderBy;if($.page!==void 0)Z.page=$.page;if($.limit!==void 0)Z.limit=$.limit;Z.fields=[J];let G=await this.getOne(Z),X=G.data;if(Object.hasOwn(X,J))return{data:X[J],sql:G.sql};let Y=J.replace(/_([a-z])/g,(U,z)=>z.toUpperCase());if(Y!==J&&Object.hasOwn(X,Y))return{data:X[Y],sql:G.sql};let H=J.replace(/[A-Z]/g,(U)=>`_${U.toLowerCase()}`);if(H!==J&&Object.hasOwn(X,H))return{data:X[H],sql:G.sql};return{data:null,sql:G.sql}}async increment($,J,Z,G=1){let X=f($),Y=f(J);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(X))throw Error(`\u65E0\u6548\u7684\u8868\u540D: ${X}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(Y))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u540D: ${J}`);if(typeof G!=="number"||isNaN(G))throw Error(`\u81EA\u589E\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57 (table: ${$}, field: ${J}, value: ${G})`);let H=N$(Z,{excludeValues:[null,void 0]}),U=h.whereKeysToSnake(H),z=h.addDefaultStateFilter(U,X,!1),O=this.createSqlBuilder().where(z),{sql:_,params:I}=O.getWhereConditions(),B=this.dialect.quoteIdent(X),S=this.dialect.quoteIdent(Y),C=_?`UPDATE ${B} SET ${S} = ${S} + ? WHERE ${_}`:`UPDATE ${B} SET ${S} = ${S} + ?`,T=await this.executeWithConn(C,[G,...I]);return{data:T.data?.changes||0,sql:T.sql}}async decrement($,J,Z,G=1){return await this.increment($,J,Z,-G)}}a();var PQ={name:"db",enable:!0,deps:["logger","redis"],async handler($){let J=$.config?.nodeEnv;if(!$.redis)throw Error("Redis \u672A\u521D\u59CB\u5316");try{let Z=z$.getSql(),G=$.config?.db?.type,X=G==="postgres"?"postgresql":G,Y=h$(X==="postgresql"||X==="sqlite"?X:"mysql");return new yJ({redis:$.redis,sql:Z,dialect:Y})}catch(Z){throw j.error({env:J,err:Z,msg:"\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25"}),Z}}},SY=PQ;var D$=wW(MW(),1);class CG{config;constructor($={}){this.config={secret:$.secret||"befly-secret",expiresIn:$.expiresIn||"7d",algorithm:$.algorithm||"HS256"}}sign($,J={}){let Z=J.secret||this.config.secret,G=J.algorithm||this.config.algorithm||"HS256",X={key:Z,algorithm:G,expiresIn:J.expiresIn??this.config.expiresIn};if(J.issuer!==void 0)X.iss=J.issuer;if(J.audience!==void 0)X.aud=J.audience;if(J.subject!==void 0)X.sub=J.subject;if(J.jwtId!==void 0)X.jti=J.jwtId;if(typeof J.notBefore==="number")X.notBefore=J.notBefore;return D$.createSigner(X)($)}verify($,J={}){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let Z=J.secret||this.config.secret,G=this.config.algorithm||"HS256",X=J.algorithms?J.algorithms:[G],Y={key:Z,algorithms:X,cache:!0,cacheTTL:600000};if(J.issuer!==void 0)Y.allowedIss=J.issuer;if(J.audience!==void 0)Y.allowedAud=J.audience;if(J.subject!==void 0)Y.allowedSub=J.subject;if(typeof J.ignoreExpiration==="boolean")Y.ignoreExpiration=J.ignoreExpiration;if(typeof J.ignoreNotBefore==="boolean")Y.ignoreNotBefore=J.ignoreNotBefore;return D$.createVerifier(Y)($)}decode($,J=!1){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(J){let X=D$.createDecoder({complete:!0})($);return{header:X.header,payload:X.payload,signature:X.signature}}return D$.createDecoder()($)}}var n8={name:"jwt",enable:!0,deps:[],handler:($)=>{return new CG($.config?$.config.auth:void 0)}},_W=n8;a();var m8={name:"logger",enable:!0,deps:[],async handler($){if($.config&&$.config.logger)j.configure($.config.logger);return j}},AW=m8;a();a();class wG{client;prefix;slowThresholdMs=500;constructor($=""){let J=z$.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,G={}){if(Z<=this.slowThresholdMs)return;j.warn({subsystem:"redis",event:"slow",duration:Z,cmd:$,key:J,extra:G,msg:"\uD83D\uDC0C Redis \u6162\u64CD\u4F5C"})}async setObject($,J,Z=null){try{let G=JSON.stringify(J),X=`${this.prefix}${$}`,Y=Date.now();if(Z){let z=await this.client.setex(X,Z,G),O=Date.now()-Y;return this.logSlow("SETEX",X,O,{ttl:Z}),z}let H=await this.client.set(X,G),U=Date.now()-Y;return this.logSlow("SET",X,U),H}catch(G){return j.error({err:G,msg:"Redis setObject \u9519\u8BEF"}),null}}async getObject($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.get(J),X=Date.now()-Z;return this.logSlow("GET",J,X),G?JSON.parse(G):null}catch(J){return j.error({err:J,msg:"Redis getObject \u9519\u8BEF"}),null}}async delObject($){try{let J=`${this.prefix}${$}`,Z=Date.now();await this.client.del(J);let G=Date.now()-Z;this.logSlow("DEL",J,G)}catch(J){j.error({err:J,msg:"Redis delObject \u9519\u8BEF"})}}async genTimeID(){let $=Date.now(),J=`${this.prefix}time_id:${$}`,Z=Date.now(),G=await this.client.incr(J);if(G===1)await this.client.expire(J,1);let X=Date.now()-Z;this.logSlow("INCR",J,X,{expireSeconds:1});let Y=100+($%900+G-1)%900;return Number(`${$}${Y}`)}async setString($,J,Z=null){try{let G=`${this.prefix}${$}`,X=Date.now();if(Z){let U=await this.client.setex(G,Z,J),z=Date.now()-X;return this.logSlow("SETEX",G,z,{ttl:Z}),U}let Y=await this.client.set(G,J),H=Date.now()-X;return this.logSlow("SET",G,H),Y}catch(G){return j.error({err:G,msg:"Redis setString \u9519\u8BEF"}),null}}async getString($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.get(J),X=Date.now()-Z;return this.logSlow("GET",J,X),G}catch(J){return j.error({err:J,msg:"Redis getString \u9519\u8BEF"}),null}}async exists($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.exists(J),X=Date.now()-Z;return this.logSlow("EXISTS",J,X),G}catch(J){return j.error({err:J,msg:"Redis exists \u9519\u8BEF"}),!1}}async incr($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.incr(J),X=Date.now()-Z;return this.logSlow("INCR",J,X),G}catch(J){return j.error({err:J,msg:"Redis incr \u9519\u8BEF"}),0}}async incrWithExpire($,J){try{let Z=`${this.prefix}${$}`,G=Date.now(),X=await this.client.incr(Z);if(X===1)await this.client.expire(Z,J);let Y=Date.now()-G;return this.logSlow("INCR",Z,Y,{expireSeconds:J}),X}catch(Z){return j.error({err:Z,msg:"Redis incrWithExpire \u9519\u8BEF"}),0}}async expire($,J){try{let Z=`${this.prefix}${$}`,G=Date.now(),X=await this.client.expire(Z,J),Y=Date.now()-G;return this.logSlow("EXPIRE",Z,Y,{seconds:J}),X}catch(Z){return j.error({err:Z,msg:"Redis expire \u9519\u8BEF"}),0}}async ttl($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.ttl(J),X=Date.now()-Z;return this.logSlow("TTL",J,X),G}catch(J){return j.error({err:J,msg:"Redis ttl \u9519\u8BEF"}),-1}}async ttlBatch($){if($.length===0)return[];try{return await Promise.all($.map((Z)=>this.ttl(Z)))}catch(J){return j.error({err:J,msg:"Redis ttlBatch \u9519\u8BEF"}),$.map(()=>-1)}}async sadd($,J){try{if(J.length===0)return 0;let Z=`${this.prefix}${$}`,G=Date.now(),X=await this.client.sadd(Z,...J),Y=Date.now()-G;return this.logSlow("SADD",Z,Y,{membersCount:J.length}),X}catch(Z){return j.error({err:Z,msg:"Redis sadd \u9519\u8BEF"}),0}}async sismember($,J){try{let Z=`${this.prefix}${$}`,G=Date.now(),X=await this.client.sismember(Z,J),Y=Date.now()-G;return this.logSlow("SISMEMBER",Z,Y),X}catch(Z){return j.error({err:Z,msg:"Redis sismember \u9519\u8BEF"}),!1}}async scard($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.scard(J),X=Date.now()-Z;return this.logSlow("SCARD",J,X),G}catch(J){return j.error({err:J,msg:"Redis scard \u9519\u8BEF"}),0}}async smembers($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.smembers(J),X=Date.now()-Z;return this.logSlow("SMEMBERS",J,X),G}catch(J){return j.error({err:J,msg:"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,G)=>Z+G,0)}catch(J){return j.error({err:J,msg:"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 j.error({err:J,msg:"Redis sismemberBatch \u9519\u8BEF"}),$.map(()=>!1)}}async del($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.del(J),X=Date.now()-Z;return this.logSlow("DEL",J,X),G}catch(J){return j.error({err:J,msg:"Redis del \u9519\u8BEF"}),0}}async delBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>{let G=`${this.prefix}${Z}`;return this.client.del(G)}))).reduce((Z,G)=>Z+G,0)}catch(J){return j.error({err:J,msg:"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 j.error({err:J,msg:"Redis setBatch \u9519\u8BEF"}),0}}async getBatch($){if($.length===0)return[];try{return await Promise.all($.map((Z)=>this.getObject(Z)))}catch(J){return j.error({err:J,msg:"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 j.error({err:J,msg:"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 j.error({err:J,msg:"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 j.error({err:$,msg:"Redis ping \u9519\u8BEF"}),$}}}var d8={name:"redis",enable:!0,deps:["logger"],async handler($){let J=$.config?.nodeEnv,Z=$.config?.redis?.prefix;try{return z$.getRedis(),new wG(Z)}catch(G){throw j.error({env:J,err:G,msg:"Redis \u521D\u59CB\u5316\u5931\u8D25"}),G}}},FW=d8;function s8($,J={},Z={}){return{code:0,msg:$,data:J,...Z}}function o8($,J=null,Z={}){return{code:1,msg:$,data:J,...Z}}function l8($,J,Z={}){let{status:G=200,contentType:X,headers:Y={}}=Z,H=X,U;if(typeof J==="string"){if(U=J,!H)H=J.trim().startsWith("<")?"application/xml":"text/plain"}else U=JSON.stringify(J),H=H||"application/json";let z={...$.corsHeaders,"Content-Type":H,...Y};return new Response(U,{status:G,headers:z})}var r8={name:"tool",enable:!0,deps:[],handler:()=>{return{Yes:s8,No:o8,Raw:l8}}},RW=r8;n0();function IW($,J){let Z=J.name,G=i(J)?Object.keys(J):[];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,customKeys:G}}function qW(){let $=[],J=[AW,FW,SY,PY,RW,BY,_W,LY];for(let Z of J)$.push(IW("plugin",Z));return $}function jW(){let $=[],J=[HY,QY,FY,jY,RY];for(let Z of J)$.push(IW("hook",Z));return $}j$();FJ();n0();import{existsSync as i8}from"fs";function t8($){let J=$.split("/").filter(Boolean),Z=J.indexOf("@befly-addon");if(Z<0)return null;let G=J[Z+1];if(typeof G!=="string"||G.trim()==="")return null;return G}function a8($){let J=$.split("/").filter(Boolean),Z=J.lastIndexOf("addons");if(Z<0)return null;let G=J[Z+1];if(typeof G!=="string"||G.trim()==="")return null;return G}async function K$($,J,Z,G){if(!i8($))return[];let X=C$($),Y=new Bun.Glob(G),H=[];try{let U=await Y.scan({cwd:$,onlyFiles:!0,absolute:!0,followSymlinks:!0});for await(let z of U){if(z.endsWith(".d.ts"))continue;let O=C$(z),_=JJ(O).name,I=vZ(X,O),B=JJ(I),S=B.dir?m(B.dir,B.name):B.name;if(_.startsWith("_"))continue;if(S.split("/").some((N)=>N.startsWith("_")))continue;let C=await I$(O,{}),T=A$(_),E="",D="";if(J==="core")E="",D=_;else if(J==="app")D=`app_${T}`;else{let N=t8(O)||a8(O);if(!N)throw Error(`scanFiles addon moduleName \u89E3\u6790\u5931\u8D25\uFF1A\u672A\u627E\u5230 @befly-addon/<addon>/ \u6BB5\u843D\uFF1A${O}`);E=N,D=`addon_${A$(E)}_${T}`}let w={source:J,type:Z,sourceName:J==="core"?"\u6838\u5FC3":J==="addon"?"\u7EC4\u4EF6":"\u9879\u76EE",filePath:O,relativePath:S,fileName:_,moduleName:D,addonName:E,fileBaseName:JJ(O).base,fileDir:$,customKeys:i(C)?Object.keys(C):[]};if(Z==="table"){w.content=C,H.push(w);continue}if(Z==="api")w.auth=!0,w.rawBody=!1,w.method="POST",w.fields={},w.required=[];if(Z==="plugin"||Z==="hook")w.deps=[],w.name="",w.handler=null;if(sG(C,(N,p)=>{w[p]=N}),Z==="api")w.routePrefix=J==="app"?"/app":`/addon/${E}`,w.path=`/api${w.routePrefix}/${S}`;H.push(w)}}catch(U){let z=Error(`scanFiles failed: source=${J} type=${Z} dir=${X} pattern=${G}`);throw z.cause=U,z}return H}var PW=async()=>{let $=[],J=[],Z=[],G=[],X=await WY();G.push(...await K$(m(d0,"tables"),"app","table","*.json"));for(let Y of X)G.push(...await K$(m(Y.fullPath,"tables"),"addon","table","*.json"));J.push(...qW()),J.push(...await K$(m(d0,"plugins"),"app","plugin","*.{ts,js}"));for(let Y of X)J.push(...await K$(m(Y.fullPath,"plugins"),"addon","plugin","*.{ts,js}"));Z.push(...jW()),Z.push(...await K$(m(d0,"hooks"),"app","hook","*.{ts,js}"));for(let Y of X)Z.push(...await K$(m(Y.fullPath,"hooks"),"addon","hook","*.{ts,js}"));$.push(...await K$(m(d0,"apis"),"app","api","**/*.{ts,js}"));for(let Y of X)$.push(...await K$(m(Y.fullPath,"apis"),"addon","api","**/*.{ts,js}"));return{hooks:Z,plugins:J,apis:$,tables:G,addons:X}};class e8{apis=new Map;plugins=[];hooks=[];context={};config=null;async start($={}){try{let J=Bun.nanoseconds();this.config=await UX($.NODE_ENV||"development"),this.context.config=this.config,this.context.env=$;let{apis:Z,tables:G,plugins:X,hooks:Y,addons:H}=await PW();this.context.addons=H,await VX(Z),await EX(G),await BX(X),await OX(Y);let U=await jX(H);if(await z$.connect({db:this.config.db||{},redis:this.config.redis||{}}),this.plugins=await DX(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 SJ(this.context,G),await gX(this.context,Z),await pX(this.context,U);let z=this.config.devEmail,O=this.config.devPassword;if(typeof z==="string"&&z.length>0&&typeof O==="string"&&O.length>0)await bX(this.context,{devEmail:z,devPassword:O});else j.debug("\u8DF3\u8FC7 syncDev\uFF1A\u672A\u914D\u7F6E devEmail/devPassword");await hX(this.context),this.hooks=await vX(Y),this.apis=await NX(Z);let _=yX(this.apis,this.hooks,this.context),I=fX(this.config.cors),B=typeof this.config.appPort==="number"?this.config.appPort:3000,S=typeof this.config.appHost==="string"&&this.config.appHost.length>0?this.config.appHost:"0.0.0.0",C=Bun.serve({port:B,hostname:S,development:this.config.nodeEnv==="development",idleTimeout:30,fetch:async(N,p)=>{let v=new URL(N.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 _(N,p);return I(N)},error:(N)=>{if(j.error({err:N,msg:"\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:N.message,stack:N.stack},{status:200});return Response.json({code:1,msg:"\u5185\u90E8\u670D\u52A1\u5668\u9519\u8BEF"},{status:200})}}),T=XY(J),E=YY($),D=E.role==="primary"?"\u4E3B\u8FDB\u7A0B":`\u5DE5\u4F5C\u8FDB\u7A0B #${E.instanceId}`,w=E.env==="standalone"?"":` [${E.env}]`;return j.info(`${this.config.appName} \u542F\u52A8\u6210\u529F! (${D}${w})`),j.info(`\u670D\u52A1\u5668\u542F\u52A8\u8017\u65F6: ${T}`),j.info(`\u670D\u52A1\u5668\u76D1\u542C\u5730\u5740: ${C.url}`),C}catch(J){j.error({err:J,msg:"\u9879\u76EE\u542F\u52A8\u5931\u8D25"});try{await j.flush()}catch{}try{await j.shutdown()}catch{}if(J instanceof Error)throw J;throw Error(String(J))}}}export{e8 as Befly};