befly 3.13.2 → 3.13.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/befly.js +8 -6
- package/dist/befly.min.js +7 -7
- package/dist/lib/cacheKeys.d.ts +1 -1
- package/dist/lib/cacheKeys.js +1 -1
- package/dist/lib/connect.js +1 -1
- package/dist/plugins/config.js +2 -2
- package/dist/plugins/db.js +3 -2
- package/dist/plugins/redis.js +2 -1
- package/package.json +2 -2
package/dist/befly.min.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var DW=Object.create;var{getPrototypeOf:kW,defineProperty:rX,getOwnPropertyNames:yW}=Object;var xW=Object.prototype.hasOwnProperty;var fW=($,J,Z)=>{Z=$!=null?DW(kW($)):{};let X=J||!$||!$.__esModule?rX(Z,"default",{value:$,enumerable:!0}):Z;for(let Y of yW($))if(!xW.call(X,Y))rX(X,Y,{get:()=>$[Y],enumerable:!0});return X};var s=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var _$=($,J)=>()=>($&&(J=$($=0)),J);var A$=import.meta.require;function o($){if(typeof $!=="object"||$===null)return!1;let J=Object.getPrototypeOf($);return J===Object.prototype||J===null}function D$($,J,Z,X){if(typeof $!=="number")return J;if(!Number.isFinite($))return J;let Y=Math.floor($);if(Y<Z)return J;if(Y>X)return X;return Y}function OJ($){if($===null||$===void 0)return!0;if(typeof $==="string")return $.trim().length===0;if(typeof $==="number")return $===0||Number.isNaN($);if(typeof $==="boolean")return $===!1;if(Array.isArray($))return $.length===0;if($ instanceof Map||$ instanceof Set)return $.size===0;if(o($))return Object.keys($).length===0;return!1}function tX($,J){if(typeof J!=="function")return;if(!o($))return;for(let Z of Object.keys($))J($[Z],Z)}function cW($){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 pW($){if($.length===0)return $;return $[0].toUpperCase()+$.slice(1)}function K$($){let J=cW($);if(J.length===0)return"";let Z=J[0].toLowerCase(),X=J.slice(1).map((Y)=>pW(Y.toLowerCase()));return[Z,...X].join("")}function uW($){return String($).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").trim()}function u($){let J=uW($);if(J.length===0)return"";return J.split(/\s+/).filter((Z)=>Z.length>0).map((Z)=>Z.toLowerCase()).join("_")}function qZ($,J){if(!J)return $;let Z=J.split("."),X=$;for(let Y of Z){if(X===null||X===void 0)return;if(typeof X!=="object")return;X=X[Y]}return X}function PZ($,J,Z){let X=J.split(".");for(let G of X)if(!G)return;let Y=$;for(let G=0;G<X.length;G++){let H=X[G];if(G===X.length-1){Y[H]=Z;return}let V=Y[H];if(!o(V))Y[H]={};Y=Y[H]}}function b($,J){if(!o($))return{};let Z=new Set(Array.isArray(J)?J:[]),X={};for(let[Y,G]of Object.entries($)){if(Z.has(Y))continue;X[Y]=G}return X}function eX($,J){let Z={};if(!Array.isArray($)||typeof J!=="function")return Z;for(let X of $){let Y=J(X);if(typeof Y!=="string"||Y==="")continue;Z[Y]=X}return Z}function $1(){return Date.now().toString(36)+Math.random().toString(36).slice(2,7)}var RZ=($)=>{if(!$||!o($))return $;let J={};for(let[Z,X]of Object.entries($)){let Y=K$(Z);J[Y]=X}return J},aX=($)=>{if(!$||!o($))return $;let J={};for(let[Z,X]of Object.entries($)){let Y=u(Z);J[Y]=X}return J},IZ=($)=>{if(!$||!Array.isArray($))return $;return $.map((J)=>RZ(J))},_J=($,J)=>{if(!$||!o($)&&!Array.isArray($))return{};let Z={};for(let X of J)if(X in $)Z[X]=$[X];return Z};var m0=()=>{};function LZ($,J="dateTime"){let Z=$.getFullYear(),X=$.getMonth()+1,Y=$.getDate(),G=$.getHours(),H=$.getMinutes(),z=$.getSeconds(),V=X<10?`0${X}`:String(X),O=Y<10?`0${Y}`:String(Y),F=G<10?`0${G}`:String(G),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`${F}:${I}:${B}`;return`${Z}-${V}-${O} ${F}:${I}:${B}`}function EZ($){let J=[];for(let Y of $.builtinPatterns){let G=String(Y).trim();if(G.length>0)J.push(G.toLowerCase())}if(Array.isArray($.userPatterns))for(let Y of $.userPatterns){let G=String(Y).trim();if(G.length>0)J.push(G.toLowerCase())}let Z=new Set,X=[];for(let Y of J){if(!Y.includes("*")){Z.add(Y);continue}let G=Y.replace(/\*+/g,"").trim();if(!G)continue;X.push(G)}return{exactSet:Z,contains:X}}function wZ($,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 AJ($,J){if($.length<=J)return $;return $.slice(0,J)}function G1($,J){let Z={name:$.name||"Error",message:AJ($.message||"",J.maxStringLen)};if(typeof $.stack==="string")Z.stack=AJ($.stack,J.maxStringLen);return Z}function lW($,J,Z){if(typeof $==="string")return $;if($ instanceof Error)try{return JSON.stringify(G1($,J))}catch{return`${$.name||"Error"}: ${$.message||""}`}if($&&typeof $==="object"){if(Z.has($))return"[Circular]"}try{let X=Z;return JSON.stringify($,(G,H)=>{if(G&&wZ(G,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 SZ($,J,Z){let X=lW($,J,Z);return AJ(X,J.maxStringLen)}function CZ($,J,Z,X,Y){if($===null||$===void 0)return $;if(typeof $==="string")return AJ($,J.maxStringLen);if(typeof $==="number"||typeof $==="boolean"||typeof $==="bigint")return $;if($ instanceof Error)return G1($,J);let G=Array.isArray($),H=o($);if(!G&&!H)return SZ($,J,Y);if(Y.has($))return"[Circular]";if(X>=J.sanitizeDepth)return SZ($,J,Y);if(Z.nodes>=J.sanitizeNodes)return SZ($,J,Y);if(Y.add($),Z.nodes=Z.nodes+1,G){let I=$,B=[],L=I.length>J.maxArrayItems?J.maxArrayItems:I.length;for(let C=0;C<L;C++)B[C]=CZ(I[C],J,Z,X+1,Y);return B}let z=$,V={},O=Object.entries(z),F=O.length>J.sanitizeObjectKeys?J.sanitizeObjectKeys:O.length;for(let I=0;I<F;I++){let B=O[I][0],L=O[I][1];if(wZ(B,J.sensitiveKeyMatcher)){V[B]="[MASKED]";continue}V[B]=CZ(L,J,Z,X+1,Y)}return V}function TZ($,J){let Z=new WeakSet,X={nodes:0},Y={};for(let[G,H]of Object.entries($)){if(wZ(G,J.sensitiveKeyMatcher)){Y[G]="[MASKED]";continue}Y[G]=CZ(H,J,X,0,Z)}return Y}var W1=_$(()=>{m0()});import{AsyncLocalStorage as rW}from"async_hooks";function H1($,J){return vZ.run($,J)}function Q1(){let $=vZ.getStore();if(!$)return null;return $}function z1($,J,Z,X){let Y=vZ.getStore();if(!Y)return;Y.userId=$,Y.roleCode=J,Y.nickname=Z,Y.roleType=X}var vZ;var KJ=_$(()=>{vZ=new rW});import{createWriteStream as iW,existsSync as tW,mkdirSync as aW}from"fs";import{stat as eW}from"fs/promises";import{hostname as $H}from"os";import{isAbsolute as JH,join as ZH,resolve as XH}from"path";function RJ($){try{process.stderr.write(`${$}
|
|
3
|
-
`)}catch{}}function WH($,J){let Z=[],X=0;while($.length>0){let Y=$[0],G=Buffer.byteLength(Y);if(Z.length>0&&X+G>J)break;Z.push(Y),X=X+G,$.shift()}return{chunk:Z.join(""),bytes:X}}class kZ{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=WH(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 HH($){let J=()=>{return $==="stderr"?process.stderr:process.stdout},Z=new kZ({maxBufferBytes:10485760,flushDelayMs:10,maxBatchBytes:65536,writeChunk:async(X)=>{try{let Y=J();if(!Y.write(X))await new Promise((H)=>{Y.once("drain",()=>H())});return!0}catch(Y){return RJ(`[Logger] stream sink error: ${Y?.message||Y}`),!1}}});return{enqueue(X){Z.enqueue(X)},async flushNow(){await Z.flushNow()},async shutdown(){await Z.shutdown()}}}class NZ{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 kZ({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((Y)=>{this.stream.once("drain",()=>Y())});return this.streamSizeBytes=this.streamSizeBytes+Z,!0}catch(X){return RJ(`[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=iW($,{flags:"a"}),this.stream.on("error",(J)=>{RJ(`[Logger] file sink error (${this.prefix}): ${J?.message||J}`),this.disabled=!0,this.closeStream()})}catch(J){RJ(`[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 ZH(A1(),X)}async ensureStreamReady($){let J=LZ(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 Y=await eW(Z);X=typeof Y.size==="number"?Y.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 QH(){if(B$)return;let $=[];if(X$)$.push({flush:()=>X$?X$.flushNow():Promise.resolve()});if(Y$)$.push({flush:()=>Y$?Y$.flushNow():Promise.resolve()});if(G$)$.push({flush:()=>G$?G$.flushNow():Promise.resolve()});for(let J of $)try{await J.flush()}catch{}}async function _1(){if(B$)return;let $=M$,J=R$,Z=X$,X=Y$,Y=G$,G=[];if(Z)G.push({shutdown:()=>Z.shutdown()});if(X)G.push({shutdown:()=>X.shutdown()});if(Y)G.push({shutdown:()=>Y.shutdown()});for(let H of G)try{await H.shutdown()}catch{}if(X$===Z)X$=null;if(Y$===X)Y$=null;if(G$===Y)G$=null;if(M$===$)M$=null;if(R$===J)R$=null}function A1(){let $=
|
|
3
|
+
`)}catch{}}function WH($,J){let Z=[],X=0;while($.length>0){let Y=$[0],G=Buffer.byteLength(Y);if(Z.length>0&&X+G>J)break;Z.push(Y),X=X+G,$.shift()}return{chunk:Z.join(""),bytes:X}}class kZ{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=WH(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 HH($){let J=()=>{return $==="stderr"?process.stderr:process.stdout},Z=new kZ({maxBufferBytes:10485760,flushDelayMs:10,maxBatchBytes:65536,writeChunk:async(X)=>{try{let Y=J();if(!Y.write(X))await new Promise((H)=>{Y.once("drain",()=>H())});return!0}catch(Y){return RJ(`[Logger] stream sink error: ${Y?.message||Y}`),!1}}});return{enqueue(X){Z.enqueue(X)},async flushNow(){await Z.flushNow()},async shutdown(){await Z.shutdown()}}}class NZ{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 kZ({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((Y)=>{this.stream.once("drain",()=>Y())});return this.streamSizeBytes=this.streamSizeBytes+Z,!0}catch(X){return RJ(`[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=iW($,{flags:"a"}),this.stream.on("error",(J)=>{RJ(`[Logger] file sink error (${this.prefix}): ${J?.message||J}`),this.disabled=!0,this.closeStream()})}catch(J){RJ(`[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 ZH(A1(),X)}async ensureStreamReady($){let J=LZ(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 Y=await eW(Z);X=typeof Y.size==="number"?Y.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 QH(){if(B$)return;let $=[];if(X$)$.push({flush:()=>X$?X$.flushNow():Promise.resolve()});if(Y$)$.push({flush:()=>Y$?Y$.flushNow():Promise.resolve()});if(G$)$.push({flush:()=>G$?G$.flushNow():Promise.resolve()});for(let J of $)try{await J.flush()}catch{}}async function _1(){if(B$)return;let $=M$,J=R$,Z=X$,X=Y$,Y=G$,G=[];if(Z)G.push({shutdown:()=>Z.shutdown()});if(X)G.push({shutdown:()=>X.shutdown()});if(Y)G.push({shutdown:()=>Y.shutdown()});for(let H of G)try{await H.shutdown()}catch{}if(X$===Z)X$=null;if(Y$===X)Y$=null;if(G$===Y)G$=null;if(M$===$)M$=null;if(R$===J)R$=null}function A1(){let $=d0.dir||"./logs";if(JH($))return $;return XH(YH,$)}function zH(){let $=A1();try{if(!tW($))aW($,{recursive:!0})}catch(J){throw Error(`\u521B\u5EFA logs \u76EE\u5F55\u5931\u8D25: ${$}. ${J?.message||J}`)}}function UH($){_1(),d0=Object.assign({debug:0,dir:"./logs",console:1,maxSize:20},$);{let J=d0.maxSize,Z=typeof J==="number"&&Number.isFinite(J)?J:20;if(Z<10)Z=10;if(Z>100)Z=100;d0.maxSize=Z}M$=null,R$=null,X$=null,Y$=null,G$=null,DZ={maxStringLen:D$(d0.maxStringLen,100,20,200000),maxArrayItems:D$(d0.maxArrayItems,100,10,5000),sanitizeDepth:D$(d0.sanitizeDepth,3,1,10),sanitizeNodes:D$(d0.sanitizeNodes,500,50,20000),sanitizeObjectKeys:D$(d0.sanitizeObjectKeys,100,10,5000),sensitiveKeyMatcher:EZ({builtinPatterns:O1,userPatterns:d0.excludeFields})}}function VH($){B$=$}function t$($){if(B$)return B$;if($==="app"){if(M$)return M$}else if(R$)return R$;zH();let J=typeof d0.maxSize==="number"?d0.maxSize:20,Z=Math.floor(J*1024*1024);if($==="app"){if(!X$)X$=new NZ({prefix:"app",maxFileBytes:Z});if(d0.console===1&&!G$)G$=HH("stdout");return M$=V1({fileSink:X$,consoleSink:d0.console===1?G$:null}),M$}if(!Y$)Y$=new NZ({prefix:"error",maxFileBytes:Z});return R$=V1({fileSink:Y$,consoleSink:null}),R$}function OH($,J){let Z=Date.now(),X={level:$,time:Z,timeFormat:LZ(new Date(Z)),pid:process.pid,hostname:GH};if(J&&o(J)){let Y=Object.assign({},J,X);if(J.msg!==void 0)Y.msg=J.msg;else if(Y.msg===void 0)Y.msg="";return`${U1(Y)}
|
|
4
4
|
`}if(X.msg===void 0)X.msg="";return`${U1(X)}
|
|
5
|
-
`}function U1($){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 V1($){let{fileSink:J,consoleSink:Z}=$,X=(Y,G)=>{if(Y==="debug"&&n0.debug!==1)return;let H=TZ(G,DZ),z=OH(Y,H);if(J.enqueue(z),Z)Z.enqueue(z)};return{info(Y){X("info",Y)},warn(Y){X("warn",Y)},error(Y){X("error",Y)},debug(Y){X("debug",Y)}}}function _H(){let $=Q1();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 AH($,J){let Z={};for(let[Y,G]of Object.entries($))Z[Y]=G;let X=["requestId","method","route","ip","now","durationSinceNowMs","userId","roleCode","nickname","roleType"];for(let Y of X)if(Z[Y]===void 0)Z[Y]=J[Y];return Z}function FJ($){if(o($))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=_H();if(!J)return $;return AH($,J)}class K1{maybeSanitizeForMock($){if(!B$)return $;return TZ($,DZ)}info($){let J=MJ(FJ($)),Z=this.maybeSanitizeForMock(J);return t$("app").info(Z)}warn($){let J=MJ(FJ($)),Z=this.maybeSanitizeForMock(J);return t$("app").warn(Z)}error($){let J=MJ(FJ($)),Z=this.maybeSanitizeForMock(J),X=t$("app").error(Z);if(B$)return X;return t$("error").error(Z),X}debug($){if(n0.debug!==1)return;let J=MJ(FJ($)),Z=this.maybeSanitizeForMock(J);return t$("app").debug(Z)}async flush(){await QH()}configure($){UH($)}setMock($){VH($)}async shutdown(){await _1()}}var YH,O1,DZ,GH,M$=null,R$=null,B$=null,X$=null,Y$=null,G$=null,n0,P;var a=_$(()=>{W1();m0();KJ();YH=process.cwd(),O1=["*password*","pass","pwd","*token*","access_token","refresh_token","accessToken","refreshToken","authorization","cookie","set-cookie","*secret*","apiKey","api_key","privateKey","private_key"],DZ={maxStringLen:100,maxArrayItems:100,sanitizeDepth:3,sanitizeNodes:500,sanitizeObjectKeys:100,sensitiveKeyMatcher:EZ({builtinPatterns:O1,userPatterns:[]})},GH=(()=>{try{return $H()}catch{return"unknown"}})(),n0={debug:0,dir:"./logs",console:1,maxSize:20};P=new K1});function e$($=""){if(!$)return $;return $.replace(/\\/g,"/").replace(KH,(J)=>J.toUpperCase())}function qH(){if(typeof process<"u"&&typeof process.cwd==="function")return process.cwd().replace(/\\/g,"/");return"/"}function yZ($,J){let Z="",X=0,Y=-1,G=0,H=null;for(let z=0;z<=$.length;++z){if(z<$.length)H=$[z];else if(H==="/")break;else H="/";if(H==="/"){if(Y===z-1||G===1);else if(G===2){if(Z.length<2||X!==2||Z[Z.length-1]!=="."||Z[Z.length-2]!=="."){if(Z.length>2){let V=Z.lastIndexOf("/");if(V===-1)Z="",X=0;else Z=Z.slice(0,V),X=Z.length-1-Z.lastIndexOf("/");Y=z,G=0;continue}else if(Z.length>0){Z="",X=0,Y=z,G=0;continue}}if(J)Z+=Z.length>0?"/..":"..",X=2}else{if(Z.length>0)Z+=`/${$.slice(Y+1,z)}`;else Z=$.slice(Y+1,z);X=z-Y-1}Y=z,G=0}else if(H==="."&&G!==-1)++G;else G=-1}return Z}var KH,FH,MH,q1,I1,RH,IH,L$=function($){if($.length===0)return".";$=e$($);let J=$.match(FH),Z=k$($),X=$[$.length-1]==="/";if($=yZ($,!Z),$.length===0){if(Z)return"/";return X?"./":"."}if(X)$+="/";if(q1.test($))$+="/";if(J){if(!Z)return`//./${$}`;return`//${$}`}return Z&&!k$($)?`/${$}`:$},d=function(...$){let J="";for(let Z of $){if(!Z)continue;if(J.length>0){let X=J[J.length-1]==="/",Y=Z[0]==="/";if(X&&Y)J+=Z.slice(1);else J+=X||Y?Z:`/${Z}`}else J+=Z}return L$(J)},a$=function(...$){$=$.map((X)=>e$(X));let J="",Z=!1;for(let X=$.length-1;X>=-1&&!Z;X--){let Y=X>=0?$[X]:qH();if(!Y||Y.length===0)continue;J=`${Y}/${J}`,Z=k$(Y)}if(J=yZ(J,!Z),Z&&!k$(J))return`/${J}`;return J.length>0?J:"."},k$=function($){return MH.test($)},P1=function($){if($==="..")return"";let J=RH.exec(e$($));return J&&J[1]||""},xZ=function($,J){let Z=a$($).replace(I1,"$1").split("/"),X=a$(J).replace(I1,"$1").split("/");if(X[0][1]===":"&&Z[0][1]===":"&&Z[0]!==X[0])return X.join("/");let Y=[...Z];for(let G of Y){if(X[0]!==G)break;Z.shift(),X.shift()}return[...Z.map(()=>".."),...X].join("/")},IJ=function($){let J=e$($).replace(/\/$/,"").split("/").slice(0,-1);if(J.length===1&&q1.test(J[0]))J[0]+="/";return J.join("/")||(k$($)?"/":".")},j1=function($,J){let Z=e$($).split("/"),X="";for(let Y=Z.length-1;Y>=0;Y--){let G=Z[Y];if(G){X=G;break}}return J&&X.endsWith(J)?X.slice(0,-J.length):X},$J=function($){let J=IH.exec($)?.[0]?.replace(/\\/g,"/")||"",Z=j1($),X=P1(Z);return{root:J,dir:IJ($),base:Z,ext:X,name:Z.slice(0,Z.length-X.length)}};var B1=_$(()=>{KH=/^[A-Za-z]:\//;FH=/^[/\\]{2}/,MH=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,q1=/^[A-Za-z]:$/,I1=/^\/([A-Za-z]:)?$/,RH=/.(\.[^./]+|\.)$/,IH=/^[/\\]|^[a-zA-Z]:[/\\]/});var I$=_$(()=>{B1()});import{statSync as PH}from"fs";var qJ=($,J)=>{if(J.isDirectory())return!0;if(!J.isSymbolicLink())return!1;try{return PH(d($,J.name)).isDirectory()}catch{return!1}};var fZ=_$(()=>{I$()});import{existsSync as JJ}from"fs";import{readdir as jH,readFile as L1}from"fs/promises";function BH($){return String($).replace(/_\d+$/,"")}function LH($){let J=/<script\b[^>]*\bsetup\b[^>]*>/i.exec($);if(!J)return null;let Z=J.index+J[0].length,X=$.indexOf("</script>",Z);if(X<0)return null;return $.slice(Z,X)}function SH($){let J=$.match(/definePage\s*\([\s\S]*?meta\s*:\s*\{[\s\S]*?title\s*:\s*(["'`])([^"'`]+)\1/);if(!J)return null;let Z=$.match(/definePage\s*\([\s\S]*?meta\s*:\s*\{[\s\S]*?order\s*:\s*(\d+)/);return{title:J[2],order:Z?Number(Z[1]):void 0}}async function S1($,J,Z=""){if(!JJ($))return[];let X=[],Y=await jH($,{withFileTypes:!0});for(let G of Y){if(!qJ($,G)||G.name==="components")continue;let H=d($,G.name),z=d(H,"index.vue");if(!JJ(z))continue;let V=null;try{let C=await L1(z,"utf-8"),w=LH(C);if(!w){P.warn({path:z,msg:"index.vue \u7F3A\u5C11 <script setup>\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}if(V=SH(w),!V?.title){P.warn({path:z,msg:"index.vue \u672A\u58F0\u660E definePage({ meta: { title, order? } })\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}}catch(C){P.warn({err:C,path:z,msg:"\u8BFB\u53D6 index.vue \u5931\u8D25"});continue}if(!V?.title)continue;let O=BH(G.name),F;if(O==="index")F=Z;else F=Z?`${Z}/${O}`:`/${O}`;let I=J?F?`${J}${F}`:J:F||"/",B={name:V.title,path:I,sort:V.order??999999},L=await S1(H,J,F);if(L.length>0)B.children=L;X.push(B)}return X.sort((G,H)=>(G.sort??999999)-(H.sort??999999)),X}function C1($){let J=$.split("/").filter((Z)=>!!Z);if(J.length<=1)return"";return`/${J.slice(0,-1).join("/")}`}async function E1($){let J=[];for(let X of $){let Y=d(X.fullPath,"adminViews"),G=d(X.fullPath,"views","admin"),H=JJ(Y)?Y:JJ(G)?G:null;if(!H)continue;try{let z=`/${X.source}/${X.name}`,V=await S1(H,z);if(V.length>0)for(let O of V)J.push(O)}catch(z){P.warn({err:z,addon:X.name,addonSource:X.source,dir:H,msg:"\u626B\u63CF addon views \u76EE\u5F55\u5931\u8D25"})}}let Z=d(process.cwd(),"menus.json");if(JJ(Z))try{let X=await L1(Z,"utf-8"),Y=JSON.parse(X);if(Array.isArray(Y)&&Y.length>0)for(let G of Y)J.push(G)}catch(X){P.warn({err:X,msg:"\u8BFB\u53D6\u9879\u76EE menus.json \u5931\u8D25"})}return J}var gZ=_$(()=>{I$();a();fZ()});var c$=s((XU,xY)=>{var yY={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 b$ 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]}}b$.codes=yY;b$.wrap=function($,J,Z){if($ instanceof b$)return $;return new b$(J,Z,{originalError:$})};xY.exports={TokenError:b$,TOKEN_ERROR_CODES:yY}});var $X=s((YU,fY)=>{var{TokenError:W$}=c$();function yQ({complete:$,checkTyp:J},Z){if(Z instanceof Buffer)Z=Z.toString("utf-8");else if(typeof Z!=="string")throw new W$(W$.codes.invalidType,"The token must be a string or a buffer.");let X=Z.indexOf("."),Y=Z.lastIndexOf(".");if(X===-1||X>=Y)throw new W$(W$.codes.malformed,"The token is malformed.");let G=!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});G=!0;let z=Buffer.from(Z.slice(X+1,Y),"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(Y+1),input:Z.slice(0,Y)}:z}catch(H){throw W$.wrap(H,W$.codes.malformed,`The token ${G?"payload":"header"} is not a valid base64url serialized JSON.`)}}fY.exports=function(J={}){let Z=J.complete||!1,X=J.checkTyp;return yQ.bind(null,{complete:Z,checkTyp:X})}});var hY=s((GU,gY)=>{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"};gY.exports=H$});var bY=s((xQ)=>{xQ.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<"u";xQ.SYMBOL_SUPPORT=typeof Symbol<"u"});var JX=s((HU,pY)=>{var cY=bY(),hQ=cY.ARRAY_BUFFER_SUPPORT,bQ=cY.SYMBOL_SUPPORT;pY.exports=function(J,Z){var X,Y,G,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)||hQ&&ArrayBuffer.isView(J)||typeof J==="string"||J.toString()==="[object Arguments]"){for(G=0,H=J.length;G<H;G++)Z(J[G],G);return}if(typeof J.forEach==="function"){J.forEach(Z);return}if(bQ&&Symbol.iterator in J&&typeof J.next!=="function")J=J[Symbol.iterator]();if(typeof J.next==="function"){X=J,G=0;while(z=X.next(),z.done!==!0)Z(z.value,G),G++;return}for(Y in J)if(J.hasOwnProperty(Y))Z(J[Y],Y);return}});var ZX=s((oQ)=>{var cQ=Math.pow(2,8)-1,pQ=Math.pow(2,16)-1,uQ=Math.pow(2,32)-1,mQ=Math.pow(2,7)-1,nQ=Math.pow(2,15)-1,dQ=Math.pow(2,31)-1;oQ.getPointerArray=function($){var J=$-1;if(J<=cQ)return Uint8Array;if(J<=pQ)return Uint16Array;if(J<=uQ)return Uint32Array;throw Error("mnemonist: Pointer Array of size > 4294967295 is not supported.")};oQ.getSignedPointerArray=function($){var J=$-1;if(J<=mQ)return Int8Array;if(J<=nQ)return Int16Array;if(J<=dQ)return Int32Array;return Float64Array};oQ.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 sQ={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};oQ.getMinimalRepresentation=function($,J){var Z=null,X=0,Y,G,H,z,V;for(z=0,V=$.length;z<V;z++)if(H=J?J($[z]):$[z],G=oQ.getNumberType(H),Y=sQ[G.name],Y>X)X=Y,Z=G;return Z};oQ.isTypedArray=function($){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView($)};oQ.concat=function(){var $=0,J,Z,X;for(J=0,X=arguments.length;J<X;J++)$+=arguments[J].length;var Y=new arguments[0].constructor($);for(J=0,Z=0;J<X;J++)Y.set(arguments[J],Z),Z+=arguments[J].length;return Y};oQ.indices=function($){var J=oQ.getPointerArray($),Z=new J($);for(var X=0;X<$;X++)Z[X]=X;return Z}});var sY=s((Zz)=>{var nY=JX(),dY=ZX();function eQ($){return Array.isArray($)||dY.isTypedArray($)}function XX($){if(typeof $.length==="number")return $.length;if(typeof $.size==="number")return $.size;return}function $z($){var J=XX($),Z=typeof J==="number"?Array(J):[],X=0;return nY($,function(Y){Z[X++]=Y}),Z}function Jz($){var J=XX($),Z=typeof J==="number"?dY.getPointerArray(J):Array,X=typeof J==="number"?Array(J):[],Y=typeof J==="number"?new Z(J):[],G=0;return nY($,function(H){X[G]=H,Y[G]=G++}),[X,Y]}Zz.isArrayLike=eQ;Zz.guessLength=XX;Zz.toArray=$z;Zz.toArrayWithIndices=Jz});var GX=s((UU,oY)=>{var YX=hY(),Hz=JX(),Qz=ZX(),zz=sY();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=Qz.getPointerArray(Z);this.forward=new X(Z),this.backward=new X(Z),this.K=typeof $==="function"?new $(Z):Array(Z),this.V=typeof J==="function"?new J(Z):Array(Z),this.size=0,this.head=0,this.tail=0,this.items={}}p0.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}};p0.prototype.splayOnTop=function($){var J=this.head;if(this.head===$)return this;var Z=this.backward[$],X=this.forward[$];if(this.tail===$)this.tail=Z;else this.backward[X]=Z;return this.forward[Z]=X,this.backward[J]=$,this.head=$,this.forward[$]=J,this};p0.prototype.set=function($,J){var Z=this.items[$];if(typeof Z<"u"){this.splayOnTop(Z),this.V[Z]=J;return}if(this.size<this.capacity)Z=this.size++;else Z=this.tail,this.tail=this.backward[Z],delete this.items[this.K[Z]];this.items[$]=Z,this.K[Z]=$,this.V[Z]=J,this.forward[Z]=this.head,this.backward[this.head]=Z,this.head=Z};p0.prototype.setpop=function($,J){var Z=null,X=null,Y=this.items[$];if(typeof Y<"u")return this.splayOnTop(Y),Z=this.V[Y],this.V[Y]=J,{evicted:!1,key:$,value:Z};if(this.size<this.capacity)Y=this.size++;else Y=this.tail,this.tail=this.backward[Y],Z=this.V[Y],X=this.K[Y],delete this.items[X];if(this.items[$]=Y,this.K[Y]=$,this.V[Y]=J,this.forward[Y]=this.head,this.backward[this.head]=Y,this.head=Y,X)return{evicted:!0,key:X,value:Z};else return null};p0.prototype.has=function($){return $ in this.items};p0.prototype.get=function($){var J=this.items[$];if(typeof J>"u")return;return this.splayOnTop(J),this.V[J]};p0.prototype.peek=function($){var J=this.items[$];if(typeof J>"u")return;return this.V[J]};p0.prototype.forEach=function($,J){J=arguments.length>1?J:this;var Z=0,X=this.size,Y=this.head,G=this.K,H=this.V,z=this.forward;while(Z<X)$.call(J,H[Y],G[Y],this),Y=z[Y],Z++};p0.prototype.keys=function(){var $=0,J=this.size,Z=this.head,X=this.K,Y=this.forward;return new YX(function(){if($>=J)return{done:!0};var G=X[Z];if($++,$<J)Z=Y[Z];return{done:!1,value:G}})};p0.prototype.values=function(){var $=0,J=this.size,Z=this.head,X=this.V,Y=this.forward;return new YX(function(){if($>=J)return{done:!0};var G=X[Z];if($++,$<J)Z=Y[Z];return{done:!1,value:G}})};p0.prototype.entries=function(){var $=0,J=this.size,Z=this.head,X=this.K,Y=this.V,G=this.forward;return new YX(function(){if($>=J)return{done:!0};var H=X[Z],z=Y[Z];if($++,$<J)Z=G[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=zz.guessLength($),typeof X!=="number")throw Error("mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.")}else if(arguments.length===2)X=J,J=null,Z=null;var Y=new p0(J,Z,X);return Hz($,function(G,H){Y.set(H,G)}),Y};oY.exports=p0});var HX=s((lY,WX)=>{(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 Y(q,W,U){if(Y.isBN(q))return q;if(this.negative=0,this.words=null,this.length=0,this.red=null,q!==null){if(W==="le"||W==="be")U=W,W=10;this._init(q||0,W||10,U||"be")}}if(typeof $==="object")$.exports=Y;else J.BN=Y;Y.BN=Y,Y.wordSize=26;var G;try{if(typeof window<"u"&&typeof window.Buffer<"u")G=window.Buffer;else G=A$("buffer").Buffer}catch(q){}Y.isBN=function(W){if(W instanceof Y)return!0;return W!==null&&typeof W==="object"&&W.constructor.wordSize===Y.wordSize&&Array.isArray(W.words)},Y.max=function(W,U){if(W.cmp(U)>0)return W;return U},Y.min=function(W,U){if(W.cmp(U)<0)return W;return U},Y.prototype._init=function(W,U,_){if(typeof W==="number")return this._initNumber(W,U,_);if(typeof W==="object")return this._initArray(W,U,_);if(U==="hex")U=16;Z(U===(U|0)&&U>=2&&U<=36),W=W.toString().replace(/\s+/g,"");var A=0;if(W[0]==="-")A++,this.negative=1;if(A<W.length){if(U===16)this._parseHex(W,A,_);else if(this._parseBase(W,U,A),_==="le")this._initArray(this.toArray(),U,_)}},Y.prototype._initNumber=function(W,U,_){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(_!=="le")return;this._initArray(this.toArray(),U,_)},Y.prototype._initArray=function(W,U,_){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 A=0;A<this.length;A++)this.words[A]=0;var R,j,S=0;if(_==="be"){for(A=W.length-1,R=0;A>=0;A-=3)if(j=W[A]|W[A-1]<<8|W[A-2]<<16,this.words[R]|=j<<S&67108863,this.words[R+1]=j>>>26-S&67108863,S+=24,S>=26)S-=26,R++}else if(_==="le"){for(A=0,R=0;A<W.length;A+=3)if(j=W[A]|W[A+1]<<8|W[A+2]<<16,this.words[R]|=j<<S&67108863,this.words[R+1]=j>>>26-S&67108863,S+=24,S>=26)S-=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 _=H(q,U);if(U-1>=W)_|=H(q,U-1)<<4;return _}Y.prototype._parseHex=function(W,U,_){this.length=Math.ceil((W.length-U)/6),this.words=Array(this.length);for(var A=0;A<this.length;A++)this.words[A]=0;var R=0,j=0,S;if(_==="be")for(A=W.length-1;A>=U;A-=2)if(S=z(W,U,A)<<R,this.words[j]|=S&67108863,R>=18)R-=18,j+=1,this.words[j]|=S>>>26;else R+=8;else{var K=W.length-U;for(A=K%2===0?U+1:U;A<W.length;A+=2)if(S=z(W,U,A)<<R,this.words[j]|=S&67108863,R>=18)R-=18,j+=1,this.words[j]|=S>>>26;else R+=8}this.strip()};function V(q,W,U,_){var A=0,R=Math.min(q.length,U);for(var j=W;j<R;j++){var S=q.charCodeAt(j)-48;if(A*=_,S>=49)A+=S-49+10;else if(S>=17)A+=S-17+10;else A+=S}return A}Y.prototype._parseBase=function(W,U,_){this.words=[0],this.length=1;for(var A=0,R=1;R<=67108863;R*=U)A++;A--,R=R/U|0;var j=W.length-_,S=j%A,K=Math.min(j,j-S)+_,Q=0;for(var M=_;M<K;M+=A)if(Q=V(W,M,M+A,U),this.imuln(R),this.words[0]+Q<67108864)this.words[0]+=Q;else this._iaddn(Q);if(S!==0){var k=1;Q=V(W,M,W.length,U);for(M=0;M<S;M++)k*=U;if(this.imuln(k),this.words[0]+Q<67108864)this.words[0]+=Q;else this._iaddn(Q)}this.strip()},Y.prototype.copy=function(W){W.words=Array(this.length);for(var U=0;U<this.length;U++)W.words[U]=this.words[U];W.length=this.length,W.negative=this.negative,W.red=this.red},Y.prototype.clone=function(){var W=new Y(null);return this.copy(W),W},Y.prototype._expand=function(W){while(this.length<W)this.words[this.length++]=0;return this},Y.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},Y.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},Y.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var 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"],F=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],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(Y.prototype.toString=function(W,U){W=W||10,U=U|0||1;var _;if(W===16||W==="hex"){_="";var A=0,R=0;for(var j=0;j<this.length;j++){var S=this.words[j],K=((S<<A|R)&16777215).toString(16);if(R=S>>>24-A&16777215,A+=2,A>=26)A-=26,j--;if(R!==0||j!==this.length-1)_=O[6-K.length]+K+_;else _=K+_}if(R!==0)_=R.toString(16)+_;while(_.length%U!==0)_="0"+_;if(this.negative!==0)_="-"+_;return _}if(W===(W|0)&&W>=2&&W<=36){var Q=F[W],M=I[W];_="";var k=this.clone();k.negative=0;while(!k.isZero()){var y=k.modn(M).toString(W);if(k=k.idivn(M),!k.isZero())_=O[Q-y.length]+y+_;else _=y+_}if(this.isZero())_="0"+_;while(_.length%U!==0)_="0"+_;if(this.negative!==0)_="-"+_;return _}Z(!1,"Base should be between 2 and 36")},Y.prototype.toNumber=function(){var W=this.words[0];if(this.length===2)W+=this.words[1]*67108864;else if(this.length===3&&this.words[2]===1)W+=4503599627370496+this.words[1]*67108864;else if(this.length>2)Z(!1,"Number can only safely store up to 53 bits");return this.negative!==0?-W:W},Y.prototype.toJSON=function(){return this.toString(16)},Y.prototype.toBuffer=function(W,U){return Z(typeof G<"u"),this.toArrayLike(G,W,U)},Y.prototype.toArray=function(W,U){return this.toArrayLike(Array,W,U)},Y.prototype.toArrayLike=function(W,U,_){var A=this.byteLength(),R=_||Math.max(1,A);Z(A<=R,"byte array longer than desired length"),Z(R>0,"Requested array length <= 0"),this.strip();var j=U==="le",S=new W(R),K,Q,M=this.clone();if(!j){for(Q=0;Q<R-A;Q++)S[Q]=0;for(Q=0;!M.isZero();Q++)K=M.andln(255),M.iushrn(8),S[R-Q-1]=K}else{for(Q=0;!M.isZero();Q++)K=M.andln(255),M.iushrn(8),S[Q]=K;for(;Q<R;Q++)S[Q]=0}return S},Math.clz32)Y.prototype._countBits=function(W){return 32-Math.clz32(W)};else Y.prototype._countBits=function(W){var U=W,_=0;if(U>=4096)_+=13,U>>>=13;if(U>=64)_+=7,U>>>=7;if(U>=8)_+=4,U>>>=4;if(U>=2)_+=2,U>>>=2;return _+U};Y.prototype._zeroBits=function(W){if(W===0)return 26;var U=W,_=0;if((U&8191)===0)_+=13,U>>>=13;if((U&127)===0)_+=7,U>>>=7;if((U&15)===0)_+=4,U>>>=4;if((U&3)===0)_+=2,U>>>=2;if((U&1)===0)_++;return _},Y.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 _=U/26|0,A=U%26;W[U]=(q.words[_]&1<<A)>>>A}return W}Y.prototype.zeroBits=function(){if(this.isZero())return 0;var W=0;for(var U=0;U<this.length;U++){var _=this._zeroBits(this.words[U]);if(W+=_,_!==26)break}return W},Y.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},Y.prototype.toTwos=function(W){if(this.negative!==0)return this.abs().inotn(W).iaddn(1);return this.clone()},Y.prototype.fromTwos=function(W){if(this.testn(W-1))return this.notn(W).iaddn(1).ineg();return this.clone()},Y.prototype.isNeg=function(){return this.negative!==0},Y.prototype.neg=function(){return this.clone().ineg()},Y.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},Y.prototype.iuor=function(W){while(this.length<W.length)this.words[this.length++]=0;for(var U=0;U<W.length;U++)this.words[U]=this.words[U]|W.words[U];return this.strip()},Y.prototype.ior=function(W){return Z((this.negative|W.negative)===0),this.iuor(W)},Y.prototype.or=function(W){if(this.length>W.length)return this.clone().ior(W);return W.clone().ior(this)},Y.prototype.uor=function(W){if(this.length>W.length)return this.clone().iuor(W);return W.clone().iuor(this)},Y.prototype.iuand=function(W){var U;if(this.length>W.length)U=W;else U=this;for(var _=0;_<U.length;_++)this.words[_]=this.words[_]&W.words[_];return this.length=U.length,this.strip()},Y.prototype.iand=function(W){return Z((this.negative|W.negative)===0),this.iuand(W)},Y.prototype.and=function(W){if(this.length>W.length)return this.clone().iand(W);return W.clone().iand(this)},Y.prototype.uand=function(W){if(this.length>W.length)return this.clone().iuand(W);return W.clone().iuand(this)},Y.prototype.iuxor=function(W){var U,_;if(this.length>W.length)U=this,_=W;else U=W,_=this;for(var A=0;A<_.length;A++)this.words[A]=U.words[A]^_.words[A];if(this!==U)for(;A<U.length;A++)this.words[A]=U.words[A];return this.length=U.length,this.strip()},Y.prototype.ixor=function(W){return Z((this.negative|W.negative)===0),this.iuxor(W)},Y.prototype.xor=function(W){if(this.length>W.length)return this.clone().ixor(W);return W.clone().ixor(this)},Y.prototype.uxor=function(W){if(this.length>W.length)return this.clone().iuxor(W);return W.clone().iuxor(this)},Y.prototype.inotn=function(W){Z(typeof W==="number"&&W>=0);var U=Math.ceil(W/26)|0,_=W%26;if(this._expand(U),_>0)U--;for(var A=0;A<U;A++)this.words[A]=~this.words[A]&67108863;if(_>0)this.words[A]=~this.words[A]&67108863>>26-_;return this.strip()},Y.prototype.notn=function(W){return this.clone().inotn(W)},Y.prototype.setn=function(W,U){Z(typeof W==="number"&&W>=0);var _=W/26|0,A=W%26;if(this._expand(_+1),U)this.words[_]=this.words[_]|1<<A;else this.words[_]=this.words[_]&~(1<<A);return this.strip()},Y.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 _,A;if(this.length>W.length)_=this,A=W;else _=W,A=this;var R=0;for(var j=0;j<A.length;j++)U=(_.words[j]|0)+(A.words[j]|0)+R,this.words[j]=U&67108863,R=U>>>26;for(;R!==0&&j<_.length;j++)U=(_.words[j]|0)+R,this.words[j]=U&67108863,R=U>>>26;if(this.length=_.length,R!==0)this.words[this.length]=R,this.length++;else if(_!==this)for(;j<_.length;j++)this.words[j]=_.words[j];return this},Y.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)},Y.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 _=this.cmp(W);if(_===0)return this.negative=0,this.length=1,this.words[0]=0,this;var A,R;if(_>0)A=this,R=W;else A=W,R=this;var j=0;for(var S=0;S<R.length;S++)U=(A.words[S]|0)-(R.words[S]|0)+j,j=U>>26,this.words[S]=U&67108863;for(;j!==0&&S<A.length;S++)U=(A.words[S]|0)+j,j=U>>26,this.words[S]=U&67108863;if(j===0&&S<A.length&&A!==this)for(;S<A.length;S++)this.words[S]=A.words[S];if(this.length=Math.max(this.length,S),A!==this)this.negative=1;return this.strip()},Y.prototype.sub=function(W){return this.clone().isub(W)};function L(q,W,U){U.negative=W.negative^q.negative;var _=q.length+W.length|0;U.length=_,_=_-1|0;var A=q.words[0]|0,R=W.words[0]|0,j=A*R,S=j&67108863,K=j/67108864|0;U.words[0]=S;for(var Q=1;Q<_;Q++){var M=K>>>26,k=K&67108863,y=Math.min(Q,W.length-1);for(var x=Math.max(0,Q-q.length+1);x<=y;x++){var p=Q-x|0;A=q.words[p]|0,R=W.words[x]|0,j=A*R+k,M+=j/67108864|0,k=j&67108863}U.words[Q]=k|0,K=M|0}if(K!==0)U.words[Q]=K|0;else U.length--;return U.strip()}var C=function(W,U,_){var A=W.words,R=U.words,j=_.words,S=0,K,Q,M,k=A[0]|0,y=k&8191,x=k>>>13,p=A[1]|0,i=p&8191,e=p>>>13,O$=A[2]|0,$0=O$&8191,Z0=O$>>>13,DX=A[3]|0,W0=DX&8191,H0=DX>>>13,kX=A[4]|0,Q0=kX&8191,z0=kX>>>13,yX=A[5]|0,U0=yX&8191,V0=yX>>>13,xX=A[6]|0,O0=xX&8191,_0=xX>>>13,fX=A[7]|0,A0=fX&8191,K0=fX>>>13,gX=A[8]|0,F0=gX&8191,M0=gX>>>13,hX=A[9]|0,R0=hX&8191,I0=hX>>>13,bX=R[0]|0,q0=bX&8191,P0=bX>>>13,cX=R[1]|0,j0=cX&8191,B0=cX>>>13,pX=R[2]|0,L0=pX&8191,S0=pX>>>13,uX=R[3]|0,C0=uX&8191,E0=uX>>>13,mX=R[4]|0,w0=mX&8191,T0=mX>>>13,nX=R[5]|0,v0=nX&8191,N0=nX>>>13,dX=R[6]|0,D0=dX&8191,k0=dX>>>13,sX=R[7]|0,y0=sX&8191,x0=sX>>>13,oX=R[8]|0,f0=oX&8191,g0=oX>>>13,lX=R[9]|0,h0=lX&8191,b0=lX>>>13;_.negative=W.negative^U.negative,_.length=19,K=Math.imul(y,q0),Q=Math.imul(y,P0),Q=Q+Math.imul(x,q0)|0,M=Math.imul(x,P0);var eJ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(eJ>>>26)|0,eJ&=67108863,K=Math.imul(i,q0),Q=Math.imul(i,P0),Q=Q+Math.imul(e,q0)|0,M=Math.imul(e,P0),K=K+Math.imul(y,j0)|0,Q=Q+Math.imul(y,B0)|0,Q=Q+Math.imul(x,j0)|0,M=M+Math.imul(x,B0)|0;var $Z=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+($Z>>>26)|0,$Z&=67108863,K=Math.imul($0,q0),Q=Math.imul($0,P0),Q=Q+Math.imul(Z0,q0)|0,M=Math.imul(Z0,P0),K=K+Math.imul(i,j0)|0,Q=Q+Math.imul(i,B0)|0,Q=Q+Math.imul(e,j0)|0,M=M+Math.imul(e,B0)|0,K=K+Math.imul(y,L0)|0,Q=Q+Math.imul(y,S0)|0,Q=Q+Math.imul(x,L0)|0,M=M+Math.imul(x,S0)|0;var JZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(JZ>>>26)|0,JZ&=67108863,K=Math.imul(W0,q0),Q=Math.imul(W0,P0),Q=Q+Math.imul(H0,q0)|0,M=Math.imul(H0,P0),K=K+Math.imul($0,j0)|0,Q=Q+Math.imul($0,B0)|0,Q=Q+Math.imul(Z0,j0)|0,M=M+Math.imul(Z0,B0)|0,K=K+Math.imul(i,L0)|0,Q=Q+Math.imul(i,S0)|0,Q=Q+Math.imul(e,L0)|0,M=M+Math.imul(e,S0)|0,K=K+Math.imul(y,C0)|0,Q=Q+Math.imul(y,E0)|0,Q=Q+Math.imul(x,C0)|0,M=M+Math.imul(x,E0)|0;var ZZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(ZZ>>>26)|0,ZZ&=67108863,K=Math.imul(Q0,q0),Q=Math.imul(Q0,P0),Q=Q+Math.imul(z0,q0)|0,M=Math.imul(z0,P0),K=K+Math.imul(W0,j0)|0,Q=Q+Math.imul(W0,B0)|0,Q=Q+Math.imul(H0,j0)|0,M=M+Math.imul(H0,B0)|0,K=K+Math.imul($0,L0)|0,Q=Q+Math.imul($0,S0)|0,Q=Q+Math.imul(Z0,L0)|0,M=M+Math.imul(Z0,S0)|0,K=K+Math.imul(i,C0)|0,Q=Q+Math.imul(i,E0)|0,Q=Q+Math.imul(e,C0)|0,M=M+Math.imul(e,E0)|0,K=K+Math.imul(y,w0)|0,Q=Q+Math.imul(y,T0)|0,Q=Q+Math.imul(x,w0)|0,M=M+Math.imul(x,T0)|0;var XZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(XZ>>>26)|0,XZ&=67108863,K=Math.imul(U0,q0),Q=Math.imul(U0,P0),Q=Q+Math.imul(V0,q0)|0,M=Math.imul(V0,P0),K=K+Math.imul(Q0,j0)|0,Q=Q+Math.imul(Q0,B0)|0,Q=Q+Math.imul(z0,j0)|0,M=M+Math.imul(z0,B0)|0,K=K+Math.imul(W0,L0)|0,Q=Q+Math.imul(W0,S0)|0,Q=Q+Math.imul(H0,L0)|0,M=M+Math.imul(H0,S0)|0,K=K+Math.imul($0,C0)|0,Q=Q+Math.imul($0,E0)|0,Q=Q+Math.imul(Z0,C0)|0,M=M+Math.imul(Z0,E0)|0,K=K+Math.imul(i,w0)|0,Q=Q+Math.imul(i,T0)|0,Q=Q+Math.imul(e,w0)|0,M=M+Math.imul(e,T0)|0,K=K+Math.imul(y,v0)|0,Q=Q+Math.imul(y,N0)|0,Q=Q+Math.imul(x,v0)|0,M=M+Math.imul(x,N0)|0;var YZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(YZ>>>26)|0,YZ&=67108863,K=Math.imul(O0,q0),Q=Math.imul(O0,P0),Q=Q+Math.imul(_0,q0)|0,M=Math.imul(_0,P0),K=K+Math.imul(U0,j0)|0,Q=Q+Math.imul(U0,B0)|0,Q=Q+Math.imul(V0,j0)|0,M=M+Math.imul(V0,B0)|0,K=K+Math.imul(Q0,L0)|0,Q=Q+Math.imul(Q0,S0)|0,Q=Q+Math.imul(z0,L0)|0,M=M+Math.imul(z0,S0)|0,K=K+Math.imul(W0,C0)|0,Q=Q+Math.imul(W0,E0)|0,Q=Q+Math.imul(H0,C0)|0,M=M+Math.imul(H0,E0)|0,K=K+Math.imul($0,w0)|0,Q=Q+Math.imul($0,T0)|0,Q=Q+Math.imul(Z0,w0)|0,M=M+Math.imul(Z0,T0)|0,K=K+Math.imul(i,v0)|0,Q=Q+Math.imul(i,N0)|0,Q=Q+Math.imul(e,v0)|0,M=M+Math.imul(e,N0)|0,K=K+Math.imul(y,D0)|0,Q=Q+Math.imul(y,k0)|0,Q=Q+Math.imul(x,D0)|0,M=M+Math.imul(x,k0)|0;var GZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(GZ>>>26)|0,GZ&=67108863,K=Math.imul(A0,q0),Q=Math.imul(A0,P0),Q=Q+Math.imul(K0,q0)|0,M=Math.imul(K0,P0),K=K+Math.imul(O0,j0)|0,Q=Q+Math.imul(O0,B0)|0,Q=Q+Math.imul(_0,j0)|0,M=M+Math.imul(_0,B0)|0,K=K+Math.imul(U0,L0)|0,Q=Q+Math.imul(U0,S0)|0,Q=Q+Math.imul(V0,L0)|0,M=M+Math.imul(V0,S0)|0,K=K+Math.imul(Q0,C0)|0,Q=Q+Math.imul(Q0,E0)|0,Q=Q+Math.imul(z0,C0)|0,M=M+Math.imul(z0,E0)|0,K=K+Math.imul(W0,w0)|0,Q=Q+Math.imul(W0,T0)|0,Q=Q+Math.imul(H0,w0)|0,M=M+Math.imul(H0,T0)|0,K=K+Math.imul($0,v0)|0,Q=Q+Math.imul($0,N0)|0,Q=Q+Math.imul(Z0,v0)|0,M=M+Math.imul(Z0,N0)|0,K=K+Math.imul(i,D0)|0,Q=Q+Math.imul(i,k0)|0,Q=Q+Math.imul(e,D0)|0,M=M+Math.imul(e,k0)|0,K=K+Math.imul(y,y0)|0,Q=Q+Math.imul(y,x0)|0,Q=Q+Math.imul(x,y0)|0,M=M+Math.imul(x,x0)|0;var WZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(WZ>>>26)|0,WZ&=67108863,K=Math.imul(F0,q0),Q=Math.imul(F0,P0),Q=Q+Math.imul(M0,q0)|0,M=Math.imul(M0,P0),K=K+Math.imul(A0,j0)|0,Q=Q+Math.imul(A0,B0)|0,Q=Q+Math.imul(K0,j0)|0,M=M+Math.imul(K0,B0)|0,K=K+Math.imul(O0,L0)|0,Q=Q+Math.imul(O0,S0)|0,Q=Q+Math.imul(_0,L0)|0,M=M+Math.imul(_0,S0)|0,K=K+Math.imul(U0,C0)|0,Q=Q+Math.imul(U0,E0)|0,Q=Q+Math.imul(V0,C0)|0,M=M+Math.imul(V0,E0)|0,K=K+Math.imul(Q0,w0)|0,Q=Q+Math.imul(Q0,T0)|0,Q=Q+Math.imul(z0,w0)|0,M=M+Math.imul(z0,T0)|0,K=K+Math.imul(W0,v0)|0,Q=Q+Math.imul(W0,N0)|0,Q=Q+Math.imul(H0,v0)|0,M=M+Math.imul(H0,N0)|0,K=K+Math.imul($0,D0)|0,Q=Q+Math.imul($0,k0)|0,Q=Q+Math.imul(Z0,D0)|0,M=M+Math.imul(Z0,k0)|0,K=K+Math.imul(i,y0)|0,Q=Q+Math.imul(i,x0)|0,Q=Q+Math.imul(e,y0)|0,M=M+Math.imul(e,x0)|0,K=K+Math.imul(y,f0)|0,Q=Q+Math.imul(y,g0)|0,Q=Q+Math.imul(x,f0)|0,M=M+Math.imul(x,g0)|0;var HZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(HZ>>>26)|0,HZ&=67108863,K=Math.imul(R0,q0),Q=Math.imul(R0,P0),Q=Q+Math.imul(I0,q0)|0,M=Math.imul(I0,P0),K=K+Math.imul(F0,j0)|0,Q=Q+Math.imul(F0,B0)|0,Q=Q+Math.imul(M0,j0)|0,M=M+Math.imul(M0,B0)|0,K=K+Math.imul(A0,L0)|0,Q=Q+Math.imul(A0,S0)|0,Q=Q+Math.imul(K0,L0)|0,M=M+Math.imul(K0,S0)|0,K=K+Math.imul(O0,C0)|0,Q=Q+Math.imul(O0,E0)|0,Q=Q+Math.imul(_0,C0)|0,M=M+Math.imul(_0,E0)|0,K=K+Math.imul(U0,w0)|0,Q=Q+Math.imul(U0,T0)|0,Q=Q+Math.imul(V0,w0)|0,M=M+Math.imul(V0,T0)|0,K=K+Math.imul(Q0,v0)|0,Q=Q+Math.imul(Q0,N0)|0,Q=Q+Math.imul(z0,v0)|0,M=M+Math.imul(z0,N0)|0,K=K+Math.imul(W0,D0)|0,Q=Q+Math.imul(W0,k0)|0,Q=Q+Math.imul(H0,D0)|0,M=M+Math.imul(H0,k0)|0,K=K+Math.imul($0,y0)|0,Q=Q+Math.imul($0,x0)|0,Q=Q+Math.imul(Z0,y0)|0,M=M+Math.imul(Z0,x0)|0,K=K+Math.imul(i,f0)|0,Q=Q+Math.imul(i,g0)|0,Q=Q+Math.imul(e,f0)|0,M=M+Math.imul(e,g0)|0,K=K+Math.imul(y,h0)|0,Q=Q+Math.imul(y,b0)|0,Q=Q+Math.imul(x,h0)|0,M=M+Math.imul(x,b0)|0;var QZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(QZ>>>26)|0,QZ&=67108863,K=Math.imul(R0,j0),Q=Math.imul(R0,B0),Q=Q+Math.imul(I0,j0)|0,M=Math.imul(I0,B0),K=K+Math.imul(F0,L0)|0,Q=Q+Math.imul(F0,S0)|0,Q=Q+Math.imul(M0,L0)|0,M=M+Math.imul(M0,S0)|0,K=K+Math.imul(A0,C0)|0,Q=Q+Math.imul(A0,E0)|0,Q=Q+Math.imul(K0,C0)|0,M=M+Math.imul(K0,E0)|0,K=K+Math.imul(O0,w0)|0,Q=Q+Math.imul(O0,T0)|0,Q=Q+Math.imul(_0,w0)|0,M=M+Math.imul(_0,T0)|0,K=K+Math.imul(U0,v0)|0,Q=Q+Math.imul(U0,N0)|0,Q=Q+Math.imul(V0,v0)|0,M=M+Math.imul(V0,N0)|0,K=K+Math.imul(Q0,D0)|0,Q=Q+Math.imul(Q0,k0)|0,Q=Q+Math.imul(z0,D0)|0,M=M+Math.imul(z0,k0)|0,K=K+Math.imul(W0,y0)|0,Q=Q+Math.imul(W0,x0)|0,Q=Q+Math.imul(H0,y0)|0,M=M+Math.imul(H0,x0)|0,K=K+Math.imul($0,f0)|0,Q=Q+Math.imul($0,g0)|0,Q=Q+Math.imul(Z0,f0)|0,M=M+Math.imul(Z0,g0)|0,K=K+Math.imul(i,h0)|0,Q=Q+Math.imul(i,b0)|0,Q=Q+Math.imul(e,h0)|0,M=M+Math.imul(e,b0)|0;var zZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,K=Math.imul(R0,L0),Q=Math.imul(R0,S0),Q=Q+Math.imul(I0,L0)|0,M=Math.imul(I0,S0),K=K+Math.imul(F0,C0)|0,Q=Q+Math.imul(F0,E0)|0,Q=Q+Math.imul(M0,C0)|0,M=M+Math.imul(M0,E0)|0,K=K+Math.imul(A0,w0)|0,Q=Q+Math.imul(A0,T0)|0,Q=Q+Math.imul(K0,w0)|0,M=M+Math.imul(K0,T0)|0,K=K+Math.imul(O0,v0)|0,Q=Q+Math.imul(O0,N0)|0,Q=Q+Math.imul(_0,v0)|0,M=M+Math.imul(_0,N0)|0,K=K+Math.imul(U0,D0)|0,Q=Q+Math.imul(U0,k0)|0,Q=Q+Math.imul(V0,D0)|0,M=M+Math.imul(V0,k0)|0,K=K+Math.imul(Q0,y0)|0,Q=Q+Math.imul(Q0,x0)|0,Q=Q+Math.imul(z0,y0)|0,M=M+Math.imul(z0,x0)|0,K=K+Math.imul(W0,f0)|0,Q=Q+Math.imul(W0,g0)|0,Q=Q+Math.imul(H0,f0)|0,M=M+Math.imul(H0,g0)|0,K=K+Math.imul($0,h0)|0,Q=Q+Math.imul($0,b0)|0,Q=Q+Math.imul(Z0,h0)|0,M=M+Math.imul(Z0,b0)|0;var UZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(UZ>>>26)|0,UZ&=67108863,K=Math.imul(R0,C0),Q=Math.imul(R0,E0),Q=Q+Math.imul(I0,C0)|0,M=Math.imul(I0,E0),K=K+Math.imul(F0,w0)|0,Q=Q+Math.imul(F0,T0)|0,Q=Q+Math.imul(M0,w0)|0,M=M+Math.imul(M0,T0)|0,K=K+Math.imul(A0,v0)|0,Q=Q+Math.imul(A0,N0)|0,Q=Q+Math.imul(K0,v0)|0,M=M+Math.imul(K0,N0)|0,K=K+Math.imul(O0,D0)|0,Q=Q+Math.imul(O0,k0)|0,Q=Q+Math.imul(_0,D0)|0,M=M+Math.imul(_0,k0)|0,K=K+Math.imul(U0,y0)|0,Q=Q+Math.imul(U0,x0)|0,Q=Q+Math.imul(V0,y0)|0,M=M+Math.imul(V0,x0)|0,K=K+Math.imul(Q0,f0)|0,Q=Q+Math.imul(Q0,g0)|0,Q=Q+Math.imul(z0,f0)|0,M=M+Math.imul(z0,g0)|0,K=K+Math.imul(W0,h0)|0,Q=Q+Math.imul(W0,b0)|0,Q=Q+Math.imul(H0,h0)|0,M=M+Math.imul(H0,b0)|0;var VZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(VZ>>>26)|0,VZ&=67108863,K=Math.imul(R0,w0),Q=Math.imul(R0,T0),Q=Q+Math.imul(I0,w0)|0,M=Math.imul(I0,T0),K=K+Math.imul(F0,v0)|0,Q=Q+Math.imul(F0,N0)|0,Q=Q+Math.imul(M0,v0)|0,M=M+Math.imul(M0,N0)|0,K=K+Math.imul(A0,D0)|0,Q=Q+Math.imul(A0,k0)|0,Q=Q+Math.imul(K0,D0)|0,M=M+Math.imul(K0,k0)|0,K=K+Math.imul(O0,y0)|0,Q=Q+Math.imul(O0,x0)|0,Q=Q+Math.imul(_0,y0)|0,M=M+Math.imul(_0,x0)|0,K=K+Math.imul(U0,f0)|0,Q=Q+Math.imul(U0,g0)|0,Q=Q+Math.imul(V0,f0)|0,M=M+Math.imul(V0,g0)|0,K=K+Math.imul(Q0,h0)|0,Q=Q+Math.imul(Q0,b0)|0,Q=Q+Math.imul(z0,h0)|0,M=M+Math.imul(z0,b0)|0;var OZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(OZ>>>26)|0,OZ&=67108863,K=Math.imul(R0,v0),Q=Math.imul(R0,N0),Q=Q+Math.imul(I0,v0)|0,M=Math.imul(I0,N0),K=K+Math.imul(F0,D0)|0,Q=Q+Math.imul(F0,k0)|0,Q=Q+Math.imul(M0,D0)|0,M=M+Math.imul(M0,k0)|0,K=K+Math.imul(A0,y0)|0,Q=Q+Math.imul(A0,x0)|0,Q=Q+Math.imul(K0,y0)|0,M=M+Math.imul(K0,x0)|0,K=K+Math.imul(O0,f0)|0,Q=Q+Math.imul(O0,g0)|0,Q=Q+Math.imul(_0,f0)|0,M=M+Math.imul(_0,g0)|0,K=K+Math.imul(U0,h0)|0,Q=Q+Math.imul(U0,b0)|0,Q=Q+Math.imul(V0,h0)|0,M=M+Math.imul(V0,b0)|0;var _Z=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(_Z>>>26)|0,_Z&=67108863,K=Math.imul(R0,D0),Q=Math.imul(R0,k0),Q=Q+Math.imul(I0,D0)|0,M=Math.imul(I0,k0),K=K+Math.imul(F0,y0)|0,Q=Q+Math.imul(F0,x0)|0,Q=Q+Math.imul(M0,y0)|0,M=M+Math.imul(M0,x0)|0,K=K+Math.imul(A0,f0)|0,Q=Q+Math.imul(A0,g0)|0,Q=Q+Math.imul(K0,f0)|0,M=M+Math.imul(K0,g0)|0,K=K+Math.imul(O0,h0)|0,Q=Q+Math.imul(O0,b0)|0,Q=Q+Math.imul(_0,h0)|0,M=M+Math.imul(_0,b0)|0;var AZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(AZ>>>26)|0,AZ&=67108863,K=Math.imul(R0,y0),Q=Math.imul(R0,x0),Q=Q+Math.imul(I0,y0)|0,M=Math.imul(I0,x0),K=K+Math.imul(F0,f0)|0,Q=Q+Math.imul(F0,g0)|0,Q=Q+Math.imul(M0,f0)|0,M=M+Math.imul(M0,g0)|0,K=K+Math.imul(A0,h0)|0,Q=Q+Math.imul(A0,b0)|0,Q=Q+Math.imul(K0,h0)|0,M=M+Math.imul(K0,b0)|0;var KZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(KZ>>>26)|0,KZ&=67108863,K=Math.imul(R0,f0),Q=Math.imul(R0,g0),Q=Q+Math.imul(I0,f0)|0,M=Math.imul(I0,g0),K=K+Math.imul(F0,h0)|0,Q=Q+Math.imul(F0,b0)|0,Q=Q+Math.imul(M0,h0)|0,M=M+Math.imul(M0,b0)|0;var FZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(FZ>>>26)|0,FZ&=67108863,K=Math.imul(R0,h0),Q=Math.imul(R0,b0),Q=Q+Math.imul(I0,h0)|0,M=Math.imul(I0,b0);var MZ=(S+K|0)+((Q&8191)<<13)|0;if(S=(M+(Q>>>13)|0)+(MZ>>>26)|0,MZ&=67108863,j[0]=eJ,j[1]=$Z,j[2]=JZ,j[3]=ZZ,j[4]=XZ,j[5]=YZ,j[6]=GZ,j[7]=WZ,j[8]=HZ,j[9]=QZ,j[10]=zZ,j[11]=UZ,j[12]=VZ,j[13]=OZ,j[14]=_Z,j[15]=AZ,j[16]=KZ,j[17]=FZ,j[18]=MZ,S!==0)j[19]=S,_.length++;return _};if(!Math.imul)C=L;function w(q,W,U){U.negative=W.negative^q.negative,U.length=q.length+W.length;var _=0,A=0;for(var R=0;R<U.length-1;R++){var j=A;A=0;var S=_&67108863,K=Math.min(R,W.length-1);for(var Q=Math.max(0,R-q.length+1);Q<=K;Q++){var M=R-Q,k=q.words[M]|0,y=W.words[Q]|0,x=k*y,p=x&67108863;j=j+(x/67108864|0)|0,p=p+S|0,S=p&67108863,j=j+(p>>>26)|0,A+=j>>>26,j&=67108863}U.words[R]=S,_=j,j=A}if(_!==0)U.words[R]=_;else U.length--;return U.strip()}function T(q,W,U){var _=new N;return _.mulp(q,W,U)}Y.prototype.mulTo=function(W,U){var _,A=this.length+W.length;if(this.length===10&&W.length===10)_=C(this,W,U);else if(A<63)_=L(this,W,U);else if(A<1024)_=w(this,W,U);else _=T(this,W,U);return _};function N(q,W){this.x=q,this.y=W}N.prototype.makeRBT=function(W){var U=Array(W),_=Y.prototype._countBits(W)-1;for(var A=0;A<W;A++)U[A]=this.revBin(A,_,W);return U},N.prototype.revBin=function(W,U,_){if(W===0||W===_-1)return W;var A=0;for(var R=0;R<U;R++)A|=(W&1)<<U-R-1,W>>=1;return A},N.prototype.permute=function(W,U,_,A,R,j){for(var S=0;S<j;S++)A[S]=U[W[S]],R[S]=_[W[S]]},N.prototype.transform=function(W,U,_,A,R,j){this.permute(j,W,U,_,A,R);for(var S=1;S<R;S<<=1){var K=S<<1,Q=Math.cos(2*Math.PI/K),M=Math.sin(2*Math.PI/K);for(var k=0;k<R;k+=K){var y=Q,x=M;for(var p=0;p<S;p++){var i=_[k+p],e=A[k+p],O$=_[k+p+S],$0=A[k+p+S],Z0=y*O$-x*$0;if($0=y*$0+x*O$,O$=Z0,_[k+p]=i+O$,A[k+p]=e+$0,_[k+p+S]=i-O$,A[k+p+S]=e-$0,p!==K)Z0=Q*y-M*x,x=Q*x+M*y,y=Z0}}}},N.prototype.guessLen13b=function(W,U){var _=Math.max(U,W)|1,A=_&1,R=0;for(_=_/2|0;_;_=_>>>1)R++;return 1<<R+1+A},N.prototype.conjugate=function(W,U,_){if(_<=1)return;for(var A=0;A<_/2;A++){var R=W[A];W[A]=W[_-A-1],W[_-A-1]=R,R=U[A],U[A]=-U[_-A-1],U[_-A-1]=-R}},N.prototype.normalize13b=function(W,U){var _=0;for(var A=0;A<U/2;A++){var R=Math.round(W[2*A+1]/U)*8192+Math.round(W[2*A]/U)+_;if(W[A]=R&67108863,R<67108864)_=0;else _=R/67108864|0}return W},N.prototype.convert13b=function(W,U,_,A){var R=0;for(var j=0;j<U;j++)R=R+(W[j]|0),_[2*j]=R&8191,R=R>>>13,_[2*j+1]=R&8191,R=R>>>13;for(j=2*U;j<A;++j)_[j]=0;Z(R===0),Z((R&-8192)===0)},N.prototype.stub=function(W){var U=Array(W);for(var _=0;_<W;_++)U[_]=0;return U},N.prototype.mulp=function(W,U,_){var A=2*this.guessLen13b(W.length,U.length),R=this.makeRBT(A),j=this.stub(A),S=Array(A),K=Array(A),Q=Array(A),M=Array(A),k=Array(A),y=Array(A),x=_.words;x.length=A,this.convert13b(W.words,W.length,S,A),this.convert13b(U.words,U.length,M,A),this.transform(S,j,K,Q,A,R),this.transform(M,j,k,y,A,R);for(var p=0;p<A;p++){var i=K[p]*k[p]-Q[p]*y[p];Q[p]=K[p]*y[p]+Q[p]*k[p],K[p]=i}return this.conjugate(K,Q,A),this.transform(K,Q,x,j,A,R),this.conjugate(x,j,A),this.normalize13b(x,A),_.negative=W.negative^U.negative,_.length=W.length+U.length,_.strip()},Y.prototype.mul=function(W){var U=new Y(null);return U.words=Array(this.length+W.length),this.mulTo(W,U)},Y.prototype.mulf=function(W){var U=new Y(null);return U.words=Array(this.length+W.length),T(this,W,U)},Y.prototype.imul=function(W){return this.clone().mulTo(W,this)},Y.prototype.imuln=function(W){Z(typeof W==="number"),Z(W<67108864);var U=0;for(var _=0;_<this.length;_++){var A=(this.words[_]|0)*W,R=(A&67108863)+(U&67108863);U>>=26,U+=A/67108864|0,U+=R>>>26,this.words[_]=R&67108863}if(U!==0)this.words[_]=U,this.length++;return this.length=W===0?1:this.length,this},Y.prototype.muln=function(W){return this.clone().imuln(W)},Y.prototype.sqr=function(){return this.mul(this)},Y.prototype.isqr=function(){return this.imul(this.clone())},Y.prototype.pow=function(W){var U=B(W);if(U.length===0)return new Y(1);var _=this;for(var A=0;A<U.length;A++,_=_.sqr())if(U[A]!==0)break;if(++A<U.length)for(var R=_.sqr();A<U.length;A++,R=R.sqr()){if(U[A]===0)continue;_=_.mul(R)}return _},Y.prototype.iushln=function(W){Z(typeof W==="number"&&W>=0);var U=W%26,_=(W-U)/26,A=67108863>>>26-U<<26-U,R;if(U!==0){var j=0;for(R=0;R<this.length;R++){var S=this.words[R]&A,K=(this.words[R]|0)-S<<U;this.words[R]=K|j,j=S>>>26-U}if(j)this.words[R]=j,this.length++}if(_!==0){for(R=this.length-1;R>=0;R--)this.words[R+_]=this.words[R];for(R=0;R<_;R++)this.words[R]=0;this.length+=_}return this.strip()},Y.prototype.ishln=function(W){return Z(this.negative===0),this.iushln(W)},Y.prototype.iushrn=function(W,U,_){Z(typeof W==="number"&&W>=0);var A;if(U)A=(U-U%26)/26;else A=0;var R=W%26,j=Math.min((W-R)/26,this.length),S=67108863^67108863>>>R<<R,K=_;if(A-=j,A=Math.max(0,A),K){for(var Q=0;Q<j;Q++)K.words[Q]=this.words[Q];K.length=j}if(j===0);else if(this.length>j){this.length-=j;for(Q=0;Q<this.length;Q++)this.words[Q]=this.words[Q+j]}else this.words[0]=0,this.length=1;var M=0;for(Q=this.length-1;Q>=0&&(M!==0||Q>=A);Q--){var k=this.words[Q]|0;this.words[Q]=M<<26-R|k>>>R,M=k&S}if(K&&M!==0)K.words[K.length++]=M;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},Y.prototype.ishrn=function(W,U,_){return Z(this.negative===0),this.iushrn(W,U,_)},Y.prototype.shln=function(W){return this.clone().ishln(W)},Y.prototype.ushln=function(W){return this.clone().iushln(W)},Y.prototype.shrn=function(W){return this.clone().ishrn(W)},Y.prototype.ushrn=function(W){return this.clone().iushrn(W)},Y.prototype.testn=function(W){Z(typeof W==="number"&&W>=0);var U=W%26,_=(W-U)/26,A=1<<U;if(this.length<=_)return!1;var R=this.words[_];return!!(R&A)},Y.prototype.imaskn=function(W){Z(typeof W==="number"&&W>=0);var U=W%26,_=(W-U)/26;if(Z(this.negative===0,"imaskn works only with positive numbers"),this.length<=_)return this;if(U!==0)_++;if(this.length=Math.min(_,this.length),U!==0){var A=67108863^67108863>>>U<<U;this.words[this.length-1]&=A}return this.strip()},Y.prototype.maskn=function(W){return this.clone().imaskn(W)},Y.prototype.iaddn=function(W){if(Z(typeof W==="number"),Z(W<67108864),W<0)return this.isubn(-W);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<W)return this.words[0]=W-(this.words[0]|0),this.negative=0,this;return this.negative=0,this.isubn(W),this.negative=1,this}return this._iaddn(W)},Y.prototype._iaddn=function(W){this.words[0]+=W;for(var 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},Y.prototype.isubn=function(W){if(Z(typeof W==="number"),Z(W<67108864),W<0)return this.iaddn(-W);if(this.negative!==0)return this.negative=0,this.iaddn(W),this.negative=1,this;if(this.words[0]-=W,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var U=0;U<this.length&&this.words[U]<0;U++)this.words[U]+=67108864,this.words[U+1]-=1;return this.strip()},Y.prototype.addn=function(W){return this.clone().iaddn(W)},Y.prototype.subn=function(W){return this.clone().isubn(W)},Y.prototype.iabs=function(){return this.negative=0,this},Y.prototype.abs=function(){return this.clone().iabs()},Y.prototype._ishlnsubmul=function(W,U,_){var A=W.length+_,R;this._expand(A);var j,S=0;for(R=0;R<W.length;R++){j=(this.words[R+_]|0)+S;var K=(W.words[R]|0)*U;j-=K&67108863,S=(j>>26)-(K/67108864|0),this.words[R+_]=j&67108863}for(;R<this.length-_;R++)j=(this.words[R+_]|0)+S,S=j>>26,this.words[R+_]=j&67108863;if(S===0)return this.strip();Z(S===-1),S=0;for(R=0;R<this.length;R++)j=-(this.words[R]|0)+S,S=j>>26,this.words[R]=j&67108863;return this.negative=1,this.strip()},Y.prototype._wordDiv=function(W,U){var _=this.length-W.length,A=this.clone(),R=W,j=R.words[R.length-1]|0,S=this._countBits(j);if(_=26-S,_!==0)R=R.ushln(_),A.iushln(_),j=R.words[R.length-1]|0;var K=A.length-R.length,Q;if(U!=="mod"){Q=new Y(null),Q.length=K+1,Q.words=Array(Q.length);for(var M=0;M<Q.length;M++)Q.words[M]=0}var k=A.clone()._ishlnsubmul(R,1,K);if(k.negative===0){if(A=k,Q)Q.words[K]=1}for(var y=K-1;y>=0;y--){var x=(A.words[R.length+y]|0)*67108864+(A.words[R.length+y-1]|0);x=Math.min(x/j|0,67108863),A._ishlnsubmul(R,x,y);while(A.negative!==0)if(x--,A.negative=0,A._ishlnsubmul(R,1,y),!A.isZero())A.negative^=1;if(Q)Q.words[y]=x}if(Q)Q.strip();if(A.strip(),U!=="div"&&_!==0)A.iushrn(_);return{div:Q||null,mod:A}},Y.prototype.divmod=function(W,U,_){if(Z(!W.isZero()),this.isZero())return{div:new Y(0),mod:new Y(0)};var A,R,j;if(this.negative!==0&&W.negative===0){if(j=this.neg().divmod(W,U),U!=="mod")A=j.div.neg();if(U!=="div"){if(R=j.mod.neg(),_&&R.negative!==0)R.iadd(W)}return{div:A,mod:R}}if(this.negative===0&&W.negative!==0){if(j=this.divmod(W.neg(),U),U!=="mod")A=j.div.neg();return{div:A,mod:j.mod}}if((this.negative&W.negative)!==0){if(j=this.neg().divmod(W.neg(),U),U!=="div"){if(R=j.mod.neg(),_&&R.negative!==0)R.isub(W)}return{div:j.div,mod:R}}if(W.length>this.length||this.cmp(W)<0)return{div:new Y(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 Y(this.modn(W.words[0]))};return{div:this.divn(W.words[0]),mod:new Y(this.modn(W.words[0]))}}return this._wordDiv(W,U)},Y.prototype.div=function(W){return this.divmod(W,"div",!1).div},Y.prototype.mod=function(W){return this.divmod(W,"mod",!1).mod},Y.prototype.umod=function(W){return this.divmod(W,"mod",!0).mod},Y.prototype.divRound=function(W){var U=this.divmod(W);if(U.mod.isZero())return U.div;var _=U.div.negative!==0?U.mod.isub(W):U.mod,A=W.ushrn(1),R=W.andln(1),j=_.cmp(A);if(j<0||R===1&&j===0)return U.div;return U.div.negative!==0?U.div.isubn(1):U.div.iaddn(1)},Y.prototype.modn=function(W){Z(W<=67108863);var U=67108864%W,_=0;for(var A=this.length-1;A>=0;A--)_=(U*_+(this.words[A]|0))%W;return _},Y.prototype.idivn=function(W){Z(W<=67108863);var U=0;for(var _=this.length-1;_>=0;_--){var A=(this.words[_]|0)+U*67108864;this.words[_]=A/W|0,U=A%W}return this.strip()},Y.prototype.divn=function(W){return this.clone().idivn(W)},Y.prototype.egcd=function(W){Z(W.negative===0),Z(!W.isZero());var U=this,_=W.clone();if(U.negative!==0)U=U.umod(W);else U=U.clone();var A=new Y(1),R=new Y(0),j=new Y(0),S=new Y(1),K=0;while(U.isEven()&&_.isEven())U.iushrn(1),_.iushrn(1),++K;var Q=_.clone(),M=U.clone();while(!U.isZero()){for(var k=0,y=1;(U.words[0]&y)===0&&k<26;++k,y<<=1);if(k>0){U.iushrn(k);while(k-- >0){if(A.isOdd()||R.isOdd())A.iadd(Q),R.isub(M);A.iushrn(1),R.iushrn(1)}}for(var x=0,p=1;(_.words[0]&p)===0&&x<26;++x,p<<=1);if(x>0){_.iushrn(x);while(x-- >0){if(j.isOdd()||S.isOdd())j.iadd(Q),S.isub(M);j.iushrn(1),S.iushrn(1)}}if(U.cmp(_)>=0)U.isub(_),A.isub(j),R.isub(S);else _.isub(U),j.isub(A),S.isub(R)}return{a:j,b:S,gcd:_.iushln(K)}},Y.prototype._invmp=function(W){Z(W.negative===0),Z(!W.isZero());var U=this,_=W.clone();if(U.negative!==0)U=U.umod(W);else U=U.clone();var A=new Y(1),R=new Y(0),j=_.clone();while(U.cmpn(1)>0&&_.cmpn(1)>0){for(var S=0,K=1;(U.words[0]&K)===0&&S<26;++S,K<<=1);if(S>0){U.iushrn(S);while(S-- >0){if(A.isOdd())A.iadd(j);A.iushrn(1)}}for(var Q=0,M=1;(_.words[0]&M)===0&&Q<26;++Q,M<<=1);if(Q>0){_.iushrn(Q);while(Q-- >0){if(R.isOdd())R.iadd(j);R.iushrn(1)}}if(U.cmp(_)>=0)U.isub(_),A.isub(R);else _.isub(U),R.isub(A)}var k;if(U.cmpn(1)===0)k=A;else k=R;if(k.cmpn(0)<0)k.iadd(W);return k},Y.prototype.gcd=function(W){if(this.isZero())return W.abs();if(W.isZero())return this.abs();var U=this.clone(),_=W.clone();U.negative=0,_.negative=0;for(var A=0;U.isEven()&&_.isEven();A++)U.iushrn(1),_.iushrn(1);do{while(U.isEven())U.iushrn(1);while(_.isEven())_.iushrn(1);var R=U.cmp(_);if(R<0){var j=U;U=_,_=j}else if(R===0||_.cmpn(1)===0)break;U.isub(_)}while(!0);return _.iushln(A)},Y.prototype.invm=function(W){return this.egcd(W).a.umod(W)},Y.prototype.isEven=function(){return(this.words[0]&1)===0},Y.prototype.isOdd=function(){return(this.words[0]&1)===1},Y.prototype.andln=function(W){return this.words[0]&W},Y.prototype.bincn=function(W){Z(typeof W==="number");var U=W%26,_=(W-U)/26,A=1<<U;if(this.length<=_)return this._expand(_+1),this.words[_]|=A,this;var R=A;for(var j=_;R!==0&&j<this.length;j++){var S=this.words[j]|0;S+=R,R=S>>>26,S&=67108863,this.words[j]=S}if(R!==0)this.words[j]=R,this.length++;return this},Y.prototype.isZero=function(){return this.length===1&&this.words[0]===0},Y.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 _;if(this.length>1)_=1;else{if(U)W=-W;Z(W<=67108863,"Number is too big");var A=this.words[0]|0;_=A===W?0:A<W?-1:1}if(this.negative!==0)return-_|0;return _},Y.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},Y.prototype.ucmp=function(W){if(this.length>W.length)return 1;if(this.length<W.length)return-1;var U=0;for(var _=this.length-1;_>=0;_--){var A=this.words[_]|0,R=W.words[_]|0;if(A===R)continue;if(A<R)U=-1;else if(A>R)U=1;break}return U},Y.prototype.gtn=function(W){return this.cmpn(W)===1},Y.prototype.gt=function(W){return this.cmp(W)===1},Y.prototype.gten=function(W){return this.cmpn(W)>=0},Y.prototype.gte=function(W){return this.cmp(W)>=0},Y.prototype.ltn=function(W){return this.cmpn(W)===-1},Y.prototype.lt=function(W){return this.cmp(W)===-1},Y.prototype.lten=function(W){return this.cmpn(W)<=0},Y.prototype.lte=function(W){return this.cmp(W)<=0},Y.prototype.eqn=function(W){return this.cmpn(W)===0},Y.prototype.eq=function(W){return this.cmp(W)===0},Y.red=function(W){return new r(W)},Y.prototype.toRed=function(W){return Z(!this.red,"Already a number in reduction context"),Z(this.negative===0,"red works only with positives"),W.convertTo(this)._forceRed(W)},Y.prototype.fromRed=function(){return Z(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},Y.prototype._forceRed=function(W){return this.red=W,this},Y.prototype.forceRed=function(W){return Z(!this.red,"Already a number in reduction context"),this._forceRed(W)},Y.prototype.redAdd=function(W){return Z(this.red,"redAdd works only with red numbers"),this.red.add(this,W)},Y.prototype.redIAdd=function(W){return Z(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,W)},Y.prototype.redSub=function(W){return Z(this.red,"redSub works only with red numbers"),this.red.sub(this,W)},Y.prototype.redISub=function(W){return Z(this.red,"redISub works only with red numbers"),this.red.isub(this,W)},Y.prototype.redShl=function(W){return Z(this.red,"redShl works only with red numbers"),this.red.shl(this,W)},Y.prototype.redMul=function(W){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,W),this.red.mul(this,W)},Y.prototype.redIMul=function(W){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,W),this.red.imul(this,W)},Y.prototype.redSqr=function(){return Z(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},Y.prototype.redISqr=function(){return Z(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},Y.prototype.redSqrt=function(){return Z(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},Y.prototype.redInvm=function(){return Z(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},Y.prototype.redNeg=function(){return Z(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},Y.prototype.redPow=function(W){return Z(this.red&&!W.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,W)};var E={k256:null,p224:null,p192:null,p25519:null};function D(q,W){this.name=q,this.p=new Y(W,16),this.n=this.p.bitLength(),this.k=new Y(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}D.prototype._tmp=function(){var W=new Y(null);return W.words=Array(Math.ceil(this.n/13)),W},D.prototype.ireduce=function(W){var U=W,_;do this.split(U,this.tmp),U=this.imulK(U),U=U.iadd(this.tmp),_=U.bitLength();while(_>this.n);var A=_<this.n?-1:U.ucmp(this.p);if(A===0)U.words[0]=0,U.length=1;else if(A>0)U.isub(this.p);else if(U.strip!==void 0)U.strip();else U._strip();return U},D.prototype.split=function(W,U){W.iushrn(this.n,0,U)},D.prototype.imulK=function(W){return W.imul(this.k)};function h(){D.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}X(h,D),h.prototype.split=function(W,U){var _=4194303,A=Math.min(W.length,9);for(var R=0;R<A;R++)U.words[R]=W.words[R];if(U.length=A,W.length<=9){W.words[0]=0,W.length=1;return}var j=W.words[9];U.words[U.length++]=j&_;for(R=10;R<W.length;R++){var S=W.words[R]|0;W.words[R-10]=(S&_)<<4|j>>>22,j=S}if(j>>>=22,W.words[R-10]=j,j===0&&W.length>10)W.length-=10;else W.length-=9},h.prototype.imulK=function(W){W.words[W.length]=0,W.words[W.length+1]=0,W.length+=2;var U=0;for(var _=0;_<W.length;_++){var A=W.words[_]|0;U+=A*977,W.words[_]=U&67108863,U=A*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(){D.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}X(v,D);function f(){D.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}X(f,D);function l(){D.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}X(l,D),l.prototype.imulK=function(W){var U=0;for(var _=0;_<W.length;_++){var A=(W.words[_]|0)*19+U,R=A&67108863;A>>>=26,W.words[_]=R,U=A}if(U!==0)W.words[W.length++]=U;return W},Y._prime=function(W){if(E[W])return E[W];var U;if(W==="k256")U=new h;else if(W==="p224")U=new v;else if(W==="p192")U=new f;else if(W==="p25519")U=new l;else throw Error("Unknown prime "+W);return E[W]=U,U};function r(q){if(typeof q==="string"){var W=Y._prime(q);this.m=W.p,this.prime=W}else Z(q.gtn(1),"modulus must be greater than 1"),this.m=q,this.prime=null}r.prototype._verify1=function(W){Z(W.negative===0,"red works only with positives"),Z(W.red,"red works only with red numbers")},r.prototype._verify2=function(W,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")},r.prototype.imod=function(W){if(this.prime)return this.prime.ireduce(W)._forceRed(this);return W.umod(this.m)._forceRed(this)},r.prototype.neg=function(W){if(W.isZero())return W.clone();return this.m.sub(W)._forceRed(this)},r.prototype.add=function(W,U){this._verify2(W,U);var _=W.add(U);if(_.cmp(this.m)>=0)_.isub(this.m);return _._forceRed(this)},r.prototype.iadd=function(W,U){this._verify2(W,U);var _=W.iadd(U);if(_.cmp(this.m)>=0)_.isub(this.m);return _},r.prototype.sub=function(W,U){this._verify2(W,U);var _=W.sub(U);if(_.cmpn(0)<0)_.iadd(this.m);return _._forceRed(this)},r.prototype.isub=function(W,U){this._verify2(W,U);var _=W.isub(U);if(_.cmpn(0)<0)_.iadd(this.m);return _},r.prototype.shl=function(W,U){return this._verify1(W),this.imod(W.ushln(U))},r.prototype.imul=function(W,U){return this._verify2(W,U),this.imod(W.imul(U))},r.prototype.mul=function(W,U){return this._verify2(W,U),this.imod(W.mul(U))},r.prototype.isqr=function(W){return this.imul(W,W.clone())},r.prototype.sqr=function(W){return this.mul(W,W)},r.prototype.sqrt=function(W){if(W.isZero())return W.clone();var U=this.m.andln(3);if(Z(U%2===1),U===3){var _=this.m.add(new Y(1)).iushrn(2);return this.pow(W,_)}var A=this.m.subn(1),R=0;while(!A.isZero()&&A.andln(1)===0)R++,A.iushrn(1);Z(!A.isZero());var j=new Y(1).toRed(this),S=j.redNeg(),K=this.m.subn(1).iushrn(1),Q=this.m.bitLength();Q=new Y(2*Q*Q).toRed(this);while(this.pow(Q,K).cmp(S)!==0)Q.redIAdd(S);var M=this.pow(Q,A),k=this.pow(W,A.addn(1).iushrn(1)),y=this.pow(W,A),x=R;while(y.cmp(j)!==0){var p=y;for(var i=0;p.cmp(j)!==0;i++)p=p.redSqr();Z(i<x);var e=this.pow(M,new Y(1).iushln(x-i-1));k=k.redMul(e),M=e.redSqr(),y=y.redMul(M),x=i}return k},r.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)},r.prototype.pow=function(W,U){if(U.isZero())return new Y(1).toRed(this);if(U.cmpn(1)===0)return W.clone();var _=4,A=Array(1<<_);A[0]=new Y(1).toRed(this),A[1]=W;for(var R=2;R<A.length;R++)A[R]=this.mul(A[R-1],W);var j=A[0],S=0,K=0,Q=U.bitLength()%26;if(Q===0)Q=26;for(R=U.length-1;R>=0;R--){var M=U.words[R];for(var k=Q-1;k>=0;k--){var y=M>>k&1;if(j!==A[0])j=this.sqr(j);if(y===0&&S===0){K=0;continue}if(S<<=1,S|=y,K++,K!==_&&(R!==0||k!==0))continue;j=this.mul(j,A[S]),K=0,S=0}Q=26}return j},r.prototype.convertTo=function(W){var U=W.umod(this.m);return U===W?U.clone():U},r.prototype.convertFrom=function(W){var U=W.clone();return U.red=null,U},Y.mont=function(W){return new u0(W)};function u0(q){if(r.call(this,q),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new Y(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}X(u0,r),u0.prototype.convertTo=function(W){return this.imod(W.ushln(this.shift))},u0.prototype.convertFrom=function(W){var 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 _=W.imul(U),A=_.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),R=_.isub(A).iushrn(this.shift),j=R;if(R.cmp(this.m)>=0)j=R.isub(this.m);else if(R.cmpn(0)<0)j=R.iadd(this.m);return j._forceRed(this)},u0.prototype.mul=function(W,U){if(W.isZero()||U.isZero())return new Y(0)._forceRed(this);var _=W.mul(U),A=_.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),R=_.isub(A).iushrn(this.shift),j=R;if(R.cmp(this.m)>=0)j=R.isub(this.m);else if(R.cmpn(0)<0)j=R.iadd(this.m);return j._forceRed(this)},u0.prototype.invm=function(W){var U=this.imod(W._invmp(this.m).mul(this.r2));return U._forceRed(this)}})(typeof WX>"u"||WX,lY)});var rY=s((VU,QX)=>{if(typeof Object.create==="function")QX.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 QX.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 j$=s((OU,zX)=>{try{if(gJ=A$("util"),typeof gJ.inherits!=="function")throw"";zX.exports=gJ.inherits}catch($){zX.exports=rY()}var gJ});var bJ=s((_U,iY)=>{var hJ=A$("buffer"),p$=hJ.Buffer,t0={},a0;for(a0 in hJ){if(!hJ.hasOwnProperty(a0))continue;if(a0==="SlowBuffer"||a0==="Buffer")continue;t0[a0]=hJ[a0]}var u$=t0.Buffer={};for(a0 in p$){if(!p$.hasOwnProperty(a0))continue;if(a0==="allocUnsafe"||a0==="allocUnsafeSlow")continue;u$[a0]=p$[a0]}t0.Buffer.prototype=p$.prototype;if(!u$.from||u$.from===Uint8Array.from)u$.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 p$($,J,Z)};if(!u$.alloc)u$.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=p$($);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}iY.exports=t0});var cJ=s((Vz)=>{var Uz=j$();function e0($){this._reporterState={obj:null,path:[],options:$||{},errors:[]}}Vz.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 Y=this._reporterState;if(this.exitKey(J),Y.obj!==null)Y.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,Y=J instanceof m$;if(Y)Z=J;else Z=new m$(X.path.map(function(G){return"["+JSON.stringify(G)+"]"}).join(""),J.message||J,J.stack);if(!X.options.partial)throw Z;if(!Y)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)}Uz(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 s$=s((Az)=>{var _z=j$(),pJ=cJ().Reporter,n$=bJ().Buffer;function $$($,J){if(pJ.call(this,J),!n$.isBuffer($)){this.error("Input not Buffer");return}this.base=$,this.offset=0,this.length=$.length}_z($$,pJ);Az.DecoderBuffer=$$;$$.isDecoderBuffer=function(J){if(J instanceof $$)return!0;return typeof J==="object"&&n$.isBuffer(J.base)&&J.constructor.name==="DecoderBuffer"&&typeof J.offset==="number"&&typeof J.length==="number"&&typeof J.save==="function"&&typeof J.restore==="function"&&typeof J.isEmpty==="function"&&typeof J.readUInt8==="function"&&typeof J.skip==="function"&&typeof J.raw==="function"};$$.prototype.save=function(){return{offset:this.offset,reporter:pJ.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,pJ.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 d$($,J){if(Array.isArray($))this.length=0,this.value=$.map(function(Z){if(!d$.isEncoderBuffer(Z))Z=new d$(Z,J);return this.length+=Z.length,Z},this);else if(typeof $==="number"){if(!(0<=$&&$<=255))return J.error("non-byte EncoderBuffer value");this.value=$,this.length=1}else if(typeof $==="string")this.value=$,this.length=n$.byteLength($);else if(n$.isBuffer($))this.value=$,this.length=$.length;else return J.error("Unsupported type: "+typeof $)}Az.EncoderBuffer=d$;d$.isEncoderBuffer=function(J){if(J instanceof d$)return!0;return typeof J==="object"&&J.constructor.name==="EncoderBuffer"&&typeof J.length==="number"&&typeof J.join==="function"};d$.prototype.join=function(J,Z){if(!J)J=n$.alloc(this.length);if(!Z)Z=0;if(this.length===0)return J;if(Array.isArray(this.value))this.value.forEach(function(X){X.join(J,Z),Z+=X.length});else{if(typeof this.value==="number")J[Z]=this.value;else if(typeof this.value==="string")J.write(this.value,Z);else if(n$.isBuffer(this.value))this.value.copy(J,Z);Z+=this.length}return J}});var eY=s((FU,aY)=>{aY.exports=tY;function tY($,J){if(!$)throw Error(J||"Assertion failed")}tY.equal=function(J,Z,X){if(J!=Z)throw Error(X||"Assertion failed: "+J+" != "+Z)}});var uJ=s((MU,JG)=>{var Mz=cJ().Reporter,Rz=s$().EncoderBuffer,Iz=s$().DecoderBuffer,o0=eY(),$G=["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"],qz=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat($G),Pz=["_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()}JG.exports=t;var jz=["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={};jz.forEach(function(Y){Z[Y]=J[Y]});let X=new this.constructor(Z.parent);return X._baseState=Z,X};t.prototype._wrap=function(){let J=this._baseState;qz.forEach(function(Z){this[Z]=function(){let Y=new this.constructor(this);return J.children.push(Y),Y[Z].apply(Y,arguments)}},this)};t.prototype._init=function(J){let Z=this._baseState;o0(Z.parent===null),J.call(this),Z.children=Z.children.filter(function(X){return X._baseState.parent===this},this),o0.equal(Z.children.length,1,"Root node can have only one child")};t.prototype._useArgs=function(J){let Z=this._baseState,X=J.filter(function(Y){return Y instanceof this.constructor},this);if(J=J.filter(function(Y){return!(Y instanceof this.constructor)},this),X.length!==0)o0(Z.children===null),Z.children=X,X.forEach(function(Y){Y._baseState.parent=this},this);if(J.length!==0)o0(Z.args===null),Z.args=J,Z.reverseArgs=J.map(function(Y){if(typeof Y!=="object"||Y.constructor!==Object)return Y;let G={};return Object.keys(Y).forEach(function(H){if(H==(H|0))H|=0;let z=Y[H];G[z]=H}),G})};Pz.forEach(function($){t.prototype[$]=function(){let Z=this._baseState;throw Error($+" not implemented for encoding: "+Z.enc)}});$G.forEach(function($){t.prototype[$]=function(){let Z=this._baseState,X=Array.prototype.slice.call(arguments);return o0(Z.tag===null),Z.tag=$,this._useArgs(X),this}});t.prototype.use=function(J){o0(J);let Z=this._baseState;return o0(Z.use===null),Z.use=J,this};t.prototype.optional=function(){let J=this._baseState;return J.optional=!0,this};t.prototype.def=function(J){let Z=this._baseState;return o0(Z.default===null),Z.default=J,Z.optional=!0,this};t.prototype.explicit=function(J){let Z=this._baseState;return o0(Z.explicit===null&&Z.implicit===null),Z.explicit=J,this};t.prototype.implicit=function(J){let Z=this._baseState;return o0(Z.explicit===null&&Z.implicit===null),Z.implicit=J,this};t.prototype.obj=function(){let J=this._baseState,Z=Array.prototype.slice.call(arguments);if(J.obj=!0,Z.length!==0)this._useArgs(Z);return this};t.prototype.key=function(J){let Z=this._baseState;return o0(Z.key===null),Z.key=J,this};t.prototype.any=function(){let J=this._baseState;return J.any=!0,this};t.prototype.choice=function(J){let Z=this._baseState;return o0(Z.choice===null),Z.choice=J,this._useArgs(Object.keys(J).map(function(X){return J[X]})),this};t.prototype.contains=function(J){let Z=this._baseState;return o0(Z.use===null),Z.contains=J,this};t.prototype._decode=function(J,Z){let X=this._baseState;if(X.parent===null)return J.wrapResult(X.children[0]._decode(J,Z));let Y=X.default,G=!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);G=!0}catch(F){G=!1}J.restore(O)}else if(G=this._peekTag(J,V,X.any),J.isError(G))return G}let z;if(X.obj&&G)z=J.enterObject();if(G){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 F=this._decodeTag(J,X.implicit!==null?X.implicit:X.tag,X.any);if(J.isError(F))return F;if(X.any)Y=J.raw(O);else J=F}if(Z&&Z.track&&X.tag!==null)Z.track(J.path(),V,J.length,"tagged");if(Z&&Z.track&&X.tag!==null)Z.track(J.path(),J.offset,J.length,"content");if(X.any);else if(X.choice===null)Y=this._decodeGeneric(X.tag,J,Z);else Y=this._decodeChoice(J,Z);if(J.isError(Y))return Y;if(!X.any&&X.choice===null&&X.children!==null)X.children.forEach(function(F){F._decode(J,Z)});if(X.contains&&(X.tag==="octstr"||X.tag==="bitstr")){let O=new Iz(Y);Y=this._getUse(X.contains,J._reporterState.obj)._decode(O,Z)}}if(X.obj&&G)Y=J.leaveObject(z);if(X.key!==null&&(Y!==null||G===!0))J.leaveKey(H,X.key,Y);else if(H!==null)J.exitKey(H);return Y};t.prototype._decodeGeneric=function(J,Z,X){let Y=this._baseState;if(J==="seq"||J==="set")return null;if(J==="seqof"||J==="setof")return this._decodeList(Z,J,Y.args[0],X);else if(/str$/.test(J))return this._decodeStr(Z,J,X);else if(J==="objid"&&Y.args)return this._decodeObjid(Z,Y.args[0],Y.args[1],X);else if(J==="objid")return this._decodeObjid(Z,null,null,X);else if(J==="gentime"||J==="utctime")return this._decodeTime(Z,J,X);else if(J==="null_")return this._decodeNull(Z,X);else if(J==="bool")return this._decodeBool(Z,X);else if(J==="objDesc")return this._decodeStr(Z,J,X);else if(J==="int"||J==="enum")return this._decodeInt(Z,Y.args&&Y.args[0],X);if(Y.use!==null)return this._getUse(Y.use,Z._reporterState.obj)._decode(Z,X);else return Z.error("unknown tag: "+J)};t.prototype._getUse=function(J,Z){let X=this._baseState;if(X.useDecoder=this._use(J,Z),o0(X.useDecoder._baseState.parent===null),X.useDecoder=X.useDecoder._baseState.children[0],X.implicit!==X.useDecoder._baseState.implicit)X.useDecoder=X.useDecoder.clone(),X.useDecoder._baseState.implicit=X.implicit;return X.useDecoder};t.prototype._decodeChoice=function(J,Z){let X=this._baseState,Y=null,G=!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;Y={type:H,value:O},G=!0}catch(O){return J.restore(z),!1}return!0},this),!G)return J.error("Choice not matched");return Y};t.prototype._createEncoderBuffer=function(J){return new Rz(J,this.reporter)};t.prototype._encode=function(J,Z,X){let Y=this._baseState;if(Y.default!==null&&Y.default===J)return;let G=this._encodeValue(J,Z,X);if(G===void 0)return;if(this._skipDefault(G,Z,X))return;return G};t.prototype._encodeValue=function(J,Z,X){let Y=this._baseState;if(Y.parent===null)return Y.children[0]._encode(J,Z||new Mz);let G=null;if(this.reporter=Z,Y.optional&&J===void 0)if(Y.default!==null)J=Y.default;else return;let H=null,z=!1;if(Y.any)G=this._createEncoderBuffer(J);else if(Y.choice)G=this._encodeChoice(J,Z);else if(Y.contains)H=this._getUse(Y.contains,X)._encode(J,Z),z=!0;else if(Y.children)H=Y.children.map(function(V){if(V._baseState.tag==="null_")return V._encode(null,Z,J);if(V._baseState.key===null)return Z.error("Child should have a key");let O=Z.enterKey(V._baseState.key);if(typeof J!=="object")return Z.error("Child expected, but input is not object");let F=V._encode(J[V._baseState.key],Z,J);return Z.leaveKey(O),F},this).filter(function(V){return V}),H=this._createEncoderBuffer(H);else if(Y.tag==="seqof"||Y.tag==="setof"){if(!(Y.args&&Y.args.length===1))return Z.error("Too many args for : "+Y.tag);if(!Array.isArray(J))return Z.error("seqof/setof, but data is not Array");let V=this.clone();V._baseState.implicit=null,H=this._createEncoderBuffer(J.map(function(O){let F=this._baseState;return this._getUse(F.args[0],J)._encode(O,Z)},V))}else if(Y.use!==null)G=this._getUse(Y.use,X)._encode(J,Z);else H=this._encodePrimitive(Y.tag,J),z=!0;if(!Y.any&&Y.choice===null){let V=Y.implicit!==null?Y.implicit:Y.tag,O=Y.implicit===null?"universal":"context";if(V===null){if(Y.use===null)Z.error("Tag could be omitted only for .use()")}else if(Y.use===null)G=this._encodeComposite(V,z,O,H)}if(Y.explicit!==null)G=this._encodeComposite(Y.explicit,!1,"context",G);return G};t.prototype._encodeChoice=function(J,Z){let X=this._baseState,Y=X.choice[J.type];if(!Y)o0(!1,J.type+" not found in "+JSON.stringify(Object.keys(X.choice)));return Y._encode(J.value,Z)};t.prototype._encodePrimitive=function(J,Z){let X=this._baseState;if(/str$/.test(J))return this._encodeStr(Z,J);else if(J==="objid"&&X.args)return this._encodeObjid(Z,X.reverseArgs[0],X.args[1]);else if(J==="objid")return this._encodeObjid(Z,null,null);else if(J==="gentime"||J==="utctime")return this._encodeTime(Z,J);else if(J==="null_")return this._encodeNull();else if(J==="int"||J==="enum")return this._encodeInt(Z,X.args&&X.reverseArgs[0]);else if(J==="bool")return this._encodeBool(Z);else if(J==="objDesc")return this._encodeStr(Z,J);else throw Error("Unsupported tag: "+J)};t.prototype._isNumstr=function(J){return/^[0-9 ]*$/.test(J)};t.prototype._isPrintstr=function(J){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(J)}});var mJ=s((Bz)=>{function ZG($){let J={};return Object.keys($).forEach(function(Z){if((Z|0)==Z)Z=Z|0;let X=$[Z];J[X]=Z}),J}Bz.tagClass={0:"universal",1:"application",2:"context",3:"private"};Bz.tagClassByName=ZG(Bz.tagClass);Bz.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"};Bz.tagByName=ZG(Bz.tag)});var VX=s((IU,HG)=>{var Cz=j$(),U$=bJ().Buffer,GG=uJ(),UX=mJ();function WG($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new Z$,this.tree._init($.body)}HG.exports=WG;WG.prototype.encode=function(J,Z){return this.tree._encode(J,Z).join()};function Z$($){GG.call(this,"der",$)}Cz(Z$,GG);Z$.prototype._encodeComposite=function(J,Z,X,Y){let G=Ez(J,Z,X,this.reporter);if(Y.length<128){let V=U$.alloc(2);return V[0]=G,V[1]=Y.length,this._createEncoderBuffer([V,Y])}let H=1;for(let V=Y.length;V>=256;V>>=8)H++;let z=U$.alloc(2+H);z[0]=G,z[1]=128|H;for(let V=1+H,O=Y.length;O>0;V--,O>>=8)z[V]=O&255;return this._createEncoderBuffer([z,Y])};Z$.prototype._encodeStr=function(J,Z){if(Z==="bitstr")return this._createEncoderBuffer([J.unused|0,J.data]);else if(Z==="bmpstr"){let X=U$.alloc(J.length*2);for(let Y=0;Y<J.length;Y++)X.writeUInt16BE(J.charCodeAt(Y),Y*2);return this._createEncoderBuffer(X)}else if(Z==="numstr"){if(!this._isNumstr(J))return this.reporter.error("Encoding of string type: numstr supports only digits and space");return this._createEncoderBuffer(J)}else if(Z==="printstr"){if(!this._isPrintstr(J))return this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");return this._createEncoderBuffer(J)}else if(/str$/.test(Z))return this._createEncoderBuffer(J);else if(Z==="objDesc")return this._createEncoderBuffer(J);else return this.reporter.error("Encoding of string type: "+Z+" unsupported")};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 Y=0;for(let z=0;z<J.length;z++){let V=J[z];for(Y++;V>=128;V>>=7)Y++}let G=U$.alloc(Y),H=G.length-1;for(let z=J.length-1;z>=0;z--){let V=J[z];G[H--]=V&127;while((V>>=7)>0)G[H--]=128|V&127}return this._createEncoderBuffer(G)};function J$($){if($<10)return"0"+$;else return $}Z$.prototype._encodeTime=function(J,Z){let X,Y=new Date(J);if(Z==="gentime")X=[J$(Y.getUTCFullYear()),J$(Y.getUTCMonth()+1),J$(Y.getUTCDate()),J$(Y.getUTCHours()),J$(Y.getUTCMinutes()),J$(Y.getUTCSeconds()),"Z"].join("");else if(Z==="utctime")X=[J$(Y.getUTCFullYear()%100),J$(Y.getUTCMonth()+1),J$(Y.getUTCDate()),J$(Y.getUTCHours()),J$(Y.getUTCMinutes()),J$(Y.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"&&!U$.isBuffer(J)){let G=J.toArray();if(!J.sign&&G[0]&128)G.unshift(0);J=U$.from(G)}if(U$.isBuffer(J)){let G=J.length;if(J.length===0)G++;let H=U$.alloc(G);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 G=J;G>=256;G>>=8)X++;let Y=Array(X);for(let G=Y.length-1;G>=0;G--)Y[G]=J&255,J>>=8;if(Y[0]&128)Y.unshift(0);return this._createEncoderBuffer(U$.from(Y))};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 Y=this._baseState,G;if(Y.default===null)return!1;let H=J.join();if(Y.defaultBuffer===void 0)Y.defaultBuffer=this._encodeValue(Y.default,Z,X).join();if(H.length!==Y.defaultBuffer.length)return!1;for(G=0;G<H.length;G++)if(H[G]!==Y.defaultBuffer[G])return!1;return!0};function Ez($,J,Z,X){let Y;if($==="seqof")$="seq";else if($==="setof")$="set";if(UX.tagByName.hasOwnProperty($))Y=UX.tagByName[$];else if(typeof $==="number"&&($|0)===$)Y=$;else return X.error("Unknown tag: "+$);if(Y>=31)return X.error("Multi-octet tag encoding unsupported");if(!J)Y|=32;return Y|=UX.tagClassByName[Z||"universal"]<<6,Y}});var zG=s((qU,QG)=>{var wz=j$(),OX=VX();function _X($){OX.call(this,$),this.enc="pem"}wz(_X,OX);QG.exports=_X;_X.prototype.encode=function(J,Z){let Y=OX.prototype.encode.call(this,J).toString("base64"),G=["-----BEGIN "+Z.label+"-----"];for(let H=0;H<Y.length;H+=64)G.push(Y.slice(H,H+64));return G.push("-----END "+Z.label+"-----"),G.join(`
|
|
6
|
-
`)}});var AX=s((VG)=>{var UG=VG;UG.der=VX();UG.pem=zG()});var FX=s((jU,MG)=>{var Tz=j$(),vz=HX(),OG=s$().DecoderBuffer,AG=uJ(),_G=mJ();function KG($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new r0,this.tree._init($.body)}MG.exports=KG;KG.prototype.decode=function(J,Z){if(!OG.isDecoderBuffer(J))J=new OG(J,Z);return this.tree._decode(J,Z)};function r0($){AG.call(this,"der",$)}Tz(r0,AG);r0.prototype._peekTag=function(J,Z,X){if(J.isEmpty())return!1;let Y=J.save(),G=KX(J,'Failed to peek tag: "'+Z+'"');if(J.isError(G))return G;return J.restore(Y),G.tag===Z||G.tagStr===Z||G.tagStr+"of"===Z||X};r0.prototype._decodeTag=function(J,Z,X){let Y=KX(J,'Failed to decode tag of "'+Z+'"');if(J.isError(Y))return Y;let G=FG(J,Y.primitive,'Failed to get length of "'+Z+'"');if(J.isError(G))return G;if(!X&&Y.tag!==Z&&Y.tagStr!==Z&&Y.tagStr+"of"!==Z)return J.error('Failed to match tag: "'+Z+'"');if(Y.primitive||G!==null)return J.skip(G,'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 G=J.offset-H.offset,J.restore(H),J.skip(G,'Failed to match body of: "'+Z+'"')};r0.prototype._skipUntilEnd=function(J,Z){for(;;){let X=KX(J,Z);if(J.isError(X))return X;let Y=FG(J,X.primitive,Z);if(J.isError(Y))return Y;let G;if(X.primitive||Y!==null)G=J.skip(Y);else G=this._skipUntilEnd(J,Z);if(J.isError(G))return G;if(X.tagStr==="end")break}};r0.prototype._decodeList=function(J,Z,X,Y){let G=[];while(!J.isEmpty()){let H=this._peekTag(J,"end");if(J.isError(H))return H;let z=X.decode(J,"der",Y);if(J.isError(z)&&H)break;G.push(z)}return G};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 Y="";for(let G=0;G<X.length/2;G++)Y+=String.fromCharCode(X.readUInt16BE(G*2));return Y}else if(Z==="numstr"){let X=J.raw().toString("ascii");if(!this._isNumstr(X))return J.error("Decoding of string type: numstr unsupported characters");return X}else if(Z==="octstr")return J.raw();else if(Z==="objDesc")return J.raw();else if(Z==="printstr"){let X=J.raw().toString("ascii");if(!this._isPrintstr(X))return J.error("Decoding of string type: printstr unsupported characters");return X}else if(/str$/.test(Z))return J.raw().toString();else return J.error("Decoding of string type: "+Z+" unsupported")};r0.prototype._decodeObjid=function(J,Z,X){let Y,G=[],H=0,z=0;while(!J.isEmpty())if(z=J.readUInt8(),H<<=7,H|=z&127,(z&128)===0)G.push(H),H=0;if(z&128)G.push(H);let V=G[0]/40|0,O=G[0]%40;if(X)Y=G;else Y=[V,O].concat(G.slice(1));if(Z){let F=Z[Y.join(" ")];if(F===void 0)F=Z[Y.join(".")];if(F!==void 0)Y=F}return Y};r0.prototype._decodeTime=function(J,Z){let X=J.raw().toString(),Y,G,H,z,V,O;if(Z==="gentime")Y=X.slice(0,4)|0,G=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(Y=X.slice(0,2)|0,G=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,Y<70)Y=2000+Y;else Y=1900+Y;else return J.error("Decoding "+Z+" time is not supported yet");return Date.UTC(Y,G-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(),Y=new vz(X);if(Z)Y=Z[Y.toString(10)]||Y;return Y};r0.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getDecoder("der").tree};function KX($,J){let Z=$.readUInt8(J);if($.isError(Z))return Z;let X=_G.tagClass[Z>>6],Y=(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 G=_G.tag[Z];return{cls:X,primitive:Y,tag:Z,tagStr:G}}function FG($,J,Z){let X=$.readUInt8(Z);if($.isError(X))return X;if(!J&&X===128)return null;if((X&128)===0)return X;let Y=X&127;if(Y>4)return $.error("length octect is too long");X=0;for(let G=0;G<Y;G++){X<<=8;let H=$.readUInt8(Z);if($.isError(H))return H;X|=H}return X}});var IG=s((BU,RG)=>{var Nz=j$(),Dz=bJ().Buffer,MX=FX();function RX($){MX.call(this,$),this.enc="pem"}Nz(RX,MX);RG.exports=RX;RX.prototype.decode=function(J,Z){let X=J.toString().split(/[\r\n]+/g),Y=Z.label.toUpperCase(),G=/^-----(BEGIN|END) ([^-]+)-----$/,H=-1,z=-1;for(let F=0;F<X.length;F++){let I=X[F].match(G);if(I===null)continue;if(I[2]!==Y)continue;if(H===-1){if(I[1]!=="BEGIN")break;H=F}else{if(I[1]!=="END")break;z=F;break}}if(H===-1||z===-1)throw Error("PEM section not found for: "+Y);let V=X.slice(H+1,z).join("");V.replace(/[^a-z0-9+/=]+/gi,"");let O=Dz.from(V,"base64");return MX.prototype.decode.call(this,O,Z)}});var IX=s((PG)=>{var qG=PG;qG.der=FX();qG.pem=IG()});var BG=s((jG)=>{var kz=AX(),yz=IX(),xz=j$(),fz=jG;fz.define=function(J,Z){return new o$(J,Z)};function o$($,J){this.name=$,this.body=J,this.decoders={},this.encoders={}}o$.prototype._createNamed=function(J){let Z=this.name;function X(Y){this._initNamed(Y,Z)}return xz(X,J),X.prototype._initNamed=function(G,H){J.call(this,G,H)},new X(this)};o$.prototype._getDecoder=function(J){if(J=J||"der",!this.decoders.hasOwnProperty(J))this.decoders[J]=this._createNamed(yz[J]);return this.decoders[J]};o$.prototype.decode=function(J,Z,X){return this._getDecoder(Z).decode(J,X)};o$.prototype._getEncoder=function(J){if(J=J||"der",!this.encoders.hasOwnProperty(J))this.encoders[J]=this._createNamed(kz[J]);return this.encoders[J]};o$.prototype.encode=function(J,Z,X){return this._getEncoder(Z).encode(J,X)}});var SG=s((LG)=>{var nJ=LG;nJ.Reporter=cJ().Reporter;nJ.DecoderBuffer=s$().DecoderBuffer;nJ.EncoderBuffer=s$().EncoderBuffer;nJ.Node=uJ()});var wG=s((EG)=>{var CG=EG;CG._reverse=function(J){let Z={};return Object.keys(J).forEach(function(X){if((X|0)==X)X=X|0;let Y=J[X];Z[Y]=X}),Z};CG.der=mJ()});var vG=s((TG)=>{var l$=TG;l$.bignum=HX();l$.define=BG().define;l$.base=SG();l$.constants=wG();l$.decoders=IX();l$.encoders=AX()});var kG=s((qX,DG)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var dJ=A$("buffer"),Q$=dJ.Buffer;function NG($,J){for(var Z in $)J[Z]=$[Z]}if(Q$.from&&Q$.alloc&&Q$.allocUnsafe&&Q$.allocUnsafeSlow)DG.exports=dJ;else NG(dJ,qX),qX.Buffer=T$;function T$($,J,Z){return Q$($,J,Z)}T$.prototype=Object.create(Q$.prototype);NG(Q$,T$);T$.from=function($,J,Z){if(typeof $==="number")throw TypeError("Argument must not be a number");return Q$($,J,Z)};T$.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};T$.allocUnsafe=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return Q$($)};T$.allocUnsafeSlow=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return dJ.SlowBuffer($)}});var xG=s((TU,yG)=>{function PX($){var J=($/8|0)+($%8===0?0:1);return J}var gz={ES256:PX(256),ES384:PX(384),ES512:PX(521)};function hz($){var J=gz[$];if(J)return J;throw Error('Unknown algorithm "'+$+'"')}yG.exports=hz});var uG=s((vU,pG)=>{var sJ=kG().Buffer,gG=xG(),oJ=128,hG=0,bz=32,cz=16,pz=2,bG=cz|bz|hG<<6,lJ=pz|hG<<6;function uz($){return $.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function cG($){if(sJ.isBuffer($))return $;else if(typeof $==="string")return sJ.from($,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function mz($,J){$=cG($);var Z=gG(J),X=Z+1,Y=$.length,G=0;if($[G++]!==bG)throw Error('Could not find expected "seq"');var H=$[G++];if(H===(oJ|1))H=$[G++];if(Y-G<H)throw Error('"seq" specified length of "'+H+'", only "'+(Y-G)+'" remaining');if($[G++]!==lJ)throw Error('Could not find expected "int" for "r"');var z=$[G++];if(Y-G-2<z)throw Error('"r" specified length of "'+z+'", only "'+(Y-G-2)+'" available');if(X<z)throw Error('"r" specified length of "'+z+'", max of "'+X+'" is acceptable');var V=G;if(G+=z,$[G++]!==lJ)throw Error('Could not find expected "int" for "s"');var O=$[G++];if(Y-G!==O)throw Error('"s" specified length of "'+O+'", expected "'+(Y-G)+'"');if(X<O)throw Error('"s" specified length of "'+O+'", max of "'+X+'" is acceptable');var F=G;if(G+=O,G!==Y)throw Error('Expected to consume entire buffer, but "'+(Y-G)+'" bytes remain');var I=Z-z,B=Z-O,L=sJ.allocUnsafe(I+z+B+O);for(G=0;G<I;++G)L[G]=0;$.copy(L,G,V+Math.max(-I,0),V+z),G=Z;for(var C=G;G<C+B;++G)L[G]=0;return $.copy(L,G,F+Math.max(-B,0),F+O),L=L.toString("base64"),L=uz(L),L}function fG($,J,Z){var X=0;while(J+X<Z&&$[J+X]===0)++X;var Y=$[J+X]>=oJ;if(Y)--X;return X}function nz($,J){$=cG($);var Z=gG(J),X=$.length;if(X!==Z*2)throw TypeError('"'+J+'" signatures must be "'+Z*2+'" bytes, saw "'+X+'"');var Y=fG($,0,Z),G=fG($,Z,$.length),H=Z-Y,z=Z-G,V=2+H+1+1+z,O=V<oJ,F=sJ.allocUnsafe((O?2:3)+V),I=0;if(F[I++]=bG,O)F[I++]=V;else F[I++]=oJ|1,F[I++]=V&255;if(F[I++]=lJ,F[I++]=H,Y<0)F[I++]=0,I+=$.copy(F,I,0,Z);else I+=$.copy(F,I,Y,Z);if(F[I++]=lJ,F[I++]=z,G<0)F[I++]=0,$.copy(F,I,Z);else $.copy(F,I,Z+G);return F}pG.exports={derToJose:mz,joseToDer:nz}});var SX=s((NU,ZW)=>{var LX=vG(),{createHmac:dG,createVerify:dz,createSign:sz,timingSafeEqual:oz,createPublicKey:lz,constants:{RSA_PKCS1_PSS_PADDING:sG,RSA_PSS_SALTLEN_DIGEST:oG,RSA_PKCS1_PADDING:lG,RSA_PSS_SALTLEN_MAX_SIGN:rz,RSA_PSS_SALTLEN_AUTO:iz},sign:mG,verify:nG}=A$("crypto"),{joseToDer:tz,derToJose:az}=uG(),rG=GX(),{TokenError:J0}=c$(),iG=/[=+/]/g,ez={"=":"","+":"-","/":"_"},tG=/^-----BEGIN(?: (RSA|EC|ENCRYPTED))? PRIVATE KEY-----/,aG=/^-----BEGIN(?: (RSA))? PUBLIC KEY-----/,rJ=new rG(1000),jX=new rG(1000),eG=["HS256","HS384","HS512"],$6=["ES256","ES384","ES512"],BX=["RS256","RS384","RS512","PS256","PS384","PS512"],J6=["EdDSA"],$W={"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"]}},Z6=LX.define("PrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),X6=LX.define("PublicKey",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),Y6=LX.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 JW($){return ez[$]}function QJ($,J,Z,X){return $.set(J,[Z,X]),Z||X}function G6($){if($.match(aG)||$.includes("-----BEGIN CERTIFICATE-----"))throw new J0(J0.codes.invalidKey,"Public keys are not supported for signing.");let J=$.trim().match(tG);if(!J)return"HS256";let Z,X,Y;switch(J[1]){case"RSA":return"RS256";case"EC":Z=Y6.decode($,"pem",{label:"EC PRIVATE KEY"}),Y=Z.parameters.value.join(".");break;case"ENCRYPTED":return"ENCRYPTED";default:switch(Z=Z6.decode($,"pem",{label:"PRIVATE KEY"}),X=Z.algorithm.algorithm.join("."),X){case"1.2.840.113549.1.1.1":return"RS256";case"1.2.840.10045.2.1":Y=Z.algorithm.parameters.join(".");break;case"1.3.101.112":case"1.3.101.113":return"EdDSA";default:throw new J0(J0.codes.invalidKey,`Unsupported PEM PCKS8 private key with OID ${X}.`)}}let G=$W[Y];if(!G)throw new J0(J0.codes.invalidKey,`Unsupported EC private key with curve ${Y}.`);return`ES${G.bits}`}function W6($){let J=$.match(aG);if($.match(tG))throw new J0(J0.codes.invalidKey,"Private keys are not supported for verifying.");else if(J&&J[1]==="RSA")return BX;else if(!J&&!$.includes("-----BEGIN CERTIFICATE-----"))return eG;if($.includes("-----BEGIN CERTIFICATE-----"))$=lz($).export({type:"spki",format:"pem"});let Z=X6.decode($,"pem",{label:"PUBLIC KEY"}),X=Z.algorithm.algorithm.join("."),Y;switch(X){case"1.2.840.113549.1.1.1":return BX;case"1.2.840.10045.2.1":Y=Z.algorithm.parameters.join(".");break;case"1.3.101.112":case"1.3.101.113":return["EdDSA"];default:throw new J0(J0.codes.invalidKey,`Unsupported PEM PCKS8 public key with OID ${X}.`)}let G=$W[Y];if(!G)throw new J0(J0.codes.invalidKey,`Unsupported EC public key with curve ${Y}.`);return[`ES${G.bits}`]}function H6($,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]=rJ.get($)||[];if(Z)return Z;else if(X)throw X;try{let Y=G6($);if(Y==="ENCRYPTED")return QJ(rJ,$,J);return QJ(rJ,$,Y)}catch(Y){throw QJ(rJ,$,null,J0.wrap(Y,J0.codes.invalidKey,"Unsupported PEM private key."))}}function Q6($){if(!$)return"none";let[J,Z]=jX.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(jX,$,W6($))}catch(X){throw QJ(jX,$,null,J0.wrap(X,J0.codes.invalidKey,"Unsupported PEM public key."))}}function z6($,J,Z){try{let X=$.slice(0,2),Y=`sha${$.slice(2)}`,G,H;switch(X){case"HS":G=dG(Y,J).update(Z).digest("base64");break;case"ES":G=az(mG(Y,Buffer.from(Z,"utf-8"),J),$).toString("base64");break;case"RS":case"PS":if(H={key:J,padding:lG,saltLength:rz},X==="PS")H.padding=sG,H.saltLength=oG;G=sz(Y).update(Z).sign(H).toString("base64");break;case"Ed":G=mG(void 0,Buffer.from(Z,"utf-8"),J).toString("base64")}return G.replace(iG,JW)}catch(X){throw new J0(J0.codes.signError,"Cannot create the signature.",{originalError:X})}}function U6($,J,Z,X){try{let Y=$.slice(0,2),G=`SHA${$.slice(2)}`;if(X=Buffer.from(X,"base64"),Y==="HS")try{return oz(dG(G,J).update(Z).digest(),X)}catch{return!1}else if(Y==="Ed")if(typeof nG==="function")return nG(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:lG,saltLength:iz};if(Y==="PS")H.padding=sG,H.saltLength=oG;else if(Y==="ES")X=tz(X,$);return dz("RSA-"+G).update(Z).verify(H,X)}catch(Y){throw new J0(J0.codes.verifyError,"Cannot verify the signature.",{originalError:Y})}}ZW.exports={base64UrlMatcher:iG,base64UrlReplacer:JW,hsAlgorithms:eG,rsaAlgorithms:BX,esAlgorithms:$6,edAlgorithms:J6,detectPrivateKeyAlgorithm:H6,detectPublicKeyAlgorithms:Q6,createSignature:z6,verifySignature:U6}});var CX=s((DU,YW)=>{var{createHash:XW}=A$("crypto"),V6=/"alg"\s*:\s*"[HERP]S(256|384)"/m,O6=/"alg"\s*:\s*"EdDSA"/m,_6=/"crv"\s*:\s*"Ed448"/m;function A6($,J,Z){let X=$(J,Z);if(X&&typeof X.then==="function")X.then((Y)=>{process.nextTick(()=>Z(null,Y))}).catch(Z)}function K6($){if(typeof $==="function")return[$];let J,Z,X=new Promise((Y,G)=>{J=Y,Z=G});return[function(Y,G){if(Y)return Z(Y);return J(G)},X]}function F6($){let J=$.split(".",1)[0],Z=Buffer.from(J,"base64").toString("utf-8"),X=null;if(Z.match(O6)&&Z.match(_6))X=XW("shake256",{outputLength:114});else{let Y=Z.match(V6);X=XW(`sha${Y?Y[1]:"512"}`)}return X.update($).digest("hex")}YW.exports={getAsyncKey:A6,ensurePromiseCallback:K6,hashToken:F6}});var VW=s((kU,UW)=>{var{createPublicKey:M6,createSecretKey:R6}=A$("crypto"),I6=GX(),{hsAlgorithms:WW,verifySignature:q6,detectPublicKeyAlgorithms:HW}=SX(),P6=$X(),{TokenError:m}=c$(),{getAsyncKey:j6,ensurePromiseCallback:B6,hashToken:L6}=CX();function S6($,J){return $===J}function QW($,J){for(let Z of $)if(J.includes(Z))return;throw new m(m.codes.invalidKey,`Invalid public key provided for algorithms ${$.join(", ")}.`)}function zW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J?R6($):M6($)}function zJ($){if(!Array.isArray($))$=[$];return $.filter((J)=>J).map((J)=>{if(J&&typeof J.test==="function")return J;return{test:S6.bind(null,J)}})}function C6($){let J=parseInt($===!0?1000:$,10);return J>0?new I6(J):null}function r$({cache:$,token:J,cacheTTL:Z,payload:X,ignoreExpiration:Y,ignoreNotBefore:G,maxAge:H,clockTimestamp:z=Date.now(),clockTolerance:V,errorCacheTTL:O,cacheKeyBuilder:F},I){if(!$)return I;let B=[I,0,0];if(I instanceof m){let w=typeof O==="function"?O(I):O;return B[2]=z+V+w,$.set(F(J),B),I}if(X&&typeof X.iat==="number"){if(B[1]=!G&&typeof X.nbf==="number"?X.nbf*1000-V:0,!Y){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(F(J),B),I}function E6($,J,Z){if($ instanceof m){if(!J)throw $;J($)}else{if(!J)return $;J(null,$)}return Z}function w6($,J,Z,X,Y){if(!Y.includes(J.alg))throw new m(m.codes.invalidAlgorithm,"The token algorithm is invalid.");if(Z&&!q6(J.alg,X,$,Z))throw new m(m.codes.invalidSignature,"The token signature is invalid.")}function T6($,J,Z,X,Y){let G=Z?`The ${J} claim must be a ${Y} or an array of ${Y}s.`:`The ${J} claim must be a ${Y}.`;if(X&&!Z)throw new m(m.codes.invalidClaimValue,G);if($.map((H)=>typeof H).some((H)=>H!==Y))throw new m(m.codes.invalidClaimType,G)}function v6($,J,Z,X){let Y=X?`None of ${J} claim values are allowed.`:`The ${J} claim value is not allowed.`;if(!$.some((G)=>Z.some((H)=>H.test(G))))throw new m(m.codes.invalidClaimValue,Y)}function N6($,J,Z,X,Y,G){let H=$*1000+(J||0);if(!(X?Z>=H:Z<=H))throw new m(m.codes[Y],`The token ${G} at ${new Date(H).toISOString()}.`)}function GW($,{input:J,header:Z,payload:X,signature:Y},{validators:G,allowedAlgorithms:H,checkTyp:z,clockTimestamp:V,requiredClaims:O}){let F=$ instanceof Buffer?$.length:!!$;if(F&&!Y)throw new m(m.codes.missingSignature,"The token signature is missing.");else if(!F&&Y)throw new m(m.codes.missingKey,"The key option is missing.");if(w6(J,Z,Y,$,H),z&&(typeof Z.typ!=="string"||z!==Z.typ.toLowerCase().replace(/^application\//,"")))throw new m(m.codes.invalidType,"Invalid typ.");if(O){for(let B of O)if(!(B in X))throw new m(m.codes.missingRequiredClaim,`The ${B} claim is required.`)}let I=V||Date.now();for(let{type:B,claim:L,allowed:C,array:w,modifier:T,greater:N,errorCode:E,errorVerb:D}of G){let h=X[L],v=Array.isArray(h),f=v?h:[h];if(!(L in X))continue;if(T6(f,L,w,v,B==="date"?"number":"string"),B==="date")N6(h,T,I,N,E,D);else v6(f,L,C,v)}}function D6({key:$,allowedAlgorithms:J,complete:Z,cacheTTL:X,checkTyp:Y,clockTimestamp:G,clockTolerance:H,ignoreExpiration:z,ignoreNotBefore:V,maxAge:O,isAsync:F,validators:I,decode:B,cache:L,requiredClaims:C,errorCacheTTL:w,cacheKeyBuilder:T},N,E){let[D,h]=F?B6(E):[];if(L){let[U,_,A]=L.get(T(N))||[void 0,0,0],R=G||Date.now();if(typeof U<"u"&&(_===0||R<_&&U.code==="FAST_JWT_INACTIVE"||R>=_&&U.code!=="FAST_JWT_INACTIVE")&&(A===0||R<=A))return E6(U,D,h)}let v;try{v=B(N)}catch(U){if(D)return D(U),h;throw U}let{header:f,payload:l,signature:r,input:u0}=v,q={cache:L,token:N,cacheTTL:X,errorCacheTTL:w,ignoreExpiration:z,ignoreNotBefore:V,maxAge:O,clockTimestamp:G,clockTolerance:H,payload:l,cacheKeyBuilder:T},W={validators:I,allowedAlgorithms:J,checkTyp:Y,clockTimestamp:G,clockTolerance:H,requiredClaims:C};if(!D)try{return GW($,v,W),r$(q,Z?{header:f,payload:l,signature:r,input:u0}:l)}catch(U){throw r$(q,U)}return j6($,{header:f,payload:l,signature:r},(U,_)=>{if(U)return D(r$(q,m.wrap(U,m.codes.keyFetchingError,"Cannot fetch key.")));if(typeof _==="string")_=Buffer.from(_,"utf-8");else if(!(_ instanceof Buffer))return D(r$(q,new m(m.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a public key.")));try{let A=HW(_);if(W.allowedAlgorithms.length)QW(J,A);else W.allowedAlgorithms=A;_=zW(_,A[0]===WW[0]),GW(_,v,W)}catch(A){return D(r$(q,A))}D(null,r$(q,Z?{header:f,payload:l,signature:r,input:N}:l))}),h}UW.exports=function(J){let{key:Z,algorithms:X,complete:Y,cache:G,cacheTTL:H,errorCacheTTL:z,checkTyp:V,clockTimestamp:O,clockTolerance:F,ignoreExpiration:I,ignoreNotBefore:B,maxAge:L,allowedJti:C,allowedAud:w,allowedIss:T,allowedSub:N,allowedNonce:E,requiredClaims:D,cacheKeyBuilder:h}={cacheTTL:600000,clockTolerance:0,errorCacheTTL:-1,cacheKeyBuilder:L6,...J};if(!Array.isArray(X))X=[];let v=typeof Z;if(v!=="string"&&v!=="object"&&v!=="function")throw new m(m.codes.INVALID_OPTION,"The key option must be a string, a buffer or a function returning the algorithm secret or public key.");if(Z&&v!=="function"){let q=HW(Z);if(X.length)QW(X,q);else X=q;Z=zW(Z,q[0]===WW[0])}if(O&&(typeof O!=="number"||O<0))throw new m(m.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(F&&(typeof F!=="number"||F<0))throw new m(m.codes.invalidOption,"The clockTolerance option must be a positive number.");if(H&&(typeof H!=="number"||H<0))throw new m(m.codes.invalidOption,"The cacheTTL option must be a positive number.");if(z&&typeof z!=="function"&&typeof z!=="number"||z<-1)throw new m(m.codes.invalidOption,"The errorCacheTTL option must be a number greater than -1 or a function.");if(D&&!Array.isArray(D))throw new m(m.codes.invalidOption,"The requiredClaims option must be an array.");let f=[];if(!B)f.push({type:"date",claim:"nbf",errorCode:"inactive",errorVerb:"will be active",greater:!0,modifier:-F});if(!I)f.push({type:"date",claim:"exp",errorCode:"expired",errorVerb:"has expired",modifier:+F});if(typeof L==="number")f.push({type:"date",claim:"iat",errorCode:"expired",errorVerb:"has expired",modifier:L});if(C)f.push({type:"string",claim:"jti",allowed:zJ(C)});if(w)f.push({type:"string",claim:"aud",allowed:zJ(w),array:!0});if(T)f.push({type:"string",claim:"iss",allowed:zJ(T)});if(N)f.push({type:"string",claim:"sub",allowed:zJ(N)});if(E)f.push({type:"string",claim:"nonce",allowed:zJ(E)});let l=V?V.toLowerCase().replace(/^application\//,""):null,r={key:Z,allowedAlgorithms:X,complete:Y,cacheTTL:H,errorCacheTTL:z,checkTyp:l,clockTimestamp:O,clockTolerance:F,ignoreExpiration:I,ignoreNotBefore:B,maxAge:L,isAsync:v==="function",validators:f,decode:P6({complete:!0}),cache:C6(G),requiredClaims:D,cacheKeyBuilder:h},u0=D6.bind(null,r);return u0.cache=r.cache,u0}});var OW=s((f6)=>{var k6=/^(-?(?:\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?)?)?$/,iJ=1000,tJ=iJ*60,aJ=tJ*60,VJ=aJ*24,EX=VJ*365.25;function y6($){var J,Z=$.toLowerCase().match(k6);if(Z!=null&&(J=parseFloat(Z[1]))){if(Z[3]!=null)return J*iJ;if(Z[4]!=null)return J*tJ;if(Z[5]!=null)return J*aJ;if(Z[6]!=null)return J*VJ;if(Z[7]!=null)return J*VJ*7;if(Z[8]!=null)return J*EX;return J}}function UJ($,J,Z,X){var Y=($|0)===$?$:~~($+0.5);return J+Y+(X?" "+Z+(Y!=1?"s":""):Z[0])}function x6($,J){var Z=$<0?"-":"",X=$<0?-$:$;if(X<iJ)return $+(J?" ms":"ms");if(X<tJ)return UJ(X/iJ,Z,"second",J);if(X<aJ)return UJ(X/tJ,Z,"minute",J);if(X<VJ)return UJ(X/aJ,Z,"hour",J);if(X<EX)return UJ(X/VJ,Z,"day",J);return UJ(X/EX,Z,"year",J)}f6.format=x6;f6.parse=y6});var qW=s((xU,IW)=>{var{base64UrlMatcher:wX,base64UrlReplacer:TX,hsAlgorithms:b6,esAlgorithms:c6,rsaAlgorithms:p6,edAlgorithms:u6,detectPrivateKeyAlgorithm:KW,createSignature:_W}=SX(),{TokenError:n}=c$(),{getAsyncKey:m6,ensurePromiseCallback:n6}=CX(),{createPrivateKey:d6,createSecretKey:s6}=A$("crypto"),{parse:AW}=OW(),FW=new Set([...b6,...c6,...p6,...u6,"none"]),o6=Array.from(FW).join(", ");function MW($,J){let Z=$.slice(0,2),X=J.slice(0,2),Y=!0;if(Z==="RS"||Z==="PS")Y=X==="RS"||Z==="RS"&&J==="ENCRYPTED";else if(Z==="ES"||Z==="Ed")Y=Z===X||Z==="ES"&&J==="ENCRYPTED";if(!Y)throw new n(n.codes.invalidKey,`Invalid private key provided for algorithm ${$}.`)}function RW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J[0]==="H"?s6($):d6($)}function l6({key:$,algorithm:J,noTimestamp:Z,mutatePayload:X,clockTimestamp:Y,expiresIn:G,notBefore:H,kid:z,typ:V,isAsync:O,additionalHeader:F,fixedPayload:I},B,L){let[C,w]=O?n6(L):[];if(typeof B!=="object")throw new n(n.codes.invalidType,"The payload must be an object.");if(B.exp&&(!Number.isInteger(B.exp)||B.exp<0))throw new n(n.codes.invalidClaimValue,"The exp claim must be a positive integer.");let T={alg:J,typ:V||"JWT",kid:z,...F},N="",E=B.iat*1000||Y||Date.now(),D={...B,...I,iat:Z?void 0:Math.floor(E/1000),exp:B.exp?B.exp:G?Math.floor((E+G)/1000):void 0,nbf:B.nbf?B.nbf:H?Math.floor((E+H)/1000):void 0};if(X)Object.assign(B,D);if(N=Buffer.from(JSON.stringify(D),"utf-8").toString("base64").replace(wX,TX),!C){let v=Buffer.from(JSON.stringify(T),"utf-8").toString("base64").replace(wX,TX)+"."+N,f=J==="none"?"":_W(J,$,v);return v+"."+f}return m6($,{header:T,payload:B},(h,v)=>{if(h){let l=n.wrap(h,n.codes.keyFetchingError,"Cannot fetch key.");return C(l)}if(typeof v==="string")v=Buffer.from(v,"utf-8");else if(!(v instanceof Buffer))return C(new n(n.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a private key."));let f;try{let l=KW(v,J);if(J)MW(J,l);else T.alg=J=l;v=RW(v,J);let u0=Buffer.from(JSON.stringify(T),"utf-8").toString("base64").replace(wX,TX)+"."+N;f=u0+"."+_W(J,v,u0)}catch(l){return C(l)}C(null,f)}),w}IW.exports=function(J){let{key:Z,algorithm:X,noTimestamp:Y,mutatePayload:G,clockTimestamp:H,expiresIn:z,notBefore:V,jti:O,aud:F,iss:I,sub:B,nonce:L,kid:C,typ:w,header:T}={clockTimestamp:0,...J};if(X&&!FW.has(X))throw new n(n.codes.invalidOption,`The algorithm option must be one of the following values: ${o6}.`);let N=typeof Z,E=N==="object"&&Z&&Z.key&&Z.passphrase;if(X==="none"){if(Z)throw new n(n.codes.invalidOption,'The key option must not be provided when the algorithm option is "none".')}else if(!Z||N!=="string"&&!(Z instanceof Buffer)&&N!=="function"&&!E)throw new n(n.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(E&&!X)throw new n(n.codes.invalidAlgorithm,"When using password protected key you must provide the algorithm option.");if(Z&&N!=="function"){let v=KW(E?Z.key:Z,X);if(X)MW(X,v);else X=v;Z=RW(Z,X)}if(z){if(typeof z==="string")z=AW(z);if(typeof z!=="number")throw new n(n.codes.invalidOption,"The expiresIn option must be a positive number or a valid string.")}if(V){if(typeof V==="string")V=AW(V);if(typeof V!=="number"||V<0)throw new n(n.codes.invalidOption,"The notBefore option must be a positive number or a valid string.")}if(H&&(typeof H!=="number"||H<0))throw new n(n.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(O&&typeof O!=="string")throw new n(n.codes.invalidOption,"The jti option must be a string.");if(F&&typeof F!=="string"&&!Array.isArray(F))throw new n(n.codes.invalidOption,"The aud option must be a string or an array of strings.");if(I&&typeof I!=="string")throw new n(n.codes.invalidOption,"The iss option must be a string.");if(B&&typeof B!=="string")throw new n(n.codes.invalidOption,"The sub option must be a string.");if(L&&typeof L!=="string")throw new n(n.codes.invalidOption,"The nonce option must be a string.");if(C&&typeof C!=="string")throw new n(n.codes.invalidOption,"The kid option must be a string.");if(T&&typeof T!=="object")throw new n(n.codes.invalidOption,"The header option must be a object.");let h=Object.entries({jti:O,aud:F,iss:I,sub:B,nonce:L}).reduce((v,[f,l])=>{if(l!==void 0)v[f]=l;return v},{});return l6.bind(null,{key:Z,algorithm:X,noTimestamp:Y,mutatePayload:G,clockTimestamp:H,expiresIn:z,notBefore:V,kid:C,typ:w,isAsync:N==="function",additionalHeader:T,fixedPayload:h})}});var jW=s((fU,PW)=>{var{TokenError:r6,TOKEN_ERROR_CODES:i6}=c$(),t6=$X(),a6=VW(),e6=qW();PW.exports={TokenError:r6,TOKEN_ERROR_CODES:i6,createDecoder:t6,createVerifier:a6,createSigner:e6}});var{Glob:gW}=globalThis.Bun;var iX=new Map;function hW($){if(typeof $>"u")return[];if(!Array.isArray($))throw Error("disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A\u5FC5\u987B\u662F string[]");let J=[];for(let Z of $){if(typeof Z!=="string")throw Error("disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A\u6570\u7EC4\u5143\u7D20\u5FC5\u987B\u662F string");let X=Z.trim();if(!X)throw Error("disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A\u4E0D\u5141\u8BB8\u7A7A\u5B57\u7B26\u4E32");J.push(X)}return J}function bW($){let J=iX.get($);if(J)return J;let Z=new gW($);return iX.set($,Z),Z}function N$($){let J=hW($);if(J.length===0)return[];let Z=[];for(let X of J)try{let Y=bW(X);Z.push({type:"glob",raw:X,glob:Y})}catch(Y){throw Error(`disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1Aglob \u89C4\u5219 ${X} \u89E3\u6790\u5931\u8D25\uFF1A${Y?.message||String(Y)}`)}return Z}function i$($,J){for(let Z of J)if(Z.glob.match($))return!0;return!1}import{existsSync as mW}from"fs";import{isAbsolute as nW,join as Z1}from"path";import{pathToFileURL as dW}from"url";m0();function F$($){if(Array.isArray($)){let J=[];for(let Z of $)J.push(F$(Z));return J}if(o($)){let J={};for(let Z of Object.keys($))J[Z]=F$($[Z]);return J}return $}function J1($,J){if(J===void 0)return $;if(Array.isArray($)&&Array.isArray(J)){for(let Z of J)$.push(F$(Z));return $}if(o($)&&o(J)){for(let Z of Object.keys(J)){let X=J[Z];if(X===void 0)continue;let Y=$[Z];if(Array.isArray(Y)&&Array.isArray(X)){let G=[];for(let H of Y)G.push(F$(H));for(let H of X)G.push(F$(H));$[Z]=G;continue}if(o(Y)&&o(X)){$[Z]=J1(F$(Y),X);continue}$[Z]=F$(X)}return $}return F$(J)}function jZ(...$){let J={};for(let Z of $){if(Z===void 0)continue;J=J1(J,Z)}return J}m0();async function X1($){let{cwd:J=process.cwd(),dirs:Z,files:X,extensions:Y=[".ts",".js",".json"],mode:G="first",paths:H,defaults:z={}}=$;if(!Array.isArray(Z)||Z.length===0)throw Error("dirs \u5FC5\u987B\u662F\u975E\u7A7A\u6570\u7EC4");if(!Array.isArray(X)||X.length===0)throw Error("files \u5FC5\u987B\u662F\u975E\u7A7A\u6570\u7EC4");let V=[];for(let F of Z){let I=nW(F)?F:Z1(J,F);for(let B of X)for(let L of Y){let C=B.endsWith(L)?B:B+L,w=Z1(I,C);if(mW(w))try{let T=dW(w).href+`?t=${Date.now()}`,N;if(L===".json")N=(await import(T,{with:{type:"json"}})).default;else{let E=await import(T);if(N=E.default||E,N instanceof Promise)N=await N}if(!o(N))continue;if(V.push(N),G==="first"){let E=jZ(z,N);if(H&&H.length>0){let D={};for(let h of H){let v=qZ(E,h);if(v!==void 0)PZ(D,h,v)}return D}return E}break}catch{}}}let O=jZ(z,...V);if(H&&H.length>0){let F={};for(let I of H){let B=qZ(O,I);if(B!==void 0)PZ(F,I,B)}return F}return O}var sW={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:{}},BZ=new Map;async function Y1(){let X=BZ.get("development");if(X)return await X;let Y=(async()=>{let G=await X1({dirs:["configs"],files:["befly.common","befly.development"],extensions:[".json"],mode:"merge",defaults:sW}),H=G?.redis?.prefix;if(typeof H==="string"){if(H.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=${H}`)}return N$(G?.disableMenus),G})();BZ.set("development",Y);try{return await Y}catch(G){throw BZ.delete("development"),G}}a();m0();async function F1($){let J=!1;for(let Z of $)try{if(typeof Z?.name!=="string"||Z.name.trim()===""){P.warn(Object.assign({},b(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"){P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}if(typeof Z?.routePath!=="string"||Z.routePath.trim()==="")P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 routePath \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;else{let X=Z.routePath.trim();if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(X))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 routePath \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09"})),J=!0;if(!X.startsWith("/api/"))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 routePath \u5FC5\u987B\u4EE5 /api/ \u5F00\u5934"})),J=!0;if(X.includes(" "))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 routePath \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C"})),J=!0;if(X.includes("/api//"))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 routePath \u4E0D\u5141\u8BB8\u51FA\u73B0 /api//\uFF08\u91CD\u590D\u659C\u6760\uFF09"})),J=!0}if(typeof Z?.routePrefix!=="string"||Z.routePrefix.trim()==="")P.warn(Object.assign({},b(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()))P.warn(Object.assign({},b(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")P.warn(Object.assign({},b(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&&!o(Z.fields))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 fields \u5C5E\u6027\u5FC5\u987B\u662F\u5BF9\u8C61"})),J=!0;if(Z.required&&!Array.isArray(Z.required))P.warn(Object.assign({},b(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"))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0}catch(X){P.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();m0();var M1=["name","enable","deps","handler"];async function R1($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let X of $)try{if(!o(X)){P.warn(Object.assign({},b(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()===""){P.warn(Object.assign({},b(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 Y=X.customKeys;if(!Array.isArray(Y)){P.warn(Object.assign({},b(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(Y.some((V)=>typeof V!=="string")){P.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let G=Y.filter((V)=>!M1.includes(V));if(G.length>0){P.warn(Object.assign({},b(X,["handler"]),{msg:`\u94A9\u5B50\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${G.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${M1.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${Y.join(", ")}`})),J=!0;continue}let H=Y.includes("enable"),z=Y.includes("deps");if(H){if(typeof X.enable!=="boolean"){P.warn(Object.assign({},b(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===""){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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){P.warn(Object.assign({},b(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}`)){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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")){P.warn(Object.assign({},b(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"){P.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(Y){P.error({err:Y,item:X,msg:"\u94A9\u5B50\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u94A9\u5B50\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();gZ();function CH($){if(!$)return{ok:!1,reason:"path \u4E0D\u80FD\u4E3A\u7A7A"};if(!$.startsWith("/"))return{ok:!1,reason:"path \u5FC5\u987B\u4EE5 / \u5F00\u5934"};if($.length>1&&$.endsWith("/"))return{ok:!1,reason:"path \u672B\u5C3E\u4E0D\u80FD\u662F /\uFF08\u6839\u8DEF\u5F84 / \u9664\u5916\uFF09"};if($.includes("//"))return{ok:!1,reason:"path \u4E0D\u80FD\u5305\u542B //"};if($.includes(".."))return{ok:!1,reason:"path \u4E0D\u80FD\u5305\u542B .."};return{ok:!0,reason:""}}function w1($,J){if(J.length===0)return $;let Z=[];for(let X of $){let Y=typeof X?.path==="string"?String(X.path).trim():"";if(Y&&i$(Y,J))continue;let G=Array.isArray(X?.children)?X.children:null;if(G&&G.length>0){let H=w1(G,J);if(H.length>0)X.children=H;else delete X.children}Z.push(X)}return Z}var T1=async($,J={})=>{let Z=!1,X=await E1($),Y=N$(J.disableMenus),G=w1(X,Y),H=[];for(let V of G)H.push({menu:V,depth:1});let z=new Set;while(H.length>0){let V=H.pop(),O=V?.menu,F=typeof V?.depth==="number"?V.depth:0;if(O===null||typeof O!=="object"){Z=!0,P.warn({menu:O,msg:"\u83DC\u5355\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61"});continue}if(F>3){Z=!0,P.warn({path:O?.path,depth:F,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});continue}let I=O.children;if(typeof I<"u"&&!Array.isArray(I)){Z=!0,P.warn({path:O?.path,childrenType:typeof I,msg:"\u83DC\u5355 children \u5FC5\u987B\u662F\u6570\u7EC4"});continue}if(Array.isArray(I)&&I.length>0)if(F>=3)Z=!0,P.warn({path:O?.path,depth:F,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});else for(let T of I)H.push({menu:T,depth:F+1});let B=typeof O.path==="string"?O.path.trim():"",L=typeof O.name==="string"?O.name.trim():"",C=typeof O.sort==="number"?O.sort:999999;if(typeof O.path==="string")O.path=B;if(typeof O.name==="string")O.name=L;if(typeof O.sort>"u")O.sort=C;if(!B){Z=!0,P.warn({menu:O,msg:"\u83DC\u5355\u7F3A\u5C11 path\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});continue}let w=CH(B);if(!w.ok)Z=!0,P.warn({path:B,reason:w.reason,msg:"\u83DC\u5355 path \u4E0D\u5408\u6CD5"});if(!L)Z=!0,P.warn({path:B,menu:O,msg:"\u83DC\u5355\u7F3A\u5C11 name\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});if(typeof O.sort<"u"&&typeof O.sort!=="number")Z=!0,P.warn({path:B,sort:O.sort,msg:"\u83DC\u5355 sort \u5FC5\u987B\u662F number"});if(typeof O.sort==="number"&&(!Number.isFinite(O.sort)||O.sort<1))Z=!0,P.warn({path:B,sort:O.sort,msg:"\u83DC\u5355 sort \u6700\u5C0F\u503C\u4E3A 1"});if(z.has(B)){Z=!0,P.warn({path:B,msg:"\u83DC\u5355 path \u91CD\u590D\uFF08\u4E25\u683C\u6A21\u5F0F\u7981\u6B62\u91CD\u590D path\uFF09"});continue}z.add(B)}if(Z)throw Error("\u83DC\u5355\u7ED3\u6784\u68C0\u67E5\u5931\u8D25");return G};a();m0();var v1=["name","enable","deps","handler"];async function N1($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let X of $)try{if(!o(X)){P.warn(Object.assign({},b(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()===""){P.warn(Object.assign({},b(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 Y=X.customKeys;if(!Array.isArray(Y)){P.warn(Object.assign({},b(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(Y.some((V)=>typeof V!=="string")){P.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let G=Y.filter((V)=>!v1.includes(V));if(G.length>0){P.warn(Object.assign({},b(X,["handler"]),{msg:`\u63D2\u4EF6\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${G.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${v1.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${Y.join(", ")}`})),J=!0;continue}let H=Y.includes("enable"),z=Y.includes("deps");if(H){if(typeof X.enable!=="boolean"){P.warn(Object.assign({},b(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===""){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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){P.warn(Object.assign({},b(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}`)){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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")){P.warn(Object.assign({},b(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"){P.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(Y){P.error({err:Y,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 D1=["id","created_at","updated_at","deleted_at","state"],k1=["string","number","text","array_string","array_text","array_number_string","array_number_text"],y1=["name","type","min","max","default","detail","index","unique","nullable","unsigned","regexp"],EH=/^_?[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)*$/,wH=/^[\u4e00-\u9fa5a-zA-Z0-9 _-]+$/,x1=65535;async function f1($){let J=!1;for(let Z of $){if(Z.type!=="table")continue;let X=typeof Z.sourceName==="string"?Z.sourceName:"",Y=X?`${X}\u8868 `:"\u8868 ";try{let G=Z.fileName,H=Z.content||{};if(!EH.test(G)){P.warn(`${Y}${G} \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)){P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u89C4\u5219\u5FC5\u987B\u4E3A\u5BF9\u8C61`),J=!0;continue}if(D1.includes(z))P.warn(`${Y}${G} \u6587\u4EF6\u5305\u542B\u4FDD\u7559\u5B57\u6BB5 ${z}\uFF0C`+`\u4E0D\u80FD\u5728\u8868\u5B9A\u4E49\u4E2D\u4F7F\u7528\u4EE5\u4E0B\u5B57\u6BB5: ${D1.join(", ")}`),J=!0;let O=V,I=Object.keys(O).filter((N)=>!y1.includes(N));if(I.length>0)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u5305\u542B\u975E\u6CD5\u5C5E\u6027: ${I.join(", ")}\uFF0C`+`\u5141\u8BB8\u7684\u5C5E\u6027\u4E3A: ${y1.join(", ")}`),J=!0;if(!O.name||typeof O.name!=="string"){P.warn(`${Y}${G} \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"){P.warn(`${Y}${G} \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"))P.warn(`${Y}${G} \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"))P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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:L,min:C,max:w,default:T}=O;if(!wH.test(B))P.warn(`${Y}${G} \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(!k1.includes(L))P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u5B57\u6BB5\u7C7B\u578B "${L}" \u683C\u5F0F\u9519\u8BEF\uFF0C`+`\u5FC5\u987B\u4E3A${k1.join("\u3001")}\u4E4B\u4E00`),J=!0;if(L!=="number"&&O.unsigned!==void 0)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u5B57\u6BB5\u7C7B\u578B\u4E3A ${L}\uFF0C\u4E0D\u5141\u8BB8\u8BBE\u7F6E unsigned\uFF08\u4EC5 number \u7C7B\u578B\u6709\u6548\uFF09`),J=!0;if(O.unique===!0&&O.index===!0)P.warn(`${Y}${G} \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&&w!==void 0&&C!==null&&w!==null){if(C>w)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u6700\u5C0F\u503C "${C}" \u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u503C "${w}"`),J=!0}if(L==="text"||L==="array_text"||L==="array_number_text"){if(C!==void 0&&C!==null)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u7684 ${L} \u7C7B\u578B\u6700\u5C0F\u503C\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${C}"`),J=!0;if(w!==void 0&&w!==null)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u7684 ${L} \u7C7B\u578B\u6700\u5927\u957F\u5EA6\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${w}"`),J=!0;if(T!==void 0&&T!==null)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u4E3A ${L} \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0;if(O.index===!0)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u4E3A ${L} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u521B\u5EFA\u7D22\u5F15\uFF08index=true \u65E0\u6548\uFF09`),J=!0;if(O.unique===!0)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u4E3A ${L} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u552F\u4E00\u7EA6\u675F\uFF08unique=true \u65E0\u6548\uFF09`),J=!0}else if(L==="string"||L==="array_string"||L==="array_number_string"){if(w!==void 0&&(w===null||typeof w!=="number"))P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u4E3A ${L} \u7C7B\u578B\uFF0C`+`\u6700\u5927\u957F\u5EA6\u5FC5\u987B\u4E3A\u6570\u5B57\uFF0C\u5F53\u524D\u4E3A "${w}"`),J=!0;else if(w!==void 0&&w>x1)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u6700\u5927\u957F\u5EA6 ${w} \u8D8A\u754C\uFF0C`+`${L} \u7C7B\u578B\u957F\u5EA6\u5FC5\u987B\u5728 1..${x1} \u8303\u56F4\u5185`),J=!0}else if(L==="number"){if(T!==void 0&&T!==null&&typeof T!=="number")P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u4E3A number \u7C7B\u578B\uFF0C`+`\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A\u6570\u5B57\u6216 null\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0}}}catch(G){P.error({msg:`${Y}${Z.fileName} \u89E3\u6790\u5931\u8D25`,err:G}),J=!0}}if(J)throw Error("\u8868\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var{SQL:g1,RedisClient:TH}=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",X=J.host||"127.0.0.1",Y=J.port||3306,G=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}://${G}:${H}@${X}:${Y}/${z}`}let O;if(Z==="sqlite")O=new g1(V);else O=new g1({url:V,max:J.poolMax??1,bigint:!1});try{let I=(async()=>{let L="";if(Z==="sqlite")L=(await O`SELECT sqlite_version() AS version`)?.[0]?.version;else if(Z==="postgresql"||Z==="postgres")L=(await O`SELECT version() AS version`)?.[0]?.version;else L=(await O`SELECT VERSION() AS version`)?.[0]?.version;return L})(),B=new Promise((L,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(F){P.error({err:F,msg:"[Connect] SQL \u8FDE\u63A5\u5931\u8D25"});try{await O?.close()}catch{}throw F}}static async disconnectSql(){if(this.sqlClient){try{await this.sqlClient.close()}catch($){P.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,Y=J.username||"",G=J.password||"",H=J.db||0,z="";if(Y&&G)z=`${Y}:${G}@`;else if(G)z=`:${G}@`;let V=`redis://${z}${Z}:${X}/${H}`,O=new TH(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 P.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($){P.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 P.error({err:J,msg:"\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25"}),await this.disconnect(),J}}static async disconnect(){await this.disconnectSql(),await this.disconnectRedis()}static isConnected(){return{sql:this.sqlClient!==null,redis:this.redisClient!==null}}static getStatus(){let $=Date.now();return{sql:{connected:this.sqlClient!==null,connectedAt:this.sqlConnectedAt,uptime:this.sqlConnectedAt?$-this.sqlConnectedAt:null,poolMax:this.sqlPoolMax},redis:{connected:this.redisClient!==null,connectedAt:this.redisConnectedAt,uptime:this.redisConnectedAt?$-this.redisConnectedAt:null}}}static __setMockSql($){this.sqlClient=$}static __setMockRedis($){this.redisClient=$}static __reset(){this.sqlClient=null,this.redisClient=null,this.sqlConnectedAt=null,this.redisConnectedAt=null,this.sqlPoolMax=1}}a();a();var PJ={"@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 h1($,J,Z){if(!$||typeof $!=="object")return $;let X={};for(let[Y,G]of Object.entries($)){if(typeof G==="string"&&G.startsWith("@")){if(PJ[G]){X[Y]=PJ[G];continue}let H=Object.keys(PJ).join(", ");throw Error(`API [${J}] (${Z}) \u5B57\u6BB5 [${Y}] \u5F15\u7528\u4E86\u672A\u5B9A\u4E49\u7684\u9884\u8BBE\u5B57\u6BB5 "${G}"\u3002\u53EF\u7528\u7684\u9884\u8BBE\u5B57\u6BB5\u6709: ${H}`)}X[Y]=G}return X}async function b1($){let J=new Map;for(let Z of $){let X=Z.type;if(X&&X!=="api")continue;try{let Y=Z;Y.fields=h1(Y.fields||{},Y.name,Y.routePath),J.set(Y.routePath,Y)}catch(Y){throw P.error({err:Y,api:Z.relativePath,file:Z.filePath,msg:"\u63A5\u53E3\u52A0\u8F7D\u5931\u8D25"}),Y}}return J}a();m0();function jJ($,J={}){let Z=J.moduleLabel||"\u6A21\u5757",X=J.getName||((I)=>{let B=I.moduleName;if(typeof B==="string"&&B.trim()!=="")return B;return K$(I.fileName)}),Y=J.getDeps||((I)=>I.deps),G=[],H=new Set,z=new Set,V={},O=!0;for(let I of $){let B=X(I);if(typeof B!=="string"||B.trim()===""){P.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]){P.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),L=Y(I);if(!Array.isArray(L)){P.error({module:B,item:I,msg:`${Z} \u7684 deps \u5FC5\u987B\u662F\u6570\u7EC4`}),O=!1;continue}for(let C of L){if(typeof C!=="string"){P.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])P.error({module:B,dependency:C,msg:`${Z} \u4F9D\u8D56\u672A\u627E\u5230`}),O=!1}}if(!O)return!1;let F=(I)=>{if(H.has(I))return;if(z.has(I)){P.error({module:I,msg:`${Z} \u5FAA\u73AF\u4F9D\u8D56`}),O=!1;return}let B=V[I];if(!B)return;let L=Y(B);z.add(I);for(let C of L)F(C);z.delete(I),H.add(I),G.push(B)};for(let I of $){let B=X(I);F(B)}return O?G:!1}async function c1($){let J=[],Z=$.filter((Y)=>{let G=Y?.moduleName;if(typeof G!=="string"||G.trim()==="")return!1;if(Y?.enable===!1)return!1;return!0}),X=jJ(Z,{moduleLabel:"\u94A9\u5B50"});if(X===!1)throw Error("\u94A9\u5B50\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let Y of X){let G=Y.moduleName,H=Y;J.push({name:G,enable:!0,deps:H.deps,handler:H.handler})}return J}a();async function p1($,J){let Z=[],X=$.filter((G)=>{let H=G?.moduleName;if(typeof H!=="string"||H.trim()==="")return!1;if(G?.enable===!1)return!1;return!0}),Y=jJ(X,{moduleLabel:"\u63D2\u4EF6"});if(Y===!1)throw Error("\u63D2\u4EF6\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let G of Y){let H=G.moduleName,z=G;try{let V=typeof z.handler==="function"?await z.handler(J):{};J[H]=V,Z.push({name:H,enable:!0,deps:z.deps,handler:z.handler})}catch(V){throw P.error({err:V,plugin:H,msg:"\u63D2\u4EF6\u521D\u59CB\u5316\u5931\u8D25"}),V}}return Z}KJ();a();function u1($,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 Y=$.headers.get("cf-connecting-ip");if(typeof Y==="string"&&Y.trim())return Y.trim();let G=$.headers.get("x-client-ip");if(typeof G==="string"&&G.trim())return G.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 q$($,J,Z=1,X=null,Y=null,G=null){if($.requestId)P.info({event:"request_blocked",reason:J,reasonCode:G,code:Z,detail:Y,msg:"request blocked"});return Response.json({code:Z,msg:J,data:X,detail:Y},{headers:$.corsHeaders})}function hZ($){if($.api&&$.requestId)P.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,Y)=>typeof Y==="bigint"?Y.toString():Y);return new Response(Z,{headers:{...$.corsHeaders,"Content-Type":"application/json"}})}else return Response.json(J,{headers:$.corsHeaders})}return Response.json({code:1,msg:"\u672A\u751F\u6210\u54CD\u5E94"},{headers:$.corsHeaders})}m0();function m1($,J,Z){return async(X,Y)=>{let G=$1(),z=new URL(X.url).pathname||"/",V=u1(X,Y),O=Date.now(),F={method:X.method,body:{},user:{},req:X,now:O,ip:V,headers:X.headers,route:z,requestId:G,corsHeaders:{"X-Request-ID":G},api:$.get(z),response:void 0,result:void 0};return H1({requestId:G,method:X.method,route:z,ip:V,now:O},async()=>{try{for(let I of J)if(await I.handler(Z,F),F.response)return F.response;if(F.api&&X.method!=="OPTIONS"){let I={event:"request",apiName:F.api.name};if(F.body&&Object.keys(F.body).length>0)I.body=F.body;I.msg="request",P.info(I)}if(!F.api){if(X.method!=="OPTIONS")F.response=Response.json({code:1,msg:"\u63A5\u53E3\u4E0D\u5B58\u5728"},{headers:F.corsHeaders})}else if(F.api.handler){let I=await F.api.handler(Z,F);if(I instanceof Response)F.response=I;else F.result=I}return hZ(F)}catch(I){let B=F.api?z:X.url;return P.error({err:I,path:B,msg:"\u8BF7\u6C42\u9519\u8BEF"}),F.result={code:1,msg:"\u5185\u90E8\u670D\u52A1\u9519\u8BEF"},hZ(F)}})}}I$();a();I$();import{fileURLToPath as vH}from"url";var NH=vH(import.meta.url),P$=IJ(NH);var d8=L$(P$).endsWith("/dist")?P$:d(P$,"dist"),s8=d(P$,"checks"),o8=d(P$,"plugins"),l8=d(P$,"hooks"),r8=d(P$,"apis"),i8=d(P$,"tables"),d0=process.cwd(),t8=d(d0,"checks"),a8=d(d0,"plugins"),e8=d(d0,"hooks"),$4=d(d0,"apis"),J4=d(d0,"tables"),n1=d(d0,"addons");function BJ($,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 d1($=void 0){return async(J)=>{let Z=BJ(J,$),X=new URL(J.url),Y=d(d0,"public",X.pathname);try{if(J.method==="OPTIONS")return new Response(null,{status:204,headers:Z});let G=Bun.file(Y);if(await G.exists())return new Response(G,{headers:{"Content-Type":G.type||"application/octet-stream",...Z}});else return Response.json({code:1,msg:"\u6587\u4EF6\u672A\u627E\u5230"},{headers:Z})}catch(G){return P.error({err:G,msg:"\u9759\u6001\u6587\u4EF6\u5904\u7406\u5931\u8D25"}),Response.json({code:1,msg:"\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25"},{headers:Z})}}}a();m0();async function s1($,J){if(!$.db)throw Error("syncApi: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncApi: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_api")).data){P.debug(`${"addon_admin_api"} \u8868\u4E0D\u5B58\u5728`);return}let Y=(await $.db.getAll({table:"addon_admin_api",fields:["id","routePath","name","addonName","state"],where:{state$gte:0}})).data.lists||[],G=eX(Y,(F)=>F.routePath),H=[],z=[],V=[],O=new Set;for(let F of J){let I=F.type;if(I&&I!=="api")continue;let B=F.routePath;O.add(F.routePath);let L=G[B];if(L){if(F.name!==L.name||F.routePath!==L.routePath||F.addonName!==L.addonName)z.push({id:L.id,api:F})}else H.push(F)}for(let F of Y)if(!O.has(F.routePath))V.push(F.id);if(z.length>0)try{await $.db.updBatch("addon_admin_api",z.map((F)=>{return{id:F.id,data:{name:F.api.name,routePath:F.api.routePath,addonName:F.api.addonName}}}))}catch(F){P.error({err:F,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u66F4\u65B0\u5931\u8D25"})}if(H.length>0)try{await $.db.insBatch("addon_admin_api",H.map((F)=>{return{name:F.name,routePath:F.routePath,addonName:F.addonName}}))}catch(F){P.error({err:F,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u65B0\u589E\u5931\u8D25"})}if(V.length>0)try{await $.db.delForceBatch("addon_admin_api",V)}catch(F){P.error({err:F,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u5220\u9664\u5931\u8D25"})}}async function o1($){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 DH}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=DH("RSA-SHA256");return X.update($),X.sign(J,Z)}static hmacSha256($,J,Z="hex"){let X=new Bun.CryptoHasher("sha256",$);return X.update(J),X.digest(Z)}static sha512($,J="hex"){let Z=new Bun.CryptoHasher("sha512");return Z.update($),Z.digest(J)}static hmacSha512($,J,Z="hex"){let X=new Bun.CryptoHasher("sha512",$);return X.update(J),X.digest(Z)}static hash($,J,Z="hex"){let X=new Bun.CryptoHasher($);return X.update(J),X.digest(Z)}static hmac($,J,Z,X="hex"){let Y=new Bun.CryptoHasher($,J);return Y.update(Z),Y.digest(X)}static async hashFile($,J="sha256",Z="hex"){let X=Bun.file($),Y=new Bun.CryptoHasher(J),H=X.stream().getReader();try{while(!0){let{done:z,value:V}=await H.read();if(z)break;Y.update(V)}return Y.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 Y=0;Y<Z.length;Y++)X+=Z[Y].toString(16).padStart(2,"0");return X.slice(0,$)}static fastHash($,J=0){let Z=Bun.hash($,J);return typeof Z==="bigint"?Number(Z):Z}}a();async function l1($,J={}){if(!J.devPassword)return;let Z=typeof J.devEmail==="string"&&J.devEmail.length>0?J.devEmail:"dev@qq.com";if(!$.db)throw Error("syncDev: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncDev: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_admin")).data){P.debug("addon_admin_admin \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_role")).data){P.debug("addon_admin_role \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_menu")).data){P.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}let X=await $.db.getAll({table:"addon_admin_menu",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),Y=Array.from(new Set((X.data.lists||[]).map((L)=>typeof L?.path==="string"?L.path.trim():"").filter((L)=>L.length>0))),G=await $.db.tableExists("addon_admin_api"),H=[];if(G.data){let L=await $.db.getAll({table:"addon_admin_api",fields:["routePath"],where:{state$gte:0},orderBy:["id#ASC"]});H=Array.from(new Set((L.data.lists||[]).map((C)=>{if(typeof C?.routePath!=="string")throw Error("syncDev: addon_admin_api.routePath \u5FC5\u987B\u662F\u5B57\u7B26\u4E32");let w=C.routePath.trim();if(w.length===0)throw Error("syncDev: addon_admin_api.routePath \u4E0D\u5141\u8BB8\u4E3A\u7A7A\u5B57\u7B26\u4E32");if(!w.startsWith("/"))throw Error(`syncDev: addon_admin_api.routePath \u5FC5\u987B\u662F pathname\uFF08\u4EE5 / \u5F00\u5934\uFF09\uFF0C\u5F53\u524D\u503C=${w}`);return w})))}let z=[{code:"dev",name:"\u5F00\u53D1\u8005\u89D2\u8272",description:"\u62E5\u6709\u6240\u6709\u83DC\u5355\u548C\u63A5\u53E3\u6743\u9650\u7684\u5F00\u53D1\u8005\u89D2\u8272",menus:Y,apis:H,sort:0},{code:"user",name:"\u7528\u6237\u89D2\u8272",description:"\u666E\u901A\u7528\u6237\u89D2\u8272",menus:[],apis:[],sort:1},{code:"admin",name:"\u7BA1\u7406\u5458\u89D2\u8272",description:"\u7BA1\u7406\u5458\u89D2\u8272",menus:[],apis:[],sort:2},{code:"guest",name:"\u8BBF\u5BA2\u89D2\u8272",description:"\u8BBF\u5BA2\u89D2\u8272",menus:[],apis:[],sort:3}],V=null;for(let L of z){let C=await $.db.getOne({table:"addon_admin_role",where:{code:L.code}});if(C.data){let{menus:w,apis:T}=L,N=Array.isArray(C.data.menus)?C.data.menus:[],E=Array.isArray(C.data.apis)?C.data.apis:[],D=N.length!==w.length||N.some((f,l)=>f!==w[l]),h=E.length!==T.length||E.some((f,l)=>f!==T[l]);if(C.data.name!==L.name||C.data.description!==L.description||D||h||C.data.sort!==L.sort)await $.db.updData({table:"addon_admin_role",where:{code:L.code},data:{name:L.name,description:L.description,menus:L.menus,apis:L.apis,sort:L.sort}});if(L.code==="dev")V=C.data}else{let w=await $.db.insData({table:"addon_admin_role",data:L});if(L.code==="dev")V={id:w.data}}}if(!V){P.error("dev \u89D2\u8272\u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u521B\u5EFA\u5F00\u53D1\u8005\u8D26\u53F7");return}let O=y$.sha256(J.devPassword+"befly"),F=await y$.hashPassword(O),I={nickname:"\u5F00\u53D1\u8005",email:Z,username:"dev",password:F,roleCode:"dev",roleType:"admin"};if((await $.db.getOne({table:"addon_admin_admin",where:{email:Z}})).data)await $.db.updData({table:"addon_admin_admin",where:{email:Z},data:I});else await $.db.insData({table:"addon_admin_admin",data:I})}a();gZ();function kH($){let J=new Map,Z=[];for(let X of $)Z.push({menu:X,parentPathFromTree:""});while(Z.length>0){let X=Z.pop(),Y=X?X.menu:null;if(!Y)continue;let G=typeof Y.path==="string"?Y.path:"",H=Y.children;if(H&&Array.isArray(H)&&H.length>0){let I=typeof G==="string"?G:"";for(let B of H)Z.push({menu:B,parentPathFromTree:I})}if(!G)continue;let z=typeof Y.name==="string"?Y.name:"";if(!z)continue;let V=typeof Y.sort==="number"?Y.sort:999999,F=typeof Y.parentPath==="string"?Y.parentPath:typeof X?.parentPathFromTree==="string"?X.parentPathFromTree:C1(G);J.set(G,{path:G,name:z,sort:V,parentPath:F})}return J}async function r1($,J){if(!$.db)throw Error("syncMenu: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncMenu: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.config)throw Error("syncMenu: ctx.config \u672A\u521D\u59CB\u5316\uFF08config \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_menu")).data){P.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}let Z=N$($.config?.disableMenus),X=Z.length===0?J:(()=>{let z=(V)=>{let O=[];for(let F of V){let I=typeof F?.path==="string"?String(F.path).trim():"";if(I&&i$(I,Z))continue;let B=Array.isArray(F?.children)?F.children:null;if(B&&B.length>0){let L=z(B);if(L.length>0)F.children=L;else delete F.children}O.push(F)}return O};return z(J)})(),Y=kH(X),G=new Set;for(let z of Y.keys())G.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||[],F=O.filter((E)=>typeof E?.state==="number"&&E.state>=0),I=new Map,B=new Set,L=new Map;for(let E of F){if(typeof E?.path!=="string"||!E.path)continue;if(typeof E?.id!=="number")continue;let D=I.get(E.path);if(!D){I.set(E.path,E);continue}let h=typeof D?.id==="number"?D.id:0,v=E.id;if(v>h){if(I.set(E.path,E),h>0)B.add(h);let f=L.get(E.path)||{keptId:v,removedIds:[]};if(f.keptId=v,h>0)f.removedIds.push(h);L.set(E.path,f)}else{if(v>0)B.add(v);let f=L.get(E.path)||{keptId:h,removedIds:[]};if(f.keptId=h,v>0)f.removedIds.push(v);L.set(E.path,f)}}if(L.size>0){let E=[];for(let D of L.entries()){let h=D[0],v=D[1];if(E.push({path:h,keptId:v.keptId,removedIds:v.removedIds}),E.length>=10)break}P.warn({table:H,duplicatePaths:L.size,duplicateIds:B.size,examples:E,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=[],w=[];for(let E of Y.values()){let D=I.get(E.path);if(D){let h=typeof D.parentPath==="string"?D.parentPath:"";if(D.name!==E.name||D.sort!==E.sort||h!==E.parentPath)C.push({id:D.id,data:{name:E.name,path:E.path,parentPath:E.parentPath,sort:E.sort}})}else w.push({name:E.name,path:E.path,parentPath:E.parentPath,sort:E.sort})}if(C.length>0)await z.updBatch(H,C);if(w.length>0)await z.insBatch(H,w);let T=new Set;if(Z.length>0)for(let E of O){let D=typeof E?.path==="string"?String(E.path).trim():"";if(!D)continue;if(i$(D,Z)){if(typeof E?.id==="number"&&E.id>0)T.add(E.id)}}for(let E of F){if(typeof E?.path!=="string"||!E.path)continue;if(!G.has(E.path)){if(typeof E?.id==="number")T.add(E.id)}}for(let E of B)if(typeof E==="number"&&E>0)T.add(E);let N=Array.from(T);if(N.length>0)await z.delForceBatch(H,N)})}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 x$=null;function f$($){let J=Error(`\u672A\u77E5\u6570\u636E\u5E93\u65B9\u8A00: ${String($)}`);if($!=="mysql"&&$!=="postgresql"&&$!=="sqlite")throw J;if(!x$)x$=new Map,x$.set("mysql",new SJ),x$.set("postgresql",new i1),x$.set("sqlite",new t1);let Z=x$.get($);if(!Z)throw J;return Z}function LJ($){if($.dialect==="mysql")return{columns:{sql:"SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION",params:[$.dbName,$.table]}};if($.dialect==="postgresql"){let X=$.schema&&$.schema.trim()!==""?$.schema:"public",Y={sql:"SELECT column_name, data_type, character_maximum_length, is_nullable, column_default FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position",params:[X,$.table]},G={sql:"SELECT a.attname AS column_name, col_description(c.oid, a.attnum) AS column_comment FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname = ? AND c.relname = ? AND a.attnum > 0",params:[X,$.table]};return{columns:Y,comments:G}}return{columns:f$("sqlite").getTableColumnsQuery($.table)}}function bZ($){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 SJ{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 i1{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 t1{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();m0();var EJ=async($,J)=>{try{let Z=[];if(!Array.isArray(J))throw Error("syncTable(items) \u53C2\u6570\u5FC5\u987B\u662F\u6570\u7EC4");if(!$)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx");if(!$.db)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.db");if(!$.redis)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.redis");if(!$.config)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.config");let X=String($.config.db?.type||"mysql").toLowerCase(),Y="mysql";if(X==="postgres"||X==="postgresql")Y="postgresql";else if(X==="sqlite")Y="sqlite";await yH(Y,$.db);let G=$.config.db?.database||"",H={dbDialect:Y,db:$.db,dbName:G};for(let z of J){if(!z||z.type!=="table")continue;if(z.source!=="app"&&z.source!=="addon"&&z.source!=="core"){P.warn(`syncTable \u8DF3\u8FC7\u672A\u77E5\u6765\u6E90\u8868\u5B9A\u4E49: source=${String(z.source)} fileName=${String(z.fileName)}`);continue}let V=u(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_${u(z.addonName)}_${V}`}let F=z.content;if(!F||typeof F!=="object")throw Error(`syncTable \u8868\u5B9A\u4E49\u65E0\u6548: table=${O}`);for(let B of Object.values(F))XY(B);if(await QY(H,O))await gH(H,O,F);else await VY(H,O,F);Z.push(O)}if(Z.length>0){let z=Z.map((V)=>X0.tableColumns(V));await $.redis.delBatch(z)}}catch(Z){throw P.error({err:Z,msg:"\u6570\u636E\u5E93\u540C\u6B65\u5931\u8D25"}),Z}},S$={MYSQL_MIN_MAJOR:8,POSTGRES_MIN_MAJOR:17,SQLITE_MIN_VERSION:"3.50.0",SQLITE_MIN_VERSION_NUM:35000},e1={length:"\u957F\u5EA6",datatype:"\u7C7B\u578B",comment:"\u6CE8\u91CA",default:"\u9ED8\u8BA4\u503C",nullable:"\u53EF\u7A7A\u7EA6\u675F",unique:"\u552F\u4E00\u7EA6\u675F"},$Y={ENGINE:"InnoDB",CHARSET:"utf8mb4",COLLATE:"utf8mb4_0900_ai_ci"},XJ=[{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"}],pZ=XJ.filter(($)=>$.needsIndex).map(($)=>$.name),JY={};for(let $ of XJ)JY[$.name]=$;var ZY={DB_VERSION_REQUIREMENTS:S$,CHANGE_TYPE_LABELS:e1,MYSQL_TABLE_CONFIG:$Y,SYSTEM_INDEX_FIELDS:pZ,getTypeMapping:wJ,quoteIdentifier:Y0,escapeComment:TJ,applyFieldDefaults:XY,isStringOrArrayType:ZJ,getSqlType:uZ,resolveDefaultValue:YJ,generateDefaultSql:vJ,buildIndexSQL:CJ,buildSystemColumnDefs:GY,buildBusinessColumnDefs:WY,generateDDLClause:cZ,isCompatibleTypeChange:HY,compareFieldDefinition:UY,tableExistsRuntime:QY,getTableColumnsRuntime:zY,getTableIndexesRuntime:mZ,createRuntime:($,J,Z="")=>{return{dbDialect:$,db:J,dbName:Z}}};EJ.TestKit=ZY;Object.defineProperty(EJ,"TestKit",{value:ZY,writable:!1,enumerable:!0,configurable:!1});function wJ($){return{number:$==="sqlite"?"INTEGER":$==="postgresql"?"BIGINT":"BIGINT",string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",text:$==="mysql"?"MEDIUMTEXT":"TEXT",array_string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",array_text:$==="mysql"?"MEDIUMTEXT":"TEXT",array_number_string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",array_number_text:$==="mysql"?"MEDIUMTEXT":"TEXT"}}function Y0($,J){return f$($).quoteIdent(J)}function TJ($){return String($).replace(/"/g,"\\\"")}function XY($){$.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 ZJ($){return $==="string"||$==="array_string"||$==="array_number_string"}function uZ($,J,Z,X=!1){let Y=wJ($);if(ZJ(J))return`${Y[J]}(${Z})`;let G=Y[J]||"TEXT";if($==="mysql"&&J==="number"&&X)return`${G} UNSIGNED`;return G}function YJ($,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 vJ($,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 CJ($,J,Z,X,Y){let G=Y0($,J),H=Y0($,Z),z=Y0($,X);if($==="mysql"){let V=[];if(Y==="create")V.push(`ADD INDEX ${H} (${z})`);else V.push(`DROP INDEX ${H}`);return`ALTER TABLE ${G} ALGORITHM=INPLACE, LOCK=NONE, ${V.join(", ")}`}if($==="postgresql"){if(Y==="create")return`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${H} ON ${G}(${z})`;return`DROP INDEX CONCURRENTLY IF EXISTS ${H}`}if(Y==="create")return`CREATE INDEX IF NOT EXISTS ${H} ON ${G}(${z})`;return`DROP INDEX IF EXISTS ${H}`}function YY($,J){let Z=JY[J];if(!Z)return null;let X=Y0($,Z.name);if($==="mysql")return`${X} ${Z.mysqlDdl} COMMENT "${TJ(Z.comment)}"`;if($==="postgresql")return`${X} ${Z.pgDdl}`;return`${X} ${Z.sqliteDdl}`}function GY($){let J=[];for(let Z of XJ){let X=YY($,Z.name);if(X)J.push(X)}return J}function WY($,J){let Z=[];for(let[X,Y]of Object.entries(J)){let G=u(X),H=Y0($,G),z=uZ($,Y.type,Y.max,Y.unsigned),V=YJ(Y.default,Y.type),O=vJ(V,Y.type),F=Y.unique?" UNIQUE":"",I=Y.nullable?" NULL":" NOT NULL";if($==="mysql")Z.push(`${H} ${z}${F}${I}${O} COMMENT "${TJ(Y.name)}"`);else Z.push(`${H} ${z}${F}${I}${O}`)}return Z}function cZ($,J,Z,X=!1){let Y=u(J),G=Y0($,Y),H=uZ($,Z.type,Z.max,Z.unsigned),z=YJ(Z.default,Z.type),V=vJ(z,Z.type),O=Z.unique?" UNIQUE":"",F=Z.nullable?" NULL":" NOT NULL";if($==="mysql")return`${X?"ADD COLUMN":"MODIFY COLUMN"} ${G} ${H}${O}${F}${V} COMMENT "${TJ(Z.name)}"`;if($==="postgresql"){if(X)return`ADD COLUMN IF NOT EXISTS ${G} ${H}${O}${F}${V}`;return`ALTER COLUMN ${G} TYPE ${H}`}if(X)return`ADD COLUMN IF NOT EXISTS ${G} ${H}${O}${F}${V}`;return""}async function a1($,J){try{return await $.unsafe(J),!0}catch(Z){if(J.includes("ALGORITHM=INSTANT")){let X=J.replace(/ALGORITHM=INSTANT/g,"ALGORITHM=INPLACE");try{return await $.unsafe(X),!0}catch{let Y=J;return Y=Y.replace(/\bALGORITHM\s*=\s*(INPLACE|INSTANT)\b\s*,?\s*/g,"").replace(/\bLOCK\s*=\s*(NONE|SHARED|EXCLUSIVE)\b\s*,?\s*/g,""),Y=Y.replace(/,\s*,/g,", ").replace(/,\s*$/g,"").replace(/\s{2,}/g," ").trim(),await $.unsafe(Y),!0}}else throw Z}}function HY($,J){let Z=String($||"").toLowerCase(),X=String(J||"").toLowerCase();if(Z===X)return!1;let Y=Z.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),G=X.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),H=["tinyint","smallint","mediumint","int","integer","bigint"],z=H.indexOf(Y),V=H.indexOf(G);if(z!==-1&&V!==-1&&V>z)return!0;if(Y==="varchar"&&(G==="text"||G==="mediumtext"||G==="longtext"))return!0;if(Y==="character varying"&&G==="text")return!0;return!1}async function QY($,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=f$($.dbDialect).tableExistsQuery(J,Z);return((await $.db.unsafe(X.sql,X.params)).data?.[0]?.count||0)>0}catch(Z){let X=String(Z?.message||Z),Y=Error(`runtime I/O \u5931\u8D25: op=tableExists table=${J} err=${X}`);if(Z?.sqlInfo)Y.sqlInfo=Z.sqlInfo;throw Y}}async function zY($,J){let Z={};try{if($.dbDialect==="mysql"){let X=LJ({dialect:"mysql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.columns.sql,X.columns.params);for(let G of Y.data){let H=G.COLUMN_DEFAULT;Z[G.COLUMN_NAME]={type:G.DATA_TYPE,columnType:G.COLUMN_TYPE,length:G.CHARACTER_MAXIMUM_LENGTH,max:G.CHARACTER_MAXIMUM_LENGTH,nullable:G.IS_NULLABLE==="YES",defaultValue:H,comment:G.COLUMN_COMMENT}}}else if($.dbDialect==="postgresql"){let X=LJ({dialect:"postgresql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.columns.sql,X.columns.params),G=X.comments?(await $.db.unsafe(X.comments.sql,X.comments.params)).data:[],H={};for(let z of G)H[z.column_name]=z.column_comment;for(let z of Y.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=LJ({dialect:"sqlite",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.columns.sql,X.columns.params);for(let G of Y.data){let H=String(G.type||"").toUpperCase(),z=null,V=/^(\w+)\s*\((\d+)\)/.exec(H);if(V)H=V[1],z=Number(V[2]);Z[G.name]={type:H.toLowerCase(),columnType:H.toLowerCase(),length:z,max:z,nullable:G.notnull===0,defaultValue:G.dflt_value,comment:null}}}return Z}catch(X){let Y=String(X?.message||X),G=Error(`runtime I/O \u5931\u8D25: op=getTableColumns table=${J} err=${Y}`);if(X?.sqlInfo)G.sqlInfo=X.sqlInfo;throw G}}async function mZ($,J){let Z={};try{if($.dbDialect==="mysql"){let X=bZ({dialect:"mysql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.sql,X.params);for(let G of Y.data){if(!Z[G.INDEX_NAME])Z[G.INDEX_NAME]=[];Z[G.INDEX_NAME].push(G.COLUMN_NAME)}}else if($.dbDialect==="postgresql"){let X=bZ({dialect:"postgresql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.sql,X.params);for(let G of Y.data){let H=/\(([^)]+)\)/.exec(G.indexdef);if(H){let z=H[1].replace(/"/g,"").trim();Z[G.indexname]=[z]}}}else if($.dbDialect==="sqlite"){let X=Y0("sqlite",J),Y=await $.db.unsafe(`PRAGMA index_list(${X})`);for(let G of Y.data){let H=Y0("sqlite",G.name),V=(await $.db.unsafe(`PRAGMA index_info(${H})`)).data.map((O)=>O.name);if(V.length===1)Z[G.name]=V}}return Z}catch(X){let Y=String(X?.message||X),G=Error(`runtime I/O \u5931\u8D25: op=getTableIndexes table=${J} err=${Y}`);if(X?.sqlInfo)G.sqlInfo=X.sqlInfo;throw G}}async function yH($,J){if(!J)throw Error("SQL \u6267\u884C\u5668\u672A\u521D\u59CB\u5316");if($==="mysql"){let Z=await J.unsafe("SELECT VERSION() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 MySQL \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,Y=parseInt(String(X).split(".")[0],10);if(!Number.isFinite(Y)||Y<S$.MYSQL_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u4EC5\u652F\u6301 MySQL ${S$.MYSQL_MIN_MAJOR}.0+\uFF0C\u5F53\u524D\u7248\u672C: ${X}`);return}if($==="postgresql"){let Z=await J.unsafe("SELECT version() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 PostgreSQL \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,Y=/PostgreSQL\s+(\d+)/i.exec(X),G=Y?parseInt(Y[1],10):NaN;if(!Number.isFinite(G)||G<S$.POSTGRES_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 PostgreSQL >= ${S$.POSTGRES_MIN_MAJOR}\uFF0C\u5F53\u524D: ${X}`);return}if($==="sqlite"){let Z=await J.unsafe("SELECT sqlite_version() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 SQLite \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,[Y,G,H]=String(X).split(".").map((V)=>parseInt(V,10)||0),z=Y*1e4+G*100+H;if(!Number.isFinite(z)||z<S$.SQLITE_MIN_VERSION_NUM)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 SQLite >= ${S$.SQLITE_MIN_VERSION}\uFF0C\u5F53\u524D: ${X}`);return}}function UY($,J,Z){let X=[];if($!=="sqlite"&&ZJ(Z.type)){if(J.max!==Z.max)X.push({type:"length",current:J.max,expected:Z.max})}if($!=="sqlite"){let O=J.comment||"";if(O!==Z.name)X.push({type:"comment",current:O,expected:Z.name})}let G=wJ($)[Z.type].toLowerCase(),H=J.type.toLowerCase();if(H!==G)X.push({type:"datatype",current:H,expected:G});let z=Z.nullable;if(J.nullable!==z)X.push({type:"nullable",current:J.nullable,expected:z});let V=YJ(Z.default,Z.type);if(String(J.defaultValue)!==String(V))X.push({type:"default",current:J.defaultValue,expected:V});return X}async function xH($,J,Z){if($.dbDialect!=="sqlite")throw Error(`rebuildSqliteTable \u4EC5\u652F\u6301 sqlite \u65B9\u8A00\uFF0C\u5F53\u524D: ${String($.dbDialect)}`);let X=Y0("sqlite",J),G=(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)=>u(I))],V=`${J}__tmp__${Date.now()}`;await VY($,V,Z);let O=z.filter((I)=>G.includes(I));if(O.length>0){let I=O.map((L)=>Y0("sqlite",L)).join(", "),B=Y0("sqlite",V);await $.db.unsafe(`INSERT INTO ${B} (${I}) SELECT ${I} FROM ${X}`)}await $.db.unsafe(`DROP TABLE ${X}`);let F=Y0("sqlite",V);await $.db.unsafe(`ALTER TABLE ${F} RENAME TO ${X}`)}async function fH($,J,Z,X){if(!X||!X.changed)return;if($.dbDialect==="sqlite")if(X.modifyClauses.length>0||X.defaultClauses.length>0)await xH($,J,Z);else for(let Y of X.addClauses){let G=`ALTER TABLE ${Y0($.dbDialect,J)} ${Y}`;await $.db.unsafe(G)}else{let Y=[...X.addClauses,...X.modifyClauses];if(Y.length>0){let G=Y0($.dbDialect,J),H=$.dbDialect==="mysql"?`ALTER TABLE ${G} ALGORITHM=INSTANT, LOCK=NONE, ${Y.join(", ")}`:`ALTER TABLE ${G} ${Y.join(", ")}`;if($.dbDialect==="mysql")await a1($.db,H);else await $.db.unsafe(H)}}if(X.defaultClauses.length>0)if($.dbDialect==="sqlite")P.warn(`SQLite \u4E0D\u652F\u6301\u4FEE\u6539\u9ED8\u8BA4\u503C\uFF0C\u8868 ${J} \u7684\u9ED8\u8BA4\u503C\u53D8\u66F4\u5DF2\u8DF3\u8FC7`);else{let Y=Y0($.dbDialect,J),G=$.dbDialect==="mysql"?`ALTER TABLE ${Y} ALGORITHM=INSTANT, LOCK=NONE, ${X.defaultClauses.join(", ")}`:`ALTER TABLE ${Y} ${X.defaultClauses.join(", ")}`;if($.dbDialect==="mysql")await a1($.db,G);else await $.db.unsafe(G)}for(let Y of X.indexActions){let G=CJ($.dbDialect,J,Y.indexName,Y.fieldName,Y.action);try{if(await $.db.unsafe(G),Y.action==="create")P.debug(`[\u7D22\u5F15\u53D8\u5316] \u65B0\u5EFA\u7D22\u5F15 ${J}.${Y.indexName} (${Y.fieldName})`);else P.debug(`[\u7D22\u5F15\u53D8\u5316] \u5220\u9664\u7D22\u5F15 ${J}.${Y.indexName} (${Y.fieldName})`)}catch(H){throw P.error({err:H,table:J,index:Y.indexName,field:Y.fieldName,msg:`${Y.action==="create"?"\u521B\u5EFA":"\u5220\u9664"}\u7D22\u5F15\u5931\u8D25`}),H}}if($.dbDialect==="postgresql"&&X.commentActions&&X.commentActions.length>0)for(let Y of X.commentActions)await $.db.unsafe(Y)}async function VY($,J,Z,X=pZ){let G=[...GY($.dbDialect),...WY($.dbDialect,Z)].join(`,
|
|
5
|
+
`}function U1($){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 V1($){let{fileSink:J,consoleSink:Z}=$,X=(Y,G)=>{if(Y==="debug"&&d0.debug!==1)return;let H=TZ(G,DZ),z=OH(Y,H);if(J.enqueue(z),Z)Z.enqueue(z)};return{info(Y){X("info",Y)},warn(Y){X("warn",Y)},error(Y){X("error",Y)},debug(Y){X("debug",Y)}}}function _H(){let $=Q1();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 AH($,J){let Z={};for(let[Y,G]of Object.entries($))Z[Y]=G;let X=["requestId","method","route","ip","now","durationSinceNowMs","userId","roleCode","nickname","roleType"];for(let Y of X)if(Z[Y]===void 0)Z[Y]=J[Y];return Z}function FJ($){if(o($))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=_H();if(!J)return $;return AH($,J)}class K1{maybeSanitizeForMock($){if(!B$)return $;return TZ($,DZ)}info($){let J=MJ(FJ($)),Z=this.maybeSanitizeForMock(J);return t$("app").info(Z)}warn($){let J=MJ(FJ($)),Z=this.maybeSanitizeForMock(J);return t$("app").warn(Z)}error($){let J=MJ(FJ($)),Z=this.maybeSanitizeForMock(J),X=t$("app").error(Z);if(B$)return X;return t$("error").error(Z),X}debug($){if(d0.debug!==1)return;let J=MJ(FJ($)),Z=this.maybeSanitizeForMock(J);return t$("app").debug(Z)}async flush(){await QH()}configure($){UH($)}setMock($){VH($)}async shutdown(){await _1()}}var YH,O1,DZ,GH,M$=null,R$=null,B$=null,X$=null,Y$=null,G$=null,d0,P;var a=_$(()=>{W1();m0();KJ();YH=process.cwd(),O1=["*password*","pass","pwd","*token*","access_token","refresh_token","accessToken","refreshToken","authorization","cookie","set-cookie","*secret*","apiKey","api_key","privateKey","private_key"],DZ={maxStringLen:100,maxArrayItems:100,sanitizeDepth:3,sanitizeNodes:500,sanitizeObjectKeys:100,sensitiveKeyMatcher:EZ({builtinPatterns:O1,userPatterns:[]})},GH=(()=>{try{return $H()}catch{return"unknown"}})(),d0={debug:0,dir:"./logs",console:1,maxSize:20};P=new K1});function e$($=""){if(!$)return $;return $.replace(/\\/g,"/").replace(KH,(J)=>J.toUpperCase())}function qH(){if(typeof process<"u"&&typeof process.cwd==="function")return process.cwd().replace(/\\/g,"/");return"/"}function yZ($,J){let Z="",X=0,Y=-1,G=0,H=null;for(let z=0;z<=$.length;++z){if(z<$.length)H=$[z];else if(H==="/")break;else H="/";if(H==="/"){if(Y===z-1||G===1);else if(G===2){if(Z.length<2||X!==2||Z[Z.length-1]!=="."||Z[Z.length-2]!=="."){if(Z.length>2){let V=Z.lastIndexOf("/");if(V===-1)Z="",X=0;else Z=Z.slice(0,V),X=Z.length-1-Z.lastIndexOf("/");Y=z,G=0;continue}else if(Z.length>0){Z="",X=0,Y=z,G=0;continue}}if(J)Z+=Z.length>0?"/..":"..",X=2}else{if(Z.length>0)Z+=`/${$.slice(Y+1,z)}`;else Z=$.slice(Y+1,z);X=z-Y-1}Y=z,G=0}else if(H==="."&&G!==-1)++G;else G=-1}return Z}var KH,FH,MH,q1,I1,RH,IH,L$=function($){if($.length===0)return".";$=e$($);let J=$.match(FH),Z=k$($),X=$[$.length-1]==="/";if($=yZ($,!Z),$.length===0){if(Z)return"/";return X?"./":"."}if(X)$+="/";if(q1.test($))$+="/";if(J){if(!Z)return`//./${$}`;return`//${$}`}return Z&&!k$($)?`/${$}`:$},n=function(...$){let J="";for(let Z of $){if(!Z)continue;if(J.length>0){let X=J[J.length-1]==="/",Y=Z[0]==="/";if(X&&Y)J+=Z.slice(1);else J+=X||Y?Z:`/${Z}`}else J+=Z}return L$(J)},a$=function(...$){$=$.map((X)=>e$(X));let J="",Z=!1;for(let X=$.length-1;X>=-1&&!Z;X--){let Y=X>=0?$[X]:qH();if(!Y||Y.length===0)continue;J=`${Y}/${J}`,Z=k$(Y)}if(J=yZ(J,!Z),Z&&!k$(J))return`/${J}`;return J.length>0?J:"."},k$=function($){return MH.test($)},P1=function($){if($==="..")return"";let J=RH.exec(e$($));return J&&J[1]||""},xZ=function($,J){let Z=a$($).replace(I1,"$1").split("/"),X=a$(J).replace(I1,"$1").split("/");if(X[0][1]===":"&&Z[0][1]===":"&&Z[0]!==X[0])return X.join("/");let Y=[...Z];for(let G of Y){if(X[0]!==G)break;Z.shift(),X.shift()}return[...Z.map(()=>".."),...X].join("/")},IJ=function($){let J=e$($).replace(/\/$/,"").split("/").slice(0,-1);if(J.length===1&&q1.test(J[0]))J[0]+="/";return J.join("/")||(k$($)?"/":".")},j1=function($,J){let Z=e$($).split("/"),X="";for(let Y=Z.length-1;Y>=0;Y--){let G=Z[Y];if(G){X=G;break}}return J&&X.endsWith(J)?X.slice(0,-J.length):X},$J=function($){let J=IH.exec($)?.[0]?.replace(/\\/g,"/")||"",Z=j1($),X=P1(Z);return{root:J,dir:IJ($),base:Z,ext:X,name:Z.slice(0,Z.length-X.length)}};var B1=_$(()=>{KH=/^[A-Za-z]:\//;FH=/^[/\\]{2}/,MH=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,q1=/^[A-Za-z]:$/,I1=/^\/([A-Za-z]:)?$/,RH=/.(\.[^./]+|\.)$/,IH=/^[/\\]|^[a-zA-Z]:[/\\]/});var I$=_$(()=>{B1()});import{statSync as PH}from"fs";var qJ=($,J)=>{if(J.isDirectory())return!0;if(!J.isSymbolicLink())return!1;try{return PH(n($,J.name)).isDirectory()}catch{return!1}};var fZ=_$(()=>{I$()});import{existsSync as JJ}from"fs";import{readdir as jH,readFile as L1}from"fs/promises";function BH($){return String($).replace(/_\d+$/,"")}function LH($){let J=/<script\b[^>]*\bsetup\b[^>]*>/i.exec($);if(!J)return null;let Z=J.index+J[0].length,X=$.indexOf("</script>",Z);if(X<0)return null;return $.slice(Z,X)}function SH($){let J=$.match(/definePage\s*\([\s\S]*?meta\s*:\s*\{[\s\S]*?title\s*:\s*(["'`])([^"'`]+)\1/);if(!J)return null;let Z=$.match(/definePage\s*\([\s\S]*?meta\s*:\s*\{[\s\S]*?order\s*:\s*(\d+)/);return{title:J[2],order:Z?Number(Z[1]):void 0}}async function S1($,J,Z=""){if(!JJ($))return[];let X=[],Y=await jH($,{withFileTypes:!0});for(let G of Y){if(!qJ($,G)||G.name==="components")continue;let H=n($,G.name),z=n(H,"index.vue");if(!JJ(z))continue;let V=null;try{let C=await L1(z,"utf-8"),w=LH(C);if(!w){P.warn({path:z,msg:"index.vue \u7F3A\u5C11 <script setup>\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}if(V=SH(w),!V?.title){P.warn({path:z,msg:"index.vue \u672A\u58F0\u660E definePage({ meta: { title, order? } })\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}}catch(C){P.warn({err:C,path:z,msg:"\u8BFB\u53D6 index.vue \u5931\u8D25"});continue}if(!V?.title)continue;let O=BH(G.name),F;if(O==="index")F=Z;else F=Z?`${Z}/${O}`:`/${O}`;let I=J?F?`${J}${F}`:J:F||"/",B={name:V.title,path:I,sort:V.order??999999},L=await S1(H,J,F);if(L.length>0)B.children=L;X.push(B)}return X.sort((G,H)=>(G.sort??999999)-(H.sort??999999)),X}function C1($){let J=$.split("/").filter((Z)=>!!Z);if(J.length<=1)return"";return`/${J.slice(0,-1).join("/")}`}async function E1($){let J=[];for(let X of $){let Y=n(X.fullPath,"adminViews"),G=n(X.fullPath,"views","admin"),H=JJ(Y)?Y:JJ(G)?G:null;if(!H)continue;try{let z=`/${X.source}/${X.name}`,V=await S1(H,z);if(V.length>0)for(let O of V)J.push(O)}catch(z){P.warn({err:z,addon:X.name,addonSource:X.source,dir:H,msg:"\u626B\u63CF addon views \u76EE\u5F55\u5931\u8D25"})}}let Z=n(process.cwd(),"menus.json");if(JJ(Z))try{let X=await L1(Z,"utf-8"),Y=JSON.parse(X);if(Array.isArray(Y)&&Y.length>0)for(let G of Y)J.push(G)}catch(X){P.warn({err:X,msg:"\u8BFB\u53D6\u9879\u76EE menus.json \u5931\u8D25"})}return J}var gZ=_$(()=>{I$();a();fZ()});var c$=s((XU,xY)=>{var yY={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 b$ 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]}}b$.codes=yY;b$.wrap=function($,J,Z){if($ instanceof b$)return $;return new b$(J,Z,{originalError:$})};xY.exports={TokenError:b$,TOKEN_ERROR_CODES:yY}});var $X=s((YU,fY)=>{var{TokenError:W$}=c$();function yQ({complete:$,checkTyp:J},Z){if(Z instanceof Buffer)Z=Z.toString("utf-8");else if(typeof Z!=="string")throw new W$(W$.codes.invalidType,"The token must be a string or a buffer.");let X=Z.indexOf("."),Y=Z.lastIndexOf(".");if(X===-1||X>=Y)throw new W$(W$.codes.malformed,"The token is malformed.");let G=!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});G=!0;let z=Buffer.from(Z.slice(X+1,Y),"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(Y+1),input:Z.slice(0,Y)}:z}catch(H){throw W$.wrap(H,W$.codes.malformed,`The token ${G?"payload":"header"} is not a valid base64url serialized JSON.`)}}fY.exports=function(J={}){let Z=J.complete||!1,X=J.checkTyp;return yQ.bind(null,{complete:Z,checkTyp:X})}});var hY=s((GU,gY)=>{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"};gY.exports=H$});var bY=s((xQ)=>{xQ.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<"u";xQ.SYMBOL_SUPPORT=typeof Symbol<"u"});var JX=s((HU,pY)=>{var cY=bY(),hQ=cY.ARRAY_BUFFER_SUPPORT,bQ=cY.SYMBOL_SUPPORT;pY.exports=function(J,Z){var X,Y,G,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)||hQ&&ArrayBuffer.isView(J)||typeof J==="string"||J.toString()==="[object Arguments]"){for(G=0,H=J.length;G<H;G++)Z(J[G],G);return}if(typeof J.forEach==="function"){J.forEach(Z);return}if(bQ&&Symbol.iterator in J&&typeof J.next!=="function")J=J[Symbol.iterator]();if(typeof J.next==="function"){X=J,G=0;while(z=X.next(),z.done!==!0)Z(z.value,G),G++;return}for(Y in J)if(J.hasOwnProperty(Y))Z(J[Y],Y);return}});var ZX=s((oQ)=>{var cQ=Math.pow(2,8)-1,pQ=Math.pow(2,16)-1,uQ=Math.pow(2,32)-1,mQ=Math.pow(2,7)-1,dQ=Math.pow(2,15)-1,nQ=Math.pow(2,31)-1;oQ.getPointerArray=function($){var J=$-1;if(J<=cQ)return Uint8Array;if(J<=pQ)return Uint16Array;if(J<=uQ)return Uint32Array;throw Error("mnemonist: Pointer Array of size > 4294967295 is not supported.")};oQ.getSignedPointerArray=function($){var J=$-1;if(J<=mQ)return Int8Array;if(J<=dQ)return Int16Array;if(J<=nQ)return Int32Array;return Float64Array};oQ.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 sQ={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};oQ.getMinimalRepresentation=function($,J){var Z=null,X=0,Y,G,H,z,V;for(z=0,V=$.length;z<V;z++)if(H=J?J($[z]):$[z],G=oQ.getNumberType(H),Y=sQ[G.name],Y>X)X=Y,Z=G;return Z};oQ.isTypedArray=function($){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView($)};oQ.concat=function(){var $=0,J,Z,X;for(J=0,X=arguments.length;J<X;J++)$+=arguments[J].length;var Y=new arguments[0].constructor($);for(J=0,Z=0;J<X;J++)Y.set(arguments[J],Z),Z+=arguments[J].length;return Y};oQ.indices=function($){var J=oQ.getPointerArray($),Z=new J($);for(var X=0;X<$;X++)Z[X]=X;return Z}});var sY=s((Zz)=>{var dY=JX(),nY=ZX();function eQ($){return Array.isArray($)||nY.isTypedArray($)}function XX($){if(typeof $.length==="number")return $.length;if(typeof $.size==="number")return $.size;return}function $z($){var J=XX($),Z=typeof J==="number"?Array(J):[],X=0;return dY($,function(Y){Z[X++]=Y}),Z}function Jz($){var J=XX($),Z=typeof J==="number"?nY.getPointerArray(J):Array,X=typeof J==="number"?Array(J):[],Y=typeof J==="number"?new Z(J):[],G=0;return dY($,function(H){X[G]=H,Y[G]=G++}),[X,Y]}Zz.isArrayLike=eQ;Zz.guessLength=XX;Zz.toArray=$z;Zz.toArrayWithIndices=Jz});var GX=s((UU,oY)=>{var YX=hY(),Hz=JX(),Qz=ZX(),zz=sY();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=Qz.getPointerArray(Z);this.forward=new X(Z),this.backward=new X(Z),this.K=typeof $==="function"?new $(Z):Array(Z),this.V=typeof J==="function"?new J(Z):Array(Z),this.size=0,this.head=0,this.tail=0,this.items={}}p0.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}};p0.prototype.splayOnTop=function($){var J=this.head;if(this.head===$)return this;var Z=this.backward[$],X=this.forward[$];if(this.tail===$)this.tail=Z;else this.backward[X]=Z;return this.forward[Z]=X,this.backward[J]=$,this.head=$,this.forward[$]=J,this};p0.prototype.set=function($,J){var Z=this.items[$];if(typeof Z<"u"){this.splayOnTop(Z),this.V[Z]=J;return}if(this.size<this.capacity)Z=this.size++;else Z=this.tail,this.tail=this.backward[Z],delete this.items[this.K[Z]];this.items[$]=Z,this.K[Z]=$,this.V[Z]=J,this.forward[Z]=this.head,this.backward[this.head]=Z,this.head=Z};p0.prototype.setpop=function($,J){var Z=null,X=null,Y=this.items[$];if(typeof Y<"u")return this.splayOnTop(Y),Z=this.V[Y],this.V[Y]=J,{evicted:!1,key:$,value:Z};if(this.size<this.capacity)Y=this.size++;else Y=this.tail,this.tail=this.backward[Y],Z=this.V[Y],X=this.K[Y],delete this.items[X];if(this.items[$]=Y,this.K[Y]=$,this.V[Y]=J,this.forward[Y]=this.head,this.backward[this.head]=Y,this.head=Y,X)return{evicted:!0,key:X,value:Z};else return null};p0.prototype.has=function($){return $ in this.items};p0.prototype.get=function($){var J=this.items[$];if(typeof J>"u")return;return this.splayOnTop(J),this.V[J]};p0.prototype.peek=function($){var J=this.items[$];if(typeof J>"u")return;return this.V[J]};p0.prototype.forEach=function($,J){J=arguments.length>1?J:this;var Z=0,X=this.size,Y=this.head,G=this.K,H=this.V,z=this.forward;while(Z<X)$.call(J,H[Y],G[Y],this),Y=z[Y],Z++};p0.prototype.keys=function(){var $=0,J=this.size,Z=this.head,X=this.K,Y=this.forward;return new YX(function(){if($>=J)return{done:!0};var G=X[Z];if($++,$<J)Z=Y[Z];return{done:!1,value:G}})};p0.prototype.values=function(){var $=0,J=this.size,Z=this.head,X=this.V,Y=this.forward;return new YX(function(){if($>=J)return{done:!0};var G=X[Z];if($++,$<J)Z=Y[Z];return{done:!1,value:G}})};p0.prototype.entries=function(){var $=0,J=this.size,Z=this.head,X=this.K,Y=this.V,G=this.forward;return new YX(function(){if($>=J)return{done:!0};var H=X[Z],z=Y[Z];if($++,$<J)Z=G[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=zz.guessLength($),typeof X!=="number")throw Error("mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.")}else if(arguments.length===2)X=J,J=null,Z=null;var Y=new p0(J,Z,X);return Hz($,function(G,H){Y.set(H,G)}),Y};oY.exports=p0});var HX=s((lY,WX)=>{(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 Y(q,W,U){if(Y.isBN(q))return q;if(this.negative=0,this.words=null,this.length=0,this.red=null,q!==null){if(W==="le"||W==="be")U=W,W=10;this._init(q||0,W||10,U||"be")}}if(typeof $==="object")$.exports=Y;else J.BN=Y;Y.BN=Y,Y.wordSize=26;var G;try{if(typeof window<"u"&&typeof window.Buffer<"u")G=window.Buffer;else G=A$("buffer").Buffer}catch(q){}Y.isBN=function(W){if(W instanceof Y)return!0;return W!==null&&typeof W==="object"&&W.constructor.wordSize===Y.wordSize&&Array.isArray(W.words)},Y.max=function(W,U){if(W.cmp(U)>0)return W;return U},Y.min=function(W,U){if(W.cmp(U)<0)return W;return U},Y.prototype._init=function(W,U,_){if(typeof W==="number")return this._initNumber(W,U,_);if(typeof W==="object")return this._initArray(W,U,_);if(U==="hex")U=16;Z(U===(U|0)&&U>=2&&U<=36),W=W.toString().replace(/\s+/g,"");var A=0;if(W[0]==="-")A++,this.negative=1;if(A<W.length){if(U===16)this._parseHex(W,A,_);else if(this._parseBase(W,U,A),_==="le")this._initArray(this.toArray(),U,_)}},Y.prototype._initNumber=function(W,U,_){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(_!=="le")return;this._initArray(this.toArray(),U,_)},Y.prototype._initArray=function(W,U,_){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 A=0;A<this.length;A++)this.words[A]=0;var R,j,S=0;if(_==="be"){for(A=W.length-1,R=0;A>=0;A-=3)if(j=W[A]|W[A-1]<<8|W[A-2]<<16,this.words[R]|=j<<S&67108863,this.words[R+1]=j>>>26-S&67108863,S+=24,S>=26)S-=26,R++}else if(_==="le"){for(A=0,R=0;A<W.length;A+=3)if(j=W[A]|W[A+1]<<8|W[A+2]<<16,this.words[R]|=j<<S&67108863,this.words[R+1]=j>>>26-S&67108863,S+=24,S>=26)S-=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 _=H(q,U);if(U-1>=W)_|=H(q,U-1)<<4;return _}Y.prototype._parseHex=function(W,U,_){this.length=Math.ceil((W.length-U)/6),this.words=Array(this.length);for(var A=0;A<this.length;A++)this.words[A]=0;var R=0,j=0,S;if(_==="be")for(A=W.length-1;A>=U;A-=2)if(S=z(W,U,A)<<R,this.words[j]|=S&67108863,R>=18)R-=18,j+=1,this.words[j]|=S>>>26;else R+=8;else{var K=W.length-U;for(A=K%2===0?U+1:U;A<W.length;A+=2)if(S=z(W,U,A)<<R,this.words[j]|=S&67108863,R>=18)R-=18,j+=1,this.words[j]|=S>>>26;else R+=8}this.strip()};function V(q,W,U,_){var A=0,R=Math.min(q.length,U);for(var j=W;j<R;j++){var S=q.charCodeAt(j)-48;if(A*=_,S>=49)A+=S-49+10;else if(S>=17)A+=S-17+10;else A+=S}return A}Y.prototype._parseBase=function(W,U,_){this.words=[0],this.length=1;for(var A=0,R=1;R<=67108863;R*=U)A++;A--,R=R/U|0;var j=W.length-_,S=j%A,K=Math.min(j,j-S)+_,Q=0;for(var M=_;M<K;M+=A)if(Q=V(W,M,M+A,U),this.imuln(R),this.words[0]+Q<67108864)this.words[0]+=Q;else this._iaddn(Q);if(S!==0){var k=1;Q=V(W,M,W.length,U);for(M=0;M<S;M++)k*=U;if(this.imuln(k),this.words[0]+Q<67108864)this.words[0]+=Q;else this._iaddn(Q)}this.strip()},Y.prototype.copy=function(W){W.words=Array(this.length);for(var U=0;U<this.length;U++)W.words[U]=this.words[U];W.length=this.length,W.negative=this.negative,W.red=this.red},Y.prototype.clone=function(){var W=new Y(null);return this.copy(W),W},Y.prototype._expand=function(W){while(this.length<W)this.words[this.length++]=0;return this},Y.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},Y.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},Y.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var 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"],F=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],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(Y.prototype.toString=function(W,U){W=W||10,U=U|0||1;var _;if(W===16||W==="hex"){_="";var A=0,R=0;for(var j=0;j<this.length;j++){var S=this.words[j],K=((S<<A|R)&16777215).toString(16);if(R=S>>>24-A&16777215,A+=2,A>=26)A-=26,j--;if(R!==0||j!==this.length-1)_=O[6-K.length]+K+_;else _=K+_}if(R!==0)_=R.toString(16)+_;while(_.length%U!==0)_="0"+_;if(this.negative!==0)_="-"+_;return _}if(W===(W|0)&&W>=2&&W<=36){var Q=F[W],M=I[W];_="";var k=this.clone();k.negative=0;while(!k.isZero()){var y=k.modn(M).toString(W);if(k=k.idivn(M),!k.isZero())_=O[Q-y.length]+y+_;else _=y+_}if(this.isZero())_="0"+_;while(_.length%U!==0)_="0"+_;if(this.negative!==0)_="-"+_;return _}Z(!1,"Base should be between 2 and 36")},Y.prototype.toNumber=function(){var W=this.words[0];if(this.length===2)W+=this.words[1]*67108864;else if(this.length===3&&this.words[2]===1)W+=4503599627370496+this.words[1]*67108864;else if(this.length>2)Z(!1,"Number can only safely store up to 53 bits");return this.negative!==0?-W:W},Y.prototype.toJSON=function(){return this.toString(16)},Y.prototype.toBuffer=function(W,U){return Z(typeof G<"u"),this.toArrayLike(G,W,U)},Y.prototype.toArray=function(W,U){return this.toArrayLike(Array,W,U)},Y.prototype.toArrayLike=function(W,U,_){var A=this.byteLength(),R=_||Math.max(1,A);Z(A<=R,"byte array longer than desired length"),Z(R>0,"Requested array length <= 0"),this.strip();var j=U==="le",S=new W(R),K,Q,M=this.clone();if(!j){for(Q=0;Q<R-A;Q++)S[Q]=0;for(Q=0;!M.isZero();Q++)K=M.andln(255),M.iushrn(8),S[R-Q-1]=K}else{for(Q=0;!M.isZero();Q++)K=M.andln(255),M.iushrn(8),S[Q]=K;for(;Q<R;Q++)S[Q]=0}return S},Math.clz32)Y.prototype._countBits=function(W){return 32-Math.clz32(W)};else Y.prototype._countBits=function(W){var U=W,_=0;if(U>=4096)_+=13,U>>>=13;if(U>=64)_+=7,U>>>=7;if(U>=8)_+=4,U>>>=4;if(U>=2)_+=2,U>>>=2;return _+U};Y.prototype._zeroBits=function(W){if(W===0)return 26;var U=W,_=0;if((U&8191)===0)_+=13,U>>>=13;if((U&127)===0)_+=7,U>>>=7;if((U&15)===0)_+=4,U>>>=4;if((U&3)===0)_+=2,U>>>=2;if((U&1)===0)_++;return _},Y.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 _=U/26|0,A=U%26;W[U]=(q.words[_]&1<<A)>>>A}return W}Y.prototype.zeroBits=function(){if(this.isZero())return 0;var W=0;for(var U=0;U<this.length;U++){var _=this._zeroBits(this.words[U]);if(W+=_,_!==26)break}return W},Y.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},Y.prototype.toTwos=function(W){if(this.negative!==0)return this.abs().inotn(W).iaddn(1);return this.clone()},Y.prototype.fromTwos=function(W){if(this.testn(W-1))return this.notn(W).iaddn(1).ineg();return this.clone()},Y.prototype.isNeg=function(){return this.negative!==0},Y.prototype.neg=function(){return this.clone().ineg()},Y.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},Y.prototype.iuor=function(W){while(this.length<W.length)this.words[this.length++]=0;for(var U=0;U<W.length;U++)this.words[U]=this.words[U]|W.words[U];return this.strip()},Y.prototype.ior=function(W){return Z((this.negative|W.negative)===0),this.iuor(W)},Y.prototype.or=function(W){if(this.length>W.length)return this.clone().ior(W);return W.clone().ior(this)},Y.prototype.uor=function(W){if(this.length>W.length)return this.clone().iuor(W);return W.clone().iuor(this)},Y.prototype.iuand=function(W){var U;if(this.length>W.length)U=W;else U=this;for(var _=0;_<U.length;_++)this.words[_]=this.words[_]&W.words[_];return this.length=U.length,this.strip()},Y.prototype.iand=function(W){return Z((this.negative|W.negative)===0),this.iuand(W)},Y.prototype.and=function(W){if(this.length>W.length)return this.clone().iand(W);return W.clone().iand(this)},Y.prototype.uand=function(W){if(this.length>W.length)return this.clone().iuand(W);return W.clone().iuand(this)},Y.prototype.iuxor=function(W){var U,_;if(this.length>W.length)U=this,_=W;else U=W,_=this;for(var A=0;A<_.length;A++)this.words[A]=U.words[A]^_.words[A];if(this!==U)for(;A<U.length;A++)this.words[A]=U.words[A];return this.length=U.length,this.strip()},Y.prototype.ixor=function(W){return Z((this.negative|W.negative)===0),this.iuxor(W)},Y.prototype.xor=function(W){if(this.length>W.length)return this.clone().ixor(W);return W.clone().ixor(this)},Y.prototype.uxor=function(W){if(this.length>W.length)return this.clone().iuxor(W);return W.clone().iuxor(this)},Y.prototype.inotn=function(W){Z(typeof W==="number"&&W>=0);var U=Math.ceil(W/26)|0,_=W%26;if(this._expand(U),_>0)U--;for(var A=0;A<U;A++)this.words[A]=~this.words[A]&67108863;if(_>0)this.words[A]=~this.words[A]&67108863>>26-_;return this.strip()},Y.prototype.notn=function(W){return this.clone().inotn(W)},Y.prototype.setn=function(W,U){Z(typeof W==="number"&&W>=0);var _=W/26|0,A=W%26;if(this._expand(_+1),U)this.words[_]=this.words[_]|1<<A;else this.words[_]=this.words[_]&~(1<<A);return this.strip()},Y.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 _,A;if(this.length>W.length)_=this,A=W;else _=W,A=this;var R=0;for(var j=0;j<A.length;j++)U=(_.words[j]|0)+(A.words[j]|0)+R,this.words[j]=U&67108863,R=U>>>26;for(;R!==0&&j<_.length;j++)U=(_.words[j]|0)+R,this.words[j]=U&67108863,R=U>>>26;if(this.length=_.length,R!==0)this.words[this.length]=R,this.length++;else if(_!==this)for(;j<_.length;j++)this.words[j]=_.words[j];return this},Y.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)},Y.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 _=this.cmp(W);if(_===0)return this.negative=0,this.length=1,this.words[0]=0,this;var A,R;if(_>0)A=this,R=W;else A=W,R=this;var j=0;for(var S=0;S<R.length;S++)U=(A.words[S]|0)-(R.words[S]|0)+j,j=U>>26,this.words[S]=U&67108863;for(;j!==0&&S<A.length;S++)U=(A.words[S]|0)+j,j=U>>26,this.words[S]=U&67108863;if(j===0&&S<A.length&&A!==this)for(;S<A.length;S++)this.words[S]=A.words[S];if(this.length=Math.max(this.length,S),A!==this)this.negative=1;return this.strip()},Y.prototype.sub=function(W){return this.clone().isub(W)};function L(q,W,U){U.negative=W.negative^q.negative;var _=q.length+W.length|0;U.length=_,_=_-1|0;var A=q.words[0]|0,R=W.words[0]|0,j=A*R,S=j&67108863,K=j/67108864|0;U.words[0]=S;for(var Q=1;Q<_;Q++){var M=K>>>26,k=K&67108863,y=Math.min(Q,W.length-1);for(var x=Math.max(0,Q-q.length+1);x<=y;x++){var p=Q-x|0;A=q.words[p]|0,R=W.words[x]|0,j=A*R+k,M+=j/67108864|0,k=j&67108863}U.words[Q]=k|0,K=M|0}if(K!==0)U.words[Q]=K|0;else U.length--;return U.strip()}var C=function(W,U,_){var A=W.words,R=U.words,j=_.words,S=0,K,Q,M,k=A[0]|0,y=k&8191,x=k>>>13,p=A[1]|0,i=p&8191,e=p>>>13,O$=A[2]|0,$0=O$&8191,Z0=O$>>>13,DX=A[3]|0,W0=DX&8191,H0=DX>>>13,kX=A[4]|0,Q0=kX&8191,z0=kX>>>13,yX=A[5]|0,U0=yX&8191,V0=yX>>>13,xX=A[6]|0,O0=xX&8191,_0=xX>>>13,fX=A[7]|0,A0=fX&8191,K0=fX>>>13,gX=A[8]|0,F0=gX&8191,M0=gX>>>13,hX=A[9]|0,R0=hX&8191,I0=hX>>>13,bX=R[0]|0,q0=bX&8191,P0=bX>>>13,cX=R[1]|0,j0=cX&8191,B0=cX>>>13,pX=R[2]|0,L0=pX&8191,S0=pX>>>13,uX=R[3]|0,C0=uX&8191,E0=uX>>>13,mX=R[4]|0,w0=mX&8191,T0=mX>>>13,dX=R[5]|0,v0=dX&8191,N0=dX>>>13,nX=R[6]|0,D0=nX&8191,k0=nX>>>13,sX=R[7]|0,y0=sX&8191,x0=sX>>>13,oX=R[8]|0,f0=oX&8191,g0=oX>>>13,lX=R[9]|0,h0=lX&8191,b0=lX>>>13;_.negative=W.negative^U.negative,_.length=19,K=Math.imul(y,q0),Q=Math.imul(y,P0),Q=Q+Math.imul(x,q0)|0,M=Math.imul(x,P0);var eJ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(eJ>>>26)|0,eJ&=67108863,K=Math.imul(i,q0),Q=Math.imul(i,P0),Q=Q+Math.imul(e,q0)|0,M=Math.imul(e,P0),K=K+Math.imul(y,j0)|0,Q=Q+Math.imul(y,B0)|0,Q=Q+Math.imul(x,j0)|0,M=M+Math.imul(x,B0)|0;var $Z=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+($Z>>>26)|0,$Z&=67108863,K=Math.imul($0,q0),Q=Math.imul($0,P0),Q=Q+Math.imul(Z0,q0)|0,M=Math.imul(Z0,P0),K=K+Math.imul(i,j0)|0,Q=Q+Math.imul(i,B0)|0,Q=Q+Math.imul(e,j0)|0,M=M+Math.imul(e,B0)|0,K=K+Math.imul(y,L0)|0,Q=Q+Math.imul(y,S0)|0,Q=Q+Math.imul(x,L0)|0,M=M+Math.imul(x,S0)|0;var JZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(JZ>>>26)|0,JZ&=67108863,K=Math.imul(W0,q0),Q=Math.imul(W0,P0),Q=Q+Math.imul(H0,q0)|0,M=Math.imul(H0,P0),K=K+Math.imul($0,j0)|0,Q=Q+Math.imul($0,B0)|0,Q=Q+Math.imul(Z0,j0)|0,M=M+Math.imul(Z0,B0)|0,K=K+Math.imul(i,L0)|0,Q=Q+Math.imul(i,S0)|0,Q=Q+Math.imul(e,L0)|0,M=M+Math.imul(e,S0)|0,K=K+Math.imul(y,C0)|0,Q=Q+Math.imul(y,E0)|0,Q=Q+Math.imul(x,C0)|0,M=M+Math.imul(x,E0)|0;var ZZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(ZZ>>>26)|0,ZZ&=67108863,K=Math.imul(Q0,q0),Q=Math.imul(Q0,P0),Q=Q+Math.imul(z0,q0)|0,M=Math.imul(z0,P0),K=K+Math.imul(W0,j0)|0,Q=Q+Math.imul(W0,B0)|0,Q=Q+Math.imul(H0,j0)|0,M=M+Math.imul(H0,B0)|0,K=K+Math.imul($0,L0)|0,Q=Q+Math.imul($0,S0)|0,Q=Q+Math.imul(Z0,L0)|0,M=M+Math.imul(Z0,S0)|0,K=K+Math.imul(i,C0)|0,Q=Q+Math.imul(i,E0)|0,Q=Q+Math.imul(e,C0)|0,M=M+Math.imul(e,E0)|0,K=K+Math.imul(y,w0)|0,Q=Q+Math.imul(y,T0)|0,Q=Q+Math.imul(x,w0)|0,M=M+Math.imul(x,T0)|0;var XZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(XZ>>>26)|0,XZ&=67108863,K=Math.imul(U0,q0),Q=Math.imul(U0,P0),Q=Q+Math.imul(V0,q0)|0,M=Math.imul(V0,P0),K=K+Math.imul(Q0,j0)|0,Q=Q+Math.imul(Q0,B0)|0,Q=Q+Math.imul(z0,j0)|0,M=M+Math.imul(z0,B0)|0,K=K+Math.imul(W0,L0)|0,Q=Q+Math.imul(W0,S0)|0,Q=Q+Math.imul(H0,L0)|0,M=M+Math.imul(H0,S0)|0,K=K+Math.imul($0,C0)|0,Q=Q+Math.imul($0,E0)|0,Q=Q+Math.imul(Z0,C0)|0,M=M+Math.imul(Z0,E0)|0,K=K+Math.imul(i,w0)|0,Q=Q+Math.imul(i,T0)|0,Q=Q+Math.imul(e,w0)|0,M=M+Math.imul(e,T0)|0,K=K+Math.imul(y,v0)|0,Q=Q+Math.imul(y,N0)|0,Q=Q+Math.imul(x,v0)|0,M=M+Math.imul(x,N0)|0;var YZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(YZ>>>26)|0,YZ&=67108863,K=Math.imul(O0,q0),Q=Math.imul(O0,P0),Q=Q+Math.imul(_0,q0)|0,M=Math.imul(_0,P0),K=K+Math.imul(U0,j0)|0,Q=Q+Math.imul(U0,B0)|0,Q=Q+Math.imul(V0,j0)|0,M=M+Math.imul(V0,B0)|0,K=K+Math.imul(Q0,L0)|0,Q=Q+Math.imul(Q0,S0)|0,Q=Q+Math.imul(z0,L0)|0,M=M+Math.imul(z0,S0)|0,K=K+Math.imul(W0,C0)|0,Q=Q+Math.imul(W0,E0)|0,Q=Q+Math.imul(H0,C0)|0,M=M+Math.imul(H0,E0)|0,K=K+Math.imul($0,w0)|0,Q=Q+Math.imul($0,T0)|0,Q=Q+Math.imul(Z0,w0)|0,M=M+Math.imul(Z0,T0)|0,K=K+Math.imul(i,v0)|0,Q=Q+Math.imul(i,N0)|0,Q=Q+Math.imul(e,v0)|0,M=M+Math.imul(e,N0)|0,K=K+Math.imul(y,D0)|0,Q=Q+Math.imul(y,k0)|0,Q=Q+Math.imul(x,D0)|0,M=M+Math.imul(x,k0)|0;var GZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(GZ>>>26)|0,GZ&=67108863,K=Math.imul(A0,q0),Q=Math.imul(A0,P0),Q=Q+Math.imul(K0,q0)|0,M=Math.imul(K0,P0),K=K+Math.imul(O0,j0)|0,Q=Q+Math.imul(O0,B0)|0,Q=Q+Math.imul(_0,j0)|0,M=M+Math.imul(_0,B0)|0,K=K+Math.imul(U0,L0)|0,Q=Q+Math.imul(U0,S0)|0,Q=Q+Math.imul(V0,L0)|0,M=M+Math.imul(V0,S0)|0,K=K+Math.imul(Q0,C0)|0,Q=Q+Math.imul(Q0,E0)|0,Q=Q+Math.imul(z0,C0)|0,M=M+Math.imul(z0,E0)|0,K=K+Math.imul(W0,w0)|0,Q=Q+Math.imul(W0,T0)|0,Q=Q+Math.imul(H0,w0)|0,M=M+Math.imul(H0,T0)|0,K=K+Math.imul($0,v0)|0,Q=Q+Math.imul($0,N0)|0,Q=Q+Math.imul(Z0,v0)|0,M=M+Math.imul(Z0,N0)|0,K=K+Math.imul(i,D0)|0,Q=Q+Math.imul(i,k0)|0,Q=Q+Math.imul(e,D0)|0,M=M+Math.imul(e,k0)|0,K=K+Math.imul(y,y0)|0,Q=Q+Math.imul(y,x0)|0,Q=Q+Math.imul(x,y0)|0,M=M+Math.imul(x,x0)|0;var WZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(WZ>>>26)|0,WZ&=67108863,K=Math.imul(F0,q0),Q=Math.imul(F0,P0),Q=Q+Math.imul(M0,q0)|0,M=Math.imul(M0,P0),K=K+Math.imul(A0,j0)|0,Q=Q+Math.imul(A0,B0)|0,Q=Q+Math.imul(K0,j0)|0,M=M+Math.imul(K0,B0)|0,K=K+Math.imul(O0,L0)|0,Q=Q+Math.imul(O0,S0)|0,Q=Q+Math.imul(_0,L0)|0,M=M+Math.imul(_0,S0)|0,K=K+Math.imul(U0,C0)|0,Q=Q+Math.imul(U0,E0)|0,Q=Q+Math.imul(V0,C0)|0,M=M+Math.imul(V0,E0)|0,K=K+Math.imul(Q0,w0)|0,Q=Q+Math.imul(Q0,T0)|0,Q=Q+Math.imul(z0,w0)|0,M=M+Math.imul(z0,T0)|0,K=K+Math.imul(W0,v0)|0,Q=Q+Math.imul(W0,N0)|0,Q=Q+Math.imul(H0,v0)|0,M=M+Math.imul(H0,N0)|0,K=K+Math.imul($0,D0)|0,Q=Q+Math.imul($0,k0)|0,Q=Q+Math.imul(Z0,D0)|0,M=M+Math.imul(Z0,k0)|0,K=K+Math.imul(i,y0)|0,Q=Q+Math.imul(i,x0)|0,Q=Q+Math.imul(e,y0)|0,M=M+Math.imul(e,x0)|0,K=K+Math.imul(y,f0)|0,Q=Q+Math.imul(y,g0)|0,Q=Q+Math.imul(x,f0)|0,M=M+Math.imul(x,g0)|0;var HZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(HZ>>>26)|0,HZ&=67108863,K=Math.imul(R0,q0),Q=Math.imul(R0,P0),Q=Q+Math.imul(I0,q0)|0,M=Math.imul(I0,P0),K=K+Math.imul(F0,j0)|0,Q=Q+Math.imul(F0,B0)|0,Q=Q+Math.imul(M0,j0)|0,M=M+Math.imul(M0,B0)|0,K=K+Math.imul(A0,L0)|0,Q=Q+Math.imul(A0,S0)|0,Q=Q+Math.imul(K0,L0)|0,M=M+Math.imul(K0,S0)|0,K=K+Math.imul(O0,C0)|0,Q=Q+Math.imul(O0,E0)|0,Q=Q+Math.imul(_0,C0)|0,M=M+Math.imul(_0,E0)|0,K=K+Math.imul(U0,w0)|0,Q=Q+Math.imul(U0,T0)|0,Q=Q+Math.imul(V0,w0)|0,M=M+Math.imul(V0,T0)|0,K=K+Math.imul(Q0,v0)|0,Q=Q+Math.imul(Q0,N0)|0,Q=Q+Math.imul(z0,v0)|0,M=M+Math.imul(z0,N0)|0,K=K+Math.imul(W0,D0)|0,Q=Q+Math.imul(W0,k0)|0,Q=Q+Math.imul(H0,D0)|0,M=M+Math.imul(H0,k0)|0,K=K+Math.imul($0,y0)|0,Q=Q+Math.imul($0,x0)|0,Q=Q+Math.imul(Z0,y0)|0,M=M+Math.imul(Z0,x0)|0,K=K+Math.imul(i,f0)|0,Q=Q+Math.imul(i,g0)|0,Q=Q+Math.imul(e,f0)|0,M=M+Math.imul(e,g0)|0,K=K+Math.imul(y,h0)|0,Q=Q+Math.imul(y,b0)|0,Q=Q+Math.imul(x,h0)|0,M=M+Math.imul(x,b0)|0;var QZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(QZ>>>26)|0,QZ&=67108863,K=Math.imul(R0,j0),Q=Math.imul(R0,B0),Q=Q+Math.imul(I0,j0)|0,M=Math.imul(I0,B0),K=K+Math.imul(F0,L0)|0,Q=Q+Math.imul(F0,S0)|0,Q=Q+Math.imul(M0,L0)|0,M=M+Math.imul(M0,S0)|0,K=K+Math.imul(A0,C0)|0,Q=Q+Math.imul(A0,E0)|0,Q=Q+Math.imul(K0,C0)|0,M=M+Math.imul(K0,E0)|0,K=K+Math.imul(O0,w0)|0,Q=Q+Math.imul(O0,T0)|0,Q=Q+Math.imul(_0,w0)|0,M=M+Math.imul(_0,T0)|0,K=K+Math.imul(U0,v0)|0,Q=Q+Math.imul(U0,N0)|0,Q=Q+Math.imul(V0,v0)|0,M=M+Math.imul(V0,N0)|0,K=K+Math.imul(Q0,D0)|0,Q=Q+Math.imul(Q0,k0)|0,Q=Q+Math.imul(z0,D0)|0,M=M+Math.imul(z0,k0)|0,K=K+Math.imul(W0,y0)|0,Q=Q+Math.imul(W0,x0)|0,Q=Q+Math.imul(H0,y0)|0,M=M+Math.imul(H0,x0)|0,K=K+Math.imul($0,f0)|0,Q=Q+Math.imul($0,g0)|0,Q=Q+Math.imul(Z0,f0)|0,M=M+Math.imul(Z0,g0)|0,K=K+Math.imul(i,h0)|0,Q=Q+Math.imul(i,b0)|0,Q=Q+Math.imul(e,h0)|0,M=M+Math.imul(e,b0)|0;var zZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,K=Math.imul(R0,L0),Q=Math.imul(R0,S0),Q=Q+Math.imul(I0,L0)|0,M=Math.imul(I0,S0),K=K+Math.imul(F0,C0)|0,Q=Q+Math.imul(F0,E0)|0,Q=Q+Math.imul(M0,C0)|0,M=M+Math.imul(M0,E0)|0,K=K+Math.imul(A0,w0)|0,Q=Q+Math.imul(A0,T0)|0,Q=Q+Math.imul(K0,w0)|0,M=M+Math.imul(K0,T0)|0,K=K+Math.imul(O0,v0)|0,Q=Q+Math.imul(O0,N0)|0,Q=Q+Math.imul(_0,v0)|0,M=M+Math.imul(_0,N0)|0,K=K+Math.imul(U0,D0)|0,Q=Q+Math.imul(U0,k0)|0,Q=Q+Math.imul(V0,D0)|0,M=M+Math.imul(V0,k0)|0,K=K+Math.imul(Q0,y0)|0,Q=Q+Math.imul(Q0,x0)|0,Q=Q+Math.imul(z0,y0)|0,M=M+Math.imul(z0,x0)|0,K=K+Math.imul(W0,f0)|0,Q=Q+Math.imul(W0,g0)|0,Q=Q+Math.imul(H0,f0)|0,M=M+Math.imul(H0,g0)|0,K=K+Math.imul($0,h0)|0,Q=Q+Math.imul($0,b0)|0,Q=Q+Math.imul(Z0,h0)|0,M=M+Math.imul(Z0,b0)|0;var UZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(UZ>>>26)|0,UZ&=67108863,K=Math.imul(R0,C0),Q=Math.imul(R0,E0),Q=Q+Math.imul(I0,C0)|0,M=Math.imul(I0,E0),K=K+Math.imul(F0,w0)|0,Q=Q+Math.imul(F0,T0)|0,Q=Q+Math.imul(M0,w0)|0,M=M+Math.imul(M0,T0)|0,K=K+Math.imul(A0,v0)|0,Q=Q+Math.imul(A0,N0)|0,Q=Q+Math.imul(K0,v0)|0,M=M+Math.imul(K0,N0)|0,K=K+Math.imul(O0,D0)|0,Q=Q+Math.imul(O0,k0)|0,Q=Q+Math.imul(_0,D0)|0,M=M+Math.imul(_0,k0)|0,K=K+Math.imul(U0,y0)|0,Q=Q+Math.imul(U0,x0)|0,Q=Q+Math.imul(V0,y0)|0,M=M+Math.imul(V0,x0)|0,K=K+Math.imul(Q0,f0)|0,Q=Q+Math.imul(Q0,g0)|0,Q=Q+Math.imul(z0,f0)|0,M=M+Math.imul(z0,g0)|0,K=K+Math.imul(W0,h0)|0,Q=Q+Math.imul(W0,b0)|0,Q=Q+Math.imul(H0,h0)|0,M=M+Math.imul(H0,b0)|0;var VZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(VZ>>>26)|0,VZ&=67108863,K=Math.imul(R0,w0),Q=Math.imul(R0,T0),Q=Q+Math.imul(I0,w0)|0,M=Math.imul(I0,T0),K=K+Math.imul(F0,v0)|0,Q=Q+Math.imul(F0,N0)|0,Q=Q+Math.imul(M0,v0)|0,M=M+Math.imul(M0,N0)|0,K=K+Math.imul(A0,D0)|0,Q=Q+Math.imul(A0,k0)|0,Q=Q+Math.imul(K0,D0)|0,M=M+Math.imul(K0,k0)|0,K=K+Math.imul(O0,y0)|0,Q=Q+Math.imul(O0,x0)|0,Q=Q+Math.imul(_0,y0)|0,M=M+Math.imul(_0,x0)|0,K=K+Math.imul(U0,f0)|0,Q=Q+Math.imul(U0,g0)|0,Q=Q+Math.imul(V0,f0)|0,M=M+Math.imul(V0,g0)|0,K=K+Math.imul(Q0,h0)|0,Q=Q+Math.imul(Q0,b0)|0,Q=Q+Math.imul(z0,h0)|0,M=M+Math.imul(z0,b0)|0;var OZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(OZ>>>26)|0,OZ&=67108863,K=Math.imul(R0,v0),Q=Math.imul(R0,N0),Q=Q+Math.imul(I0,v0)|0,M=Math.imul(I0,N0),K=K+Math.imul(F0,D0)|0,Q=Q+Math.imul(F0,k0)|0,Q=Q+Math.imul(M0,D0)|0,M=M+Math.imul(M0,k0)|0,K=K+Math.imul(A0,y0)|0,Q=Q+Math.imul(A0,x0)|0,Q=Q+Math.imul(K0,y0)|0,M=M+Math.imul(K0,x0)|0,K=K+Math.imul(O0,f0)|0,Q=Q+Math.imul(O0,g0)|0,Q=Q+Math.imul(_0,f0)|0,M=M+Math.imul(_0,g0)|0,K=K+Math.imul(U0,h0)|0,Q=Q+Math.imul(U0,b0)|0,Q=Q+Math.imul(V0,h0)|0,M=M+Math.imul(V0,b0)|0;var _Z=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(_Z>>>26)|0,_Z&=67108863,K=Math.imul(R0,D0),Q=Math.imul(R0,k0),Q=Q+Math.imul(I0,D0)|0,M=Math.imul(I0,k0),K=K+Math.imul(F0,y0)|0,Q=Q+Math.imul(F0,x0)|0,Q=Q+Math.imul(M0,y0)|0,M=M+Math.imul(M0,x0)|0,K=K+Math.imul(A0,f0)|0,Q=Q+Math.imul(A0,g0)|0,Q=Q+Math.imul(K0,f0)|0,M=M+Math.imul(K0,g0)|0,K=K+Math.imul(O0,h0)|0,Q=Q+Math.imul(O0,b0)|0,Q=Q+Math.imul(_0,h0)|0,M=M+Math.imul(_0,b0)|0;var AZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(AZ>>>26)|0,AZ&=67108863,K=Math.imul(R0,y0),Q=Math.imul(R0,x0),Q=Q+Math.imul(I0,y0)|0,M=Math.imul(I0,x0),K=K+Math.imul(F0,f0)|0,Q=Q+Math.imul(F0,g0)|0,Q=Q+Math.imul(M0,f0)|0,M=M+Math.imul(M0,g0)|0,K=K+Math.imul(A0,h0)|0,Q=Q+Math.imul(A0,b0)|0,Q=Q+Math.imul(K0,h0)|0,M=M+Math.imul(K0,b0)|0;var KZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(KZ>>>26)|0,KZ&=67108863,K=Math.imul(R0,f0),Q=Math.imul(R0,g0),Q=Q+Math.imul(I0,f0)|0,M=Math.imul(I0,g0),K=K+Math.imul(F0,h0)|0,Q=Q+Math.imul(F0,b0)|0,Q=Q+Math.imul(M0,h0)|0,M=M+Math.imul(M0,b0)|0;var FZ=(S+K|0)+((Q&8191)<<13)|0;S=(M+(Q>>>13)|0)+(FZ>>>26)|0,FZ&=67108863,K=Math.imul(R0,h0),Q=Math.imul(R0,b0),Q=Q+Math.imul(I0,h0)|0,M=Math.imul(I0,b0);var MZ=(S+K|0)+((Q&8191)<<13)|0;if(S=(M+(Q>>>13)|0)+(MZ>>>26)|0,MZ&=67108863,j[0]=eJ,j[1]=$Z,j[2]=JZ,j[3]=ZZ,j[4]=XZ,j[5]=YZ,j[6]=GZ,j[7]=WZ,j[8]=HZ,j[9]=QZ,j[10]=zZ,j[11]=UZ,j[12]=VZ,j[13]=OZ,j[14]=_Z,j[15]=AZ,j[16]=KZ,j[17]=FZ,j[18]=MZ,S!==0)j[19]=S,_.length++;return _};if(!Math.imul)C=L;function w(q,W,U){U.negative=W.negative^q.negative,U.length=q.length+W.length;var _=0,A=0;for(var R=0;R<U.length-1;R++){var j=A;A=0;var S=_&67108863,K=Math.min(R,W.length-1);for(var Q=Math.max(0,R-q.length+1);Q<=K;Q++){var M=R-Q,k=q.words[M]|0,y=W.words[Q]|0,x=k*y,p=x&67108863;j=j+(x/67108864|0)|0,p=p+S|0,S=p&67108863,j=j+(p>>>26)|0,A+=j>>>26,j&=67108863}U.words[R]=S,_=j,j=A}if(_!==0)U.words[R]=_;else U.length--;return U.strip()}function T(q,W,U){var _=new N;return _.mulp(q,W,U)}Y.prototype.mulTo=function(W,U){var _,A=this.length+W.length;if(this.length===10&&W.length===10)_=C(this,W,U);else if(A<63)_=L(this,W,U);else if(A<1024)_=w(this,W,U);else _=T(this,W,U);return _};function N(q,W){this.x=q,this.y=W}N.prototype.makeRBT=function(W){var U=Array(W),_=Y.prototype._countBits(W)-1;for(var A=0;A<W;A++)U[A]=this.revBin(A,_,W);return U},N.prototype.revBin=function(W,U,_){if(W===0||W===_-1)return W;var A=0;for(var R=0;R<U;R++)A|=(W&1)<<U-R-1,W>>=1;return A},N.prototype.permute=function(W,U,_,A,R,j){for(var S=0;S<j;S++)A[S]=U[W[S]],R[S]=_[W[S]]},N.prototype.transform=function(W,U,_,A,R,j){this.permute(j,W,U,_,A,R);for(var S=1;S<R;S<<=1){var K=S<<1,Q=Math.cos(2*Math.PI/K),M=Math.sin(2*Math.PI/K);for(var k=0;k<R;k+=K){var y=Q,x=M;for(var p=0;p<S;p++){var i=_[k+p],e=A[k+p],O$=_[k+p+S],$0=A[k+p+S],Z0=y*O$-x*$0;if($0=y*$0+x*O$,O$=Z0,_[k+p]=i+O$,A[k+p]=e+$0,_[k+p+S]=i-O$,A[k+p+S]=e-$0,p!==K)Z0=Q*y-M*x,x=Q*x+M*y,y=Z0}}}},N.prototype.guessLen13b=function(W,U){var _=Math.max(U,W)|1,A=_&1,R=0;for(_=_/2|0;_;_=_>>>1)R++;return 1<<R+1+A},N.prototype.conjugate=function(W,U,_){if(_<=1)return;for(var A=0;A<_/2;A++){var R=W[A];W[A]=W[_-A-1],W[_-A-1]=R,R=U[A],U[A]=-U[_-A-1],U[_-A-1]=-R}},N.prototype.normalize13b=function(W,U){var _=0;for(var A=0;A<U/2;A++){var R=Math.round(W[2*A+1]/U)*8192+Math.round(W[2*A]/U)+_;if(W[A]=R&67108863,R<67108864)_=0;else _=R/67108864|0}return W},N.prototype.convert13b=function(W,U,_,A){var R=0;for(var j=0;j<U;j++)R=R+(W[j]|0),_[2*j]=R&8191,R=R>>>13,_[2*j+1]=R&8191,R=R>>>13;for(j=2*U;j<A;++j)_[j]=0;Z(R===0),Z((R&-8192)===0)},N.prototype.stub=function(W){var U=Array(W);for(var _=0;_<W;_++)U[_]=0;return U},N.prototype.mulp=function(W,U,_){var A=2*this.guessLen13b(W.length,U.length),R=this.makeRBT(A),j=this.stub(A),S=Array(A),K=Array(A),Q=Array(A),M=Array(A),k=Array(A),y=Array(A),x=_.words;x.length=A,this.convert13b(W.words,W.length,S,A),this.convert13b(U.words,U.length,M,A),this.transform(S,j,K,Q,A,R),this.transform(M,j,k,y,A,R);for(var p=0;p<A;p++){var i=K[p]*k[p]-Q[p]*y[p];Q[p]=K[p]*y[p]+Q[p]*k[p],K[p]=i}return this.conjugate(K,Q,A),this.transform(K,Q,x,j,A,R),this.conjugate(x,j,A),this.normalize13b(x,A),_.negative=W.negative^U.negative,_.length=W.length+U.length,_.strip()},Y.prototype.mul=function(W){var U=new Y(null);return U.words=Array(this.length+W.length),this.mulTo(W,U)},Y.prototype.mulf=function(W){var U=new Y(null);return U.words=Array(this.length+W.length),T(this,W,U)},Y.prototype.imul=function(W){return this.clone().mulTo(W,this)},Y.prototype.imuln=function(W){Z(typeof W==="number"),Z(W<67108864);var U=0;for(var _=0;_<this.length;_++){var A=(this.words[_]|0)*W,R=(A&67108863)+(U&67108863);U>>=26,U+=A/67108864|0,U+=R>>>26,this.words[_]=R&67108863}if(U!==0)this.words[_]=U,this.length++;return this.length=W===0?1:this.length,this},Y.prototype.muln=function(W){return this.clone().imuln(W)},Y.prototype.sqr=function(){return this.mul(this)},Y.prototype.isqr=function(){return this.imul(this.clone())},Y.prototype.pow=function(W){var U=B(W);if(U.length===0)return new Y(1);var _=this;for(var A=0;A<U.length;A++,_=_.sqr())if(U[A]!==0)break;if(++A<U.length)for(var R=_.sqr();A<U.length;A++,R=R.sqr()){if(U[A]===0)continue;_=_.mul(R)}return _},Y.prototype.iushln=function(W){Z(typeof W==="number"&&W>=0);var U=W%26,_=(W-U)/26,A=67108863>>>26-U<<26-U,R;if(U!==0){var j=0;for(R=0;R<this.length;R++){var S=this.words[R]&A,K=(this.words[R]|0)-S<<U;this.words[R]=K|j,j=S>>>26-U}if(j)this.words[R]=j,this.length++}if(_!==0){for(R=this.length-1;R>=0;R--)this.words[R+_]=this.words[R];for(R=0;R<_;R++)this.words[R]=0;this.length+=_}return this.strip()},Y.prototype.ishln=function(W){return Z(this.negative===0),this.iushln(W)},Y.prototype.iushrn=function(W,U,_){Z(typeof W==="number"&&W>=0);var A;if(U)A=(U-U%26)/26;else A=0;var R=W%26,j=Math.min((W-R)/26,this.length),S=67108863^67108863>>>R<<R,K=_;if(A-=j,A=Math.max(0,A),K){for(var Q=0;Q<j;Q++)K.words[Q]=this.words[Q];K.length=j}if(j===0);else if(this.length>j){this.length-=j;for(Q=0;Q<this.length;Q++)this.words[Q]=this.words[Q+j]}else this.words[0]=0,this.length=1;var M=0;for(Q=this.length-1;Q>=0&&(M!==0||Q>=A);Q--){var k=this.words[Q]|0;this.words[Q]=M<<26-R|k>>>R,M=k&S}if(K&&M!==0)K.words[K.length++]=M;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},Y.prototype.ishrn=function(W,U,_){return Z(this.negative===0),this.iushrn(W,U,_)},Y.prototype.shln=function(W){return this.clone().ishln(W)},Y.prototype.ushln=function(W){return this.clone().iushln(W)},Y.prototype.shrn=function(W){return this.clone().ishrn(W)},Y.prototype.ushrn=function(W){return this.clone().iushrn(W)},Y.prototype.testn=function(W){Z(typeof W==="number"&&W>=0);var U=W%26,_=(W-U)/26,A=1<<U;if(this.length<=_)return!1;var R=this.words[_];return!!(R&A)},Y.prototype.imaskn=function(W){Z(typeof W==="number"&&W>=0);var U=W%26,_=(W-U)/26;if(Z(this.negative===0,"imaskn works only with positive numbers"),this.length<=_)return this;if(U!==0)_++;if(this.length=Math.min(_,this.length),U!==0){var A=67108863^67108863>>>U<<U;this.words[this.length-1]&=A}return this.strip()},Y.prototype.maskn=function(W){return this.clone().imaskn(W)},Y.prototype.iaddn=function(W){if(Z(typeof W==="number"),Z(W<67108864),W<0)return this.isubn(-W);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<W)return this.words[0]=W-(this.words[0]|0),this.negative=0,this;return this.negative=0,this.isubn(W),this.negative=1,this}return this._iaddn(W)},Y.prototype._iaddn=function(W){this.words[0]+=W;for(var 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},Y.prototype.isubn=function(W){if(Z(typeof W==="number"),Z(W<67108864),W<0)return this.iaddn(-W);if(this.negative!==0)return this.negative=0,this.iaddn(W),this.negative=1,this;if(this.words[0]-=W,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var U=0;U<this.length&&this.words[U]<0;U++)this.words[U]+=67108864,this.words[U+1]-=1;return this.strip()},Y.prototype.addn=function(W){return this.clone().iaddn(W)},Y.prototype.subn=function(W){return this.clone().isubn(W)},Y.prototype.iabs=function(){return this.negative=0,this},Y.prototype.abs=function(){return this.clone().iabs()},Y.prototype._ishlnsubmul=function(W,U,_){var A=W.length+_,R;this._expand(A);var j,S=0;for(R=0;R<W.length;R++){j=(this.words[R+_]|0)+S;var K=(W.words[R]|0)*U;j-=K&67108863,S=(j>>26)-(K/67108864|0),this.words[R+_]=j&67108863}for(;R<this.length-_;R++)j=(this.words[R+_]|0)+S,S=j>>26,this.words[R+_]=j&67108863;if(S===0)return this.strip();Z(S===-1),S=0;for(R=0;R<this.length;R++)j=-(this.words[R]|0)+S,S=j>>26,this.words[R]=j&67108863;return this.negative=1,this.strip()},Y.prototype._wordDiv=function(W,U){var _=this.length-W.length,A=this.clone(),R=W,j=R.words[R.length-1]|0,S=this._countBits(j);if(_=26-S,_!==0)R=R.ushln(_),A.iushln(_),j=R.words[R.length-1]|0;var K=A.length-R.length,Q;if(U!=="mod"){Q=new Y(null),Q.length=K+1,Q.words=Array(Q.length);for(var M=0;M<Q.length;M++)Q.words[M]=0}var k=A.clone()._ishlnsubmul(R,1,K);if(k.negative===0){if(A=k,Q)Q.words[K]=1}for(var y=K-1;y>=0;y--){var x=(A.words[R.length+y]|0)*67108864+(A.words[R.length+y-1]|0);x=Math.min(x/j|0,67108863),A._ishlnsubmul(R,x,y);while(A.negative!==0)if(x--,A.negative=0,A._ishlnsubmul(R,1,y),!A.isZero())A.negative^=1;if(Q)Q.words[y]=x}if(Q)Q.strip();if(A.strip(),U!=="div"&&_!==0)A.iushrn(_);return{div:Q||null,mod:A}},Y.prototype.divmod=function(W,U,_){if(Z(!W.isZero()),this.isZero())return{div:new Y(0),mod:new Y(0)};var A,R,j;if(this.negative!==0&&W.negative===0){if(j=this.neg().divmod(W,U),U!=="mod")A=j.div.neg();if(U!=="div"){if(R=j.mod.neg(),_&&R.negative!==0)R.iadd(W)}return{div:A,mod:R}}if(this.negative===0&&W.negative!==0){if(j=this.divmod(W.neg(),U),U!=="mod")A=j.div.neg();return{div:A,mod:j.mod}}if((this.negative&W.negative)!==0){if(j=this.neg().divmod(W.neg(),U),U!=="div"){if(R=j.mod.neg(),_&&R.negative!==0)R.isub(W)}return{div:j.div,mod:R}}if(W.length>this.length||this.cmp(W)<0)return{div:new Y(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 Y(this.modn(W.words[0]))};return{div:this.divn(W.words[0]),mod:new Y(this.modn(W.words[0]))}}return this._wordDiv(W,U)},Y.prototype.div=function(W){return this.divmod(W,"div",!1).div},Y.prototype.mod=function(W){return this.divmod(W,"mod",!1).mod},Y.prototype.umod=function(W){return this.divmod(W,"mod",!0).mod},Y.prototype.divRound=function(W){var U=this.divmod(W);if(U.mod.isZero())return U.div;var _=U.div.negative!==0?U.mod.isub(W):U.mod,A=W.ushrn(1),R=W.andln(1),j=_.cmp(A);if(j<0||R===1&&j===0)return U.div;return U.div.negative!==0?U.div.isubn(1):U.div.iaddn(1)},Y.prototype.modn=function(W){Z(W<=67108863);var U=67108864%W,_=0;for(var A=this.length-1;A>=0;A--)_=(U*_+(this.words[A]|0))%W;return _},Y.prototype.idivn=function(W){Z(W<=67108863);var U=0;for(var _=this.length-1;_>=0;_--){var A=(this.words[_]|0)+U*67108864;this.words[_]=A/W|0,U=A%W}return this.strip()},Y.prototype.divn=function(W){return this.clone().idivn(W)},Y.prototype.egcd=function(W){Z(W.negative===0),Z(!W.isZero());var U=this,_=W.clone();if(U.negative!==0)U=U.umod(W);else U=U.clone();var A=new Y(1),R=new Y(0),j=new Y(0),S=new Y(1),K=0;while(U.isEven()&&_.isEven())U.iushrn(1),_.iushrn(1),++K;var Q=_.clone(),M=U.clone();while(!U.isZero()){for(var k=0,y=1;(U.words[0]&y)===0&&k<26;++k,y<<=1);if(k>0){U.iushrn(k);while(k-- >0){if(A.isOdd()||R.isOdd())A.iadd(Q),R.isub(M);A.iushrn(1),R.iushrn(1)}}for(var x=0,p=1;(_.words[0]&p)===0&&x<26;++x,p<<=1);if(x>0){_.iushrn(x);while(x-- >0){if(j.isOdd()||S.isOdd())j.iadd(Q),S.isub(M);j.iushrn(1),S.iushrn(1)}}if(U.cmp(_)>=0)U.isub(_),A.isub(j),R.isub(S);else _.isub(U),j.isub(A),S.isub(R)}return{a:j,b:S,gcd:_.iushln(K)}},Y.prototype._invmp=function(W){Z(W.negative===0),Z(!W.isZero());var U=this,_=W.clone();if(U.negative!==0)U=U.umod(W);else U=U.clone();var A=new Y(1),R=new Y(0),j=_.clone();while(U.cmpn(1)>0&&_.cmpn(1)>0){for(var S=0,K=1;(U.words[0]&K)===0&&S<26;++S,K<<=1);if(S>0){U.iushrn(S);while(S-- >0){if(A.isOdd())A.iadd(j);A.iushrn(1)}}for(var Q=0,M=1;(_.words[0]&M)===0&&Q<26;++Q,M<<=1);if(Q>0){_.iushrn(Q);while(Q-- >0){if(R.isOdd())R.iadd(j);R.iushrn(1)}}if(U.cmp(_)>=0)U.isub(_),A.isub(R);else _.isub(U),R.isub(A)}var k;if(U.cmpn(1)===0)k=A;else k=R;if(k.cmpn(0)<0)k.iadd(W);return k},Y.prototype.gcd=function(W){if(this.isZero())return W.abs();if(W.isZero())return this.abs();var U=this.clone(),_=W.clone();U.negative=0,_.negative=0;for(var A=0;U.isEven()&&_.isEven();A++)U.iushrn(1),_.iushrn(1);do{while(U.isEven())U.iushrn(1);while(_.isEven())_.iushrn(1);var R=U.cmp(_);if(R<0){var j=U;U=_,_=j}else if(R===0||_.cmpn(1)===0)break;U.isub(_)}while(!0);return _.iushln(A)},Y.prototype.invm=function(W){return this.egcd(W).a.umod(W)},Y.prototype.isEven=function(){return(this.words[0]&1)===0},Y.prototype.isOdd=function(){return(this.words[0]&1)===1},Y.prototype.andln=function(W){return this.words[0]&W},Y.prototype.bincn=function(W){Z(typeof W==="number");var U=W%26,_=(W-U)/26,A=1<<U;if(this.length<=_)return this._expand(_+1),this.words[_]|=A,this;var R=A;for(var j=_;R!==0&&j<this.length;j++){var S=this.words[j]|0;S+=R,R=S>>>26,S&=67108863,this.words[j]=S}if(R!==0)this.words[j]=R,this.length++;return this},Y.prototype.isZero=function(){return this.length===1&&this.words[0]===0},Y.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 _;if(this.length>1)_=1;else{if(U)W=-W;Z(W<=67108863,"Number is too big");var A=this.words[0]|0;_=A===W?0:A<W?-1:1}if(this.negative!==0)return-_|0;return _},Y.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},Y.prototype.ucmp=function(W){if(this.length>W.length)return 1;if(this.length<W.length)return-1;var U=0;for(var _=this.length-1;_>=0;_--){var A=this.words[_]|0,R=W.words[_]|0;if(A===R)continue;if(A<R)U=-1;else if(A>R)U=1;break}return U},Y.prototype.gtn=function(W){return this.cmpn(W)===1},Y.prototype.gt=function(W){return this.cmp(W)===1},Y.prototype.gten=function(W){return this.cmpn(W)>=0},Y.prototype.gte=function(W){return this.cmp(W)>=0},Y.prototype.ltn=function(W){return this.cmpn(W)===-1},Y.prototype.lt=function(W){return this.cmp(W)===-1},Y.prototype.lten=function(W){return this.cmpn(W)<=0},Y.prototype.lte=function(W){return this.cmp(W)<=0},Y.prototype.eqn=function(W){return this.cmpn(W)===0},Y.prototype.eq=function(W){return this.cmp(W)===0},Y.red=function(W){return new r(W)},Y.prototype.toRed=function(W){return Z(!this.red,"Already a number in reduction context"),Z(this.negative===0,"red works only with positives"),W.convertTo(this)._forceRed(W)},Y.prototype.fromRed=function(){return Z(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},Y.prototype._forceRed=function(W){return this.red=W,this},Y.prototype.forceRed=function(W){return Z(!this.red,"Already a number in reduction context"),this._forceRed(W)},Y.prototype.redAdd=function(W){return Z(this.red,"redAdd works only with red numbers"),this.red.add(this,W)},Y.prototype.redIAdd=function(W){return Z(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,W)},Y.prototype.redSub=function(W){return Z(this.red,"redSub works only with red numbers"),this.red.sub(this,W)},Y.prototype.redISub=function(W){return Z(this.red,"redISub works only with red numbers"),this.red.isub(this,W)},Y.prototype.redShl=function(W){return Z(this.red,"redShl works only with red numbers"),this.red.shl(this,W)},Y.prototype.redMul=function(W){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,W),this.red.mul(this,W)},Y.prototype.redIMul=function(W){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,W),this.red.imul(this,W)},Y.prototype.redSqr=function(){return Z(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},Y.prototype.redISqr=function(){return Z(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},Y.prototype.redSqrt=function(){return Z(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},Y.prototype.redInvm=function(){return Z(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},Y.prototype.redNeg=function(){return Z(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},Y.prototype.redPow=function(W){return Z(this.red&&!W.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,W)};var E={k256:null,p224:null,p192:null,p25519:null};function D(q,W){this.name=q,this.p=new Y(W,16),this.n=this.p.bitLength(),this.k=new Y(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}D.prototype._tmp=function(){var W=new Y(null);return W.words=Array(Math.ceil(this.n/13)),W},D.prototype.ireduce=function(W){var U=W,_;do this.split(U,this.tmp),U=this.imulK(U),U=U.iadd(this.tmp),_=U.bitLength();while(_>this.n);var A=_<this.n?-1:U.ucmp(this.p);if(A===0)U.words[0]=0,U.length=1;else if(A>0)U.isub(this.p);else if(U.strip!==void 0)U.strip();else U._strip();return U},D.prototype.split=function(W,U){W.iushrn(this.n,0,U)},D.prototype.imulK=function(W){return W.imul(this.k)};function h(){D.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}X(h,D),h.prototype.split=function(W,U){var _=4194303,A=Math.min(W.length,9);for(var R=0;R<A;R++)U.words[R]=W.words[R];if(U.length=A,W.length<=9){W.words[0]=0,W.length=1;return}var j=W.words[9];U.words[U.length++]=j&_;for(R=10;R<W.length;R++){var S=W.words[R]|0;W.words[R-10]=(S&_)<<4|j>>>22,j=S}if(j>>>=22,W.words[R-10]=j,j===0&&W.length>10)W.length-=10;else W.length-=9},h.prototype.imulK=function(W){W.words[W.length]=0,W.words[W.length+1]=0,W.length+=2;var U=0;for(var _=0;_<W.length;_++){var A=W.words[_]|0;U+=A*977,W.words[_]=U&67108863,U=A*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(){D.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}X(v,D);function f(){D.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}X(f,D);function l(){D.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}X(l,D),l.prototype.imulK=function(W){var U=0;for(var _=0;_<W.length;_++){var A=(W.words[_]|0)*19+U,R=A&67108863;A>>>=26,W.words[_]=R,U=A}if(U!==0)W.words[W.length++]=U;return W},Y._prime=function(W){if(E[W])return E[W];var U;if(W==="k256")U=new h;else if(W==="p224")U=new v;else if(W==="p192")U=new f;else if(W==="p25519")U=new l;else throw Error("Unknown prime "+W);return E[W]=U,U};function r(q){if(typeof q==="string"){var W=Y._prime(q);this.m=W.p,this.prime=W}else Z(q.gtn(1),"modulus must be greater than 1"),this.m=q,this.prime=null}r.prototype._verify1=function(W){Z(W.negative===0,"red works only with positives"),Z(W.red,"red works only with red numbers")},r.prototype._verify2=function(W,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")},r.prototype.imod=function(W){if(this.prime)return this.prime.ireduce(W)._forceRed(this);return W.umod(this.m)._forceRed(this)},r.prototype.neg=function(W){if(W.isZero())return W.clone();return this.m.sub(W)._forceRed(this)},r.prototype.add=function(W,U){this._verify2(W,U);var _=W.add(U);if(_.cmp(this.m)>=0)_.isub(this.m);return _._forceRed(this)},r.prototype.iadd=function(W,U){this._verify2(W,U);var _=W.iadd(U);if(_.cmp(this.m)>=0)_.isub(this.m);return _},r.prototype.sub=function(W,U){this._verify2(W,U);var _=W.sub(U);if(_.cmpn(0)<0)_.iadd(this.m);return _._forceRed(this)},r.prototype.isub=function(W,U){this._verify2(W,U);var _=W.isub(U);if(_.cmpn(0)<0)_.iadd(this.m);return _},r.prototype.shl=function(W,U){return this._verify1(W),this.imod(W.ushln(U))},r.prototype.imul=function(W,U){return this._verify2(W,U),this.imod(W.imul(U))},r.prototype.mul=function(W,U){return this._verify2(W,U),this.imod(W.mul(U))},r.prototype.isqr=function(W){return this.imul(W,W.clone())},r.prototype.sqr=function(W){return this.mul(W,W)},r.prototype.sqrt=function(W){if(W.isZero())return W.clone();var U=this.m.andln(3);if(Z(U%2===1),U===3){var _=this.m.add(new Y(1)).iushrn(2);return this.pow(W,_)}var A=this.m.subn(1),R=0;while(!A.isZero()&&A.andln(1)===0)R++,A.iushrn(1);Z(!A.isZero());var j=new Y(1).toRed(this),S=j.redNeg(),K=this.m.subn(1).iushrn(1),Q=this.m.bitLength();Q=new Y(2*Q*Q).toRed(this);while(this.pow(Q,K).cmp(S)!==0)Q.redIAdd(S);var M=this.pow(Q,A),k=this.pow(W,A.addn(1).iushrn(1)),y=this.pow(W,A),x=R;while(y.cmp(j)!==0){var p=y;for(var i=0;p.cmp(j)!==0;i++)p=p.redSqr();Z(i<x);var e=this.pow(M,new Y(1).iushln(x-i-1));k=k.redMul(e),M=e.redSqr(),y=y.redMul(M),x=i}return k},r.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)},r.prototype.pow=function(W,U){if(U.isZero())return new Y(1).toRed(this);if(U.cmpn(1)===0)return W.clone();var _=4,A=Array(1<<_);A[0]=new Y(1).toRed(this),A[1]=W;for(var R=2;R<A.length;R++)A[R]=this.mul(A[R-1],W);var j=A[0],S=0,K=0,Q=U.bitLength()%26;if(Q===0)Q=26;for(R=U.length-1;R>=0;R--){var M=U.words[R];for(var k=Q-1;k>=0;k--){var y=M>>k&1;if(j!==A[0])j=this.sqr(j);if(y===0&&S===0){K=0;continue}if(S<<=1,S|=y,K++,K!==_&&(R!==0||k!==0))continue;j=this.mul(j,A[S]),K=0,S=0}Q=26}return j},r.prototype.convertTo=function(W){var U=W.umod(this.m);return U===W?U.clone():U},r.prototype.convertFrom=function(W){var U=W.clone();return U.red=null,U},Y.mont=function(W){return new u0(W)};function u0(q){if(r.call(this,q),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new Y(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}X(u0,r),u0.prototype.convertTo=function(W){return this.imod(W.ushln(this.shift))},u0.prototype.convertFrom=function(W){var 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 _=W.imul(U),A=_.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),R=_.isub(A).iushrn(this.shift),j=R;if(R.cmp(this.m)>=0)j=R.isub(this.m);else if(R.cmpn(0)<0)j=R.iadd(this.m);return j._forceRed(this)},u0.prototype.mul=function(W,U){if(W.isZero()||U.isZero())return new Y(0)._forceRed(this);var _=W.mul(U),A=_.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),R=_.isub(A).iushrn(this.shift),j=R;if(R.cmp(this.m)>=0)j=R.isub(this.m);else if(R.cmpn(0)<0)j=R.iadd(this.m);return j._forceRed(this)},u0.prototype.invm=function(W){var U=this.imod(W._invmp(this.m).mul(this.r2));return U._forceRed(this)}})(typeof WX>"u"||WX,lY)});var rY=s((VU,QX)=>{if(typeof Object.create==="function")QX.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 QX.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 j$=s((OU,zX)=>{try{if(gJ=A$("util"),typeof gJ.inherits!=="function")throw"";zX.exports=gJ.inherits}catch($){zX.exports=rY()}var gJ});var bJ=s((_U,iY)=>{var hJ=A$("buffer"),p$=hJ.Buffer,t0={},a0;for(a0 in hJ){if(!hJ.hasOwnProperty(a0))continue;if(a0==="SlowBuffer"||a0==="Buffer")continue;t0[a0]=hJ[a0]}var u$=t0.Buffer={};for(a0 in p$){if(!p$.hasOwnProperty(a0))continue;if(a0==="allocUnsafe"||a0==="allocUnsafeSlow")continue;u$[a0]=p$[a0]}t0.Buffer.prototype=p$.prototype;if(!u$.from||u$.from===Uint8Array.from)u$.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 p$($,J,Z)};if(!u$.alloc)u$.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=p$($);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}iY.exports=t0});var cJ=s((Vz)=>{var Uz=j$();function e0($){this._reporterState={obj:null,path:[],options:$||{},errors:[]}}Vz.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 Y=this._reporterState;if(this.exitKey(J),Y.obj!==null)Y.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,Y=J instanceof m$;if(Y)Z=J;else Z=new m$(X.path.map(function(G){return"["+JSON.stringify(G)+"]"}).join(""),J.message||J,J.stack);if(!X.options.partial)throw Z;if(!Y)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)}Uz(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 s$=s((Az)=>{var _z=j$(),pJ=cJ().Reporter,d$=bJ().Buffer;function $$($,J){if(pJ.call(this,J),!d$.isBuffer($)){this.error("Input not Buffer");return}this.base=$,this.offset=0,this.length=$.length}_z($$,pJ);Az.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:pJ.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,pJ.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 n$($,J){if(Array.isArray($))this.length=0,this.value=$.map(function(Z){if(!n$.isEncoderBuffer(Z))Z=new n$(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 $)}Az.EncoderBuffer=n$;n$.isEncoderBuffer=function(J){if(J instanceof n$)return!0;return typeof J==="object"&&J.constructor.name==="EncoderBuffer"&&typeof J.length==="number"&&typeof J.join==="function"};n$.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 eY=s((FU,aY)=>{aY.exports=tY;function tY($,J){if(!$)throw Error(J||"Assertion failed")}tY.equal=function(J,Z,X){if(J!=Z)throw Error(X||"Assertion failed: "+J+" != "+Z)}});var uJ=s((MU,JG)=>{var Mz=cJ().Reporter,Rz=s$().EncoderBuffer,Iz=s$().DecoderBuffer,o0=eY(),$G=["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"],qz=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat($G),Pz=["_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()}JG.exports=t;var jz=["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={};jz.forEach(function(Y){Z[Y]=J[Y]});let X=new this.constructor(Z.parent);return X._baseState=Z,X};t.prototype._wrap=function(){let J=this._baseState;qz.forEach(function(Z){this[Z]=function(){let Y=new this.constructor(this);return J.children.push(Y),Y[Z].apply(Y,arguments)}},this)};t.prototype._init=function(J){let Z=this._baseState;o0(Z.parent===null),J.call(this),Z.children=Z.children.filter(function(X){return X._baseState.parent===this},this),o0.equal(Z.children.length,1,"Root node can have only one child")};t.prototype._useArgs=function(J){let Z=this._baseState,X=J.filter(function(Y){return Y instanceof this.constructor},this);if(J=J.filter(function(Y){return!(Y instanceof this.constructor)},this),X.length!==0)o0(Z.children===null),Z.children=X,X.forEach(function(Y){Y._baseState.parent=this},this);if(J.length!==0)o0(Z.args===null),Z.args=J,Z.reverseArgs=J.map(function(Y){if(typeof Y!=="object"||Y.constructor!==Object)return Y;let G={};return Object.keys(Y).forEach(function(H){if(H==(H|0))H|=0;let z=Y[H];G[z]=H}),G})};Pz.forEach(function($){t.prototype[$]=function(){let Z=this._baseState;throw Error($+" not implemented for encoding: "+Z.enc)}});$G.forEach(function($){t.prototype[$]=function(){let Z=this._baseState,X=Array.prototype.slice.call(arguments);return o0(Z.tag===null),Z.tag=$,this._useArgs(X),this}});t.prototype.use=function(J){o0(J);let Z=this._baseState;return o0(Z.use===null),Z.use=J,this};t.prototype.optional=function(){let J=this._baseState;return J.optional=!0,this};t.prototype.def=function(J){let Z=this._baseState;return o0(Z.default===null),Z.default=J,Z.optional=!0,this};t.prototype.explicit=function(J){let Z=this._baseState;return o0(Z.explicit===null&&Z.implicit===null),Z.explicit=J,this};t.prototype.implicit=function(J){let Z=this._baseState;return o0(Z.explicit===null&&Z.implicit===null),Z.implicit=J,this};t.prototype.obj=function(){let J=this._baseState,Z=Array.prototype.slice.call(arguments);if(J.obj=!0,Z.length!==0)this._useArgs(Z);return this};t.prototype.key=function(J){let Z=this._baseState;return o0(Z.key===null),Z.key=J,this};t.prototype.any=function(){let J=this._baseState;return J.any=!0,this};t.prototype.choice=function(J){let Z=this._baseState;return o0(Z.choice===null),Z.choice=J,this._useArgs(Object.keys(J).map(function(X){return J[X]})),this};t.prototype.contains=function(J){let Z=this._baseState;return o0(Z.use===null),Z.contains=J,this};t.prototype._decode=function(J,Z){let X=this._baseState;if(X.parent===null)return J.wrapResult(X.children[0]._decode(J,Z));let Y=X.default,G=!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);G=!0}catch(F){G=!1}J.restore(O)}else if(G=this._peekTag(J,V,X.any),J.isError(G))return G}let z;if(X.obj&&G)z=J.enterObject();if(G){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 F=this._decodeTag(J,X.implicit!==null?X.implicit:X.tag,X.any);if(J.isError(F))return F;if(X.any)Y=J.raw(O);else J=F}if(Z&&Z.track&&X.tag!==null)Z.track(J.path(),V,J.length,"tagged");if(Z&&Z.track&&X.tag!==null)Z.track(J.path(),J.offset,J.length,"content");if(X.any);else if(X.choice===null)Y=this._decodeGeneric(X.tag,J,Z);else Y=this._decodeChoice(J,Z);if(J.isError(Y))return Y;if(!X.any&&X.choice===null&&X.children!==null)X.children.forEach(function(F){F._decode(J,Z)});if(X.contains&&(X.tag==="octstr"||X.tag==="bitstr")){let O=new Iz(Y);Y=this._getUse(X.contains,J._reporterState.obj)._decode(O,Z)}}if(X.obj&&G)Y=J.leaveObject(z);if(X.key!==null&&(Y!==null||G===!0))J.leaveKey(H,X.key,Y);else if(H!==null)J.exitKey(H);return Y};t.prototype._decodeGeneric=function(J,Z,X){let Y=this._baseState;if(J==="seq"||J==="set")return null;if(J==="seqof"||J==="setof")return this._decodeList(Z,J,Y.args[0],X);else if(/str$/.test(J))return this._decodeStr(Z,J,X);else if(J==="objid"&&Y.args)return this._decodeObjid(Z,Y.args[0],Y.args[1],X);else if(J==="objid")return this._decodeObjid(Z,null,null,X);else if(J==="gentime"||J==="utctime")return this._decodeTime(Z,J,X);else if(J==="null_")return this._decodeNull(Z,X);else if(J==="bool")return this._decodeBool(Z,X);else if(J==="objDesc")return this._decodeStr(Z,J,X);else if(J==="int"||J==="enum")return this._decodeInt(Z,Y.args&&Y.args[0],X);if(Y.use!==null)return this._getUse(Y.use,Z._reporterState.obj)._decode(Z,X);else return Z.error("unknown tag: "+J)};t.prototype._getUse=function(J,Z){let X=this._baseState;if(X.useDecoder=this._use(J,Z),o0(X.useDecoder._baseState.parent===null),X.useDecoder=X.useDecoder._baseState.children[0],X.implicit!==X.useDecoder._baseState.implicit)X.useDecoder=X.useDecoder.clone(),X.useDecoder._baseState.implicit=X.implicit;return X.useDecoder};t.prototype._decodeChoice=function(J,Z){let X=this._baseState,Y=null,G=!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;Y={type:H,value:O},G=!0}catch(O){return J.restore(z),!1}return!0},this),!G)return J.error("Choice not matched");return Y};t.prototype._createEncoderBuffer=function(J){return new Rz(J,this.reporter)};t.prototype._encode=function(J,Z,X){let Y=this._baseState;if(Y.default!==null&&Y.default===J)return;let G=this._encodeValue(J,Z,X);if(G===void 0)return;if(this._skipDefault(G,Z,X))return;return G};t.prototype._encodeValue=function(J,Z,X){let Y=this._baseState;if(Y.parent===null)return Y.children[0]._encode(J,Z||new Mz);let G=null;if(this.reporter=Z,Y.optional&&J===void 0)if(Y.default!==null)J=Y.default;else return;let H=null,z=!1;if(Y.any)G=this._createEncoderBuffer(J);else if(Y.choice)G=this._encodeChoice(J,Z);else if(Y.contains)H=this._getUse(Y.contains,X)._encode(J,Z),z=!0;else if(Y.children)H=Y.children.map(function(V){if(V._baseState.tag==="null_")return V._encode(null,Z,J);if(V._baseState.key===null)return Z.error("Child should have a key");let O=Z.enterKey(V._baseState.key);if(typeof J!=="object")return Z.error("Child expected, but input is not object");let F=V._encode(J[V._baseState.key],Z,J);return Z.leaveKey(O),F},this).filter(function(V){return V}),H=this._createEncoderBuffer(H);else if(Y.tag==="seqof"||Y.tag==="setof"){if(!(Y.args&&Y.args.length===1))return Z.error("Too many args for : "+Y.tag);if(!Array.isArray(J))return Z.error("seqof/setof, but data is not Array");let V=this.clone();V._baseState.implicit=null,H=this._createEncoderBuffer(J.map(function(O){let F=this._baseState;return this._getUse(F.args[0],J)._encode(O,Z)},V))}else if(Y.use!==null)G=this._getUse(Y.use,X)._encode(J,Z);else H=this._encodePrimitive(Y.tag,J),z=!0;if(!Y.any&&Y.choice===null){let V=Y.implicit!==null?Y.implicit:Y.tag,O=Y.implicit===null?"universal":"context";if(V===null){if(Y.use===null)Z.error("Tag could be omitted only for .use()")}else if(Y.use===null)G=this._encodeComposite(V,z,O,H)}if(Y.explicit!==null)G=this._encodeComposite(Y.explicit,!1,"context",G);return G};t.prototype._encodeChoice=function(J,Z){let X=this._baseState,Y=X.choice[J.type];if(!Y)o0(!1,J.type+" not found in "+JSON.stringify(Object.keys(X.choice)));return Y._encode(J.value,Z)};t.prototype._encodePrimitive=function(J,Z){let X=this._baseState;if(/str$/.test(J))return this._encodeStr(Z,J);else if(J==="objid"&&X.args)return this._encodeObjid(Z,X.reverseArgs[0],X.args[1]);else if(J==="objid")return this._encodeObjid(Z,null,null);else if(J==="gentime"||J==="utctime")return this._encodeTime(Z,J);else if(J==="null_")return this._encodeNull();else if(J==="int"||J==="enum")return this._encodeInt(Z,X.args&&X.reverseArgs[0]);else if(J==="bool")return this._encodeBool(Z);else if(J==="objDesc")return this._encodeStr(Z,J);else throw Error("Unsupported tag: "+J)};t.prototype._isNumstr=function(J){return/^[0-9 ]*$/.test(J)};t.prototype._isPrintstr=function(J){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(J)}});var mJ=s((Bz)=>{function ZG($){let J={};return Object.keys($).forEach(function(Z){if((Z|0)==Z)Z=Z|0;let X=$[Z];J[X]=Z}),J}Bz.tagClass={0:"universal",1:"application",2:"context",3:"private"};Bz.tagClassByName=ZG(Bz.tagClass);Bz.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"};Bz.tagByName=ZG(Bz.tag)});var VX=s((IU,HG)=>{var Cz=j$(),U$=bJ().Buffer,GG=uJ(),UX=mJ();function WG($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new Z$,this.tree._init($.body)}HG.exports=WG;WG.prototype.encode=function(J,Z){return this.tree._encode(J,Z).join()};function Z$($){GG.call(this,"der",$)}Cz(Z$,GG);Z$.prototype._encodeComposite=function(J,Z,X,Y){let G=Ez(J,Z,X,this.reporter);if(Y.length<128){let V=U$.alloc(2);return V[0]=G,V[1]=Y.length,this._createEncoderBuffer([V,Y])}let H=1;for(let V=Y.length;V>=256;V>>=8)H++;let z=U$.alloc(2+H);z[0]=G,z[1]=128|H;for(let V=1+H,O=Y.length;O>0;V--,O>>=8)z[V]=O&255;return this._createEncoderBuffer([z,Y])};Z$.prototype._encodeStr=function(J,Z){if(Z==="bitstr")return this._createEncoderBuffer([J.unused|0,J.data]);else if(Z==="bmpstr"){let X=U$.alloc(J.length*2);for(let Y=0;Y<J.length;Y++)X.writeUInt16BE(J.charCodeAt(Y),Y*2);return this._createEncoderBuffer(X)}else if(Z==="numstr"){if(!this._isNumstr(J))return this.reporter.error("Encoding of string type: numstr supports only digits and space");return this._createEncoderBuffer(J)}else if(Z==="printstr"){if(!this._isPrintstr(J))return this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");return this._createEncoderBuffer(J)}else if(/str$/.test(Z))return this._createEncoderBuffer(J);else if(Z==="objDesc")return this._createEncoderBuffer(J);else return this.reporter.error("Encoding of string type: "+Z+" unsupported")};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 Y=0;for(let z=0;z<J.length;z++){let V=J[z];for(Y++;V>=128;V>>=7)Y++}let G=U$.alloc(Y),H=G.length-1;for(let z=J.length-1;z>=0;z--){let V=J[z];G[H--]=V&127;while((V>>=7)>0)G[H--]=128|V&127}return this._createEncoderBuffer(G)};function J$($){if($<10)return"0"+$;else return $}Z$.prototype._encodeTime=function(J,Z){let X,Y=new Date(J);if(Z==="gentime")X=[J$(Y.getUTCFullYear()),J$(Y.getUTCMonth()+1),J$(Y.getUTCDate()),J$(Y.getUTCHours()),J$(Y.getUTCMinutes()),J$(Y.getUTCSeconds()),"Z"].join("");else if(Z==="utctime")X=[J$(Y.getUTCFullYear()%100),J$(Y.getUTCMonth()+1),J$(Y.getUTCDate()),J$(Y.getUTCHours()),J$(Y.getUTCMinutes()),J$(Y.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"&&!U$.isBuffer(J)){let G=J.toArray();if(!J.sign&&G[0]&128)G.unshift(0);J=U$.from(G)}if(U$.isBuffer(J)){let G=J.length;if(J.length===0)G++;let H=U$.alloc(G);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 G=J;G>=256;G>>=8)X++;let Y=Array(X);for(let G=Y.length-1;G>=0;G--)Y[G]=J&255,J>>=8;if(Y[0]&128)Y.unshift(0);return this._createEncoderBuffer(U$.from(Y))};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 Y=this._baseState,G;if(Y.default===null)return!1;let H=J.join();if(Y.defaultBuffer===void 0)Y.defaultBuffer=this._encodeValue(Y.default,Z,X).join();if(H.length!==Y.defaultBuffer.length)return!1;for(G=0;G<H.length;G++)if(H[G]!==Y.defaultBuffer[G])return!1;return!0};function Ez($,J,Z,X){let Y;if($==="seqof")$="seq";else if($==="setof")$="set";if(UX.tagByName.hasOwnProperty($))Y=UX.tagByName[$];else if(typeof $==="number"&&($|0)===$)Y=$;else return X.error("Unknown tag: "+$);if(Y>=31)return X.error("Multi-octet tag encoding unsupported");if(!J)Y|=32;return Y|=UX.tagClassByName[Z||"universal"]<<6,Y}});var zG=s((qU,QG)=>{var wz=j$(),OX=VX();function _X($){OX.call(this,$),this.enc="pem"}wz(_X,OX);QG.exports=_X;_X.prototype.encode=function(J,Z){let Y=OX.prototype.encode.call(this,J).toString("base64"),G=["-----BEGIN "+Z.label+"-----"];for(let H=0;H<Y.length;H+=64)G.push(Y.slice(H,H+64));return G.push("-----END "+Z.label+"-----"),G.join(`
|
|
6
|
+
`)}});var AX=s((VG)=>{var UG=VG;UG.der=VX();UG.pem=zG()});var FX=s((jU,MG)=>{var Tz=j$(),vz=HX(),OG=s$().DecoderBuffer,AG=uJ(),_G=mJ();function KG($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new r0,this.tree._init($.body)}MG.exports=KG;KG.prototype.decode=function(J,Z){if(!OG.isDecoderBuffer(J))J=new OG(J,Z);return this.tree._decode(J,Z)};function r0($){AG.call(this,"der",$)}Tz(r0,AG);r0.prototype._peekTag=function(J,Z,X){if(J.isEmpty())return!1;let Y=J.save(),G=KX(J,'Failed to peek tag: "'+Z+'"');if(J.isError(G))return G;return J.restore(Y),G.tag===Z||G.tagStr===Z||G.tagStr+"of"===Z||X};r0.prototype._decodeTag=function(J,Z,X){let Y=KX(J,'Failed to decode tag of "'+Z+'"');if(J.isError(Y))return Y;let G=FG(J,Y.primitive,'Failed to get length of "'+Z+'"');if(J.isError(G))return G;if(!X&&Y.tag!==Z&&Y.tagStr!==Z&&Y.tagStr+"of"!==Z)return J.error('Failed to match tag: "'+Z+'"');if(Y.primitive||G!==null)return J.skip(G,'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 G=J.offset-H.offset,J.restore(H),J.skip(G,'Failed to match body of: "'+Z+'"')};r0.prototype._skipUntilEnd=function(J,Z){for(;;){let X=KX(J,Z);if(J.isError(X))return X;let Y=FG(J,X.primitive,Z);if(J.isError(Y))return Y;let G;if(X.primitive||Y!==null)G=J.skip(Y);else G=this._skipUntilEnd(J,Z);if(J.isError(G))return G;if(X.tagStr==="end")break}};r0.prototype._decodeList=function(J,Z,X,Y){let G=[];while(!J.isEmpty()){let H=this._peekTag(J,"end");if(J.isError(H))return H;let z=X.decode(J,"der",Y);if(J.isError(z)&&H)break;G.push(z)}return G};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 Y="";for(let G=0;G<X.length/2;G++)Y+=String.fromCharCode(X.readUInt16BE(G*2));return Y}else if(Z==="numstr"){let X=J.raw().toString("ascii");if(!this._isNumstr(X))return J.error("Decoding of string type: numstr unsupported characters");return X}else if(Z==="octstr")return J.raw();else if(Z==="objDesc")return J.raw();else if(Z==="printstr"){let X=J.raw().toString("ascii");if(!this._isPrintstr(X))return J.error("Decoding of string type: printstr unsupported characters");return X}else if(/str$/.test(Z))return J.raw().toString();else return J.error("Decoding of string type: "+Z+" unsupported")};r0.prototype._decodeObjid=function(J,Z,X){let Y,G=[],H=0,z=0;while(!J.isEmpty())if(z=J.readUInt8(),H<<=7,H|=z&127,(z&128)===0)G.push(H),H=0;if(z&128)G.push(H);let V=G[0]/40|0,O=G[0]%40;if(X)Y=G;else Y=[V,O].concat(G.slice(1));if(Z){let F=Z[Y.join(" ")];if(F===void 0)F=Z[Y.join(".")];if(F!==void 0)Y=F}return Y};r0.prototype._decodeTime=function(J,Z){let X=J.raw().toString(),Y,G,H,z,V,O;if(Z==="gentime")Y=X.slice(0,4)|0,G=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(Y=X.slice(0,2)|0,G=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,Y<70)Y=2000+Y;else Y=1900+Y;else return J.error("Decoding "+Z+" time is not supported yet");return Date.UTC(Y,G-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(),Y=new vz(X);if(Z)Y=Z[Y.toString(10)]||Y;return Y};r0.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getDecoder("der").tree};function KX($,J){let Z=$.readUInt8(J);if($.isError(Z))return Z;let X=_G.tagClass[Z>>6],Y=(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 G=_G.tag[Z];return{cls:X,primitive:Y,tag:Z,tagStr:G}}function FG($,J,Z){let X=$.readUInt8(Z);if($.isError(X))return X;if(!J&&X===128)return null;if((X&128)===0)return X;let Y=X&127;if(Y>4)return $.error("length octect is too long");X=0;for(let G=0;G<Y;G++){X<<=8;let H=$.readUInt8(Z);if($.isError(H))return H;X|=H}return X}});var IG=s((BU,RG)=>{var Nz=j$(),Dz=bJ().Buffer,MX=FX();function RX($){MX.call(this,$),this.enc="pem"}Nz(RX,MX);RG.exports=RX;RX.prototype.decode=function(J,Z){let X=J.toString().split(/[\r\n]+/g),Y=Z.label.toUpperCase(),G=/^-----(BEGIN|END) ([^-]+)-----$/,H=-1,z=-1;for(let F=0;F<X.length;F++){let I=X[F].match(G);if(I===null)continue;if(I[2]!==Y)continue;if(H===-1){if(I[1]!=="BEGIN")break;H=F}else{if(I[1]!=="END")break;z=F;break}}if(H===-1||z===-1)throw Error("PEM section not found for: "+Y);let V=X.slice(H+1,z).join("");V.replace(/[^a-z0-9+/=]+/gi,"");let O=Dz.from(V,"base64");return MX.prototype.decode.call(this,O,Z)}});var IX=s((PG)=>{var qG=PG;qG.der=FX();qG.pem=IG()});var BG=s((jG)=>{var kz=AX(),yz=IX(),xz=j$(),fz=jG;fz.define=function(J,Z){return new o$(J,Z)};function o$($,J){this.name=$,this.body=J,this.decoders={},this.encoders={}}o$.prototype._createNamed=function(J){let Z=this.name;function X(Y){this._initNamed(Y,Z)}return xz(X,J),X.prototype._initNamed=function(G,H){J.call(this,G,H)},new X(this)};o$.prototype._getDecoder=function(J){if(J=J||"der",!this.decoders.hasOwnProperty(J))this.decoders[J]=this._createNamed(yz[J]);return this.decoders[J]};o$.prototype.decode=function(J,Z,X){return this._getDecoder(Z).decode(J,X)};o$.prototype._getEncoder=function(J){if(J=J||"der",!this.encoders.hasOwnProperty(J))this.encoders[J]=this._createNamed(kz[J]);return this.encoders[J]};o$.prototype.encode=function(J,Z,X){return this._getEncoder(Z).encode(J,X)}});var SG=s((LG)=>{var dJ=LG;dJ.Reporter=cJ().Reporter;dJ.DecoderBuffer=s$().DecoderBuffer;dJ.EncoderBuffer=s$().EncoderBuffer;dJ.Node=uJ()});var wG=s((EG)=>{var CG=EG;CG._reverse=function(J){let Z={};return Object.keys(J).forEach(function(X){if((X|0)==X)X=X|0;let Y=J[X];Z[Y]=X}),Z};CG.der=mJ()});var vG=s((TG)=>{var l$=TG;l$.bignum=HX();l$.define=BG().define;l$.base=SG();l$.constants=wG();l$.decoders=IX();l$.encoders=AX()});var kG=s((qX,DG)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var nJ=A$("buffer"),Q$=nJ.Buffer;function NG($,J){for(var Z in $)J[Z]=$[Z]}if(Q$.from&&Q$.alloc&&Q$.allocUnsafe&&Q$.allocUnsafeSlow)DG.exports=nJ;else NG(nJ,qX),qX.Buffer=T$;function T$($,J,Z){return Q$($,J,Z)}T$.prototype=Object.create(Q$.prototype);NG(Q$,T$);T$.from=function($,J,Z){if(typeof $==="number")throw TypeError("Argument must not be a number");return Q$($,J,Z)};T$.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};T$.allocUnsafe=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return Q$($)};T$.allocUnsafeSlow=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return nJ.SlowBuffer($)}});var xG=s((TU,yG)=>{function PX($){var J=($/8|0)+($%8===0?0:1);return J}var gz={ES256:PX(256),ES384:PX(384),ES512:PX(521)};function hz($){var J=gz[$];if(J)return J;throw Error('Unknown algorithm "'+$+'"')}yG.exports=hz});var uG=s((vU,pG)=>{var sJ=kG().Buffer,gG=xG(),oJ=128,hG=0,bz=32,cz=16,pz=2,bG=cz|bz|hG<<6,lJ=pz|hG<<6;function uz($){return $.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function cG($){if(sJ.isBuffer($))return $;else if(typeof $==="string")return sJ.from($,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function mz($,J){$=cG($);var Z=gG(J),X=Z+1,Y=$.length,G=0;if($[G++]!==bG)throw Error('Could not find expected "seq"');var H=$[G++];if(H===(oJ|1))H=$[G++];if(Y-G<H)throw Error('"seq" specified length of "'+H+'", only "'+(Y-G)+'" remaining');if($[G++]!==lJ)throw Error('Could not find expected "int" for "r"');var z=$[G++];if(Y-G-2<z)throw Error('"r" specified length of "'+z+'", only "'+(Y-G-2)+'" available');if(X<z)throw Error('"r" specified length of "'+z+'", max of "'+X+'" is acceptable');var V=G;if(G+=z,$[G++]!==lJ)throw Error('Could not find expected "int" for "s"');var O=$[G++];if(Y-G!==O)throw Error('"s" specified length of "'+O+'", expected "'+(Y-G)+'"');if(X<O)throw Error('"s" specified length of "'+O+'", max of "'+X+'" is acceptable');var F=G;if(G+=O,G!==Y)throw Error('Expected to consume entire buffer, but "'+(Y-G)+'" bytes remain');var I=Z-z,B=Z-O,L=sJ.allocUnsafe(I+z+B+O);for(G=0;G<I;++G)L[G]=0;$.copy(L,G,V+Math.max(-I,0),V+z),G=Z;for(var C=G;G<C+B;++G)L[G]=0;return $.copy(L,G,F+Math.max(-B,0),F+O),L=L.toString("base64"),L=uz(L),L}function fG($,J,Z){var X=0;while(J+X<Z&&$[J+X]===0)++X;var Y=$[J+X]>=oJ;if(Y)--X;return X}function dz($,J){$=cG($);var Z=gG(J),X=$.length;if(X!==Z*2)throw TypeError('"'+J+'" signatures must be "'+Z*2+'" bytes, saw "'+X+'"');var Y=fG($,0,Z),G=fG($,Z,$.length),H=Z-Y,z=Z-G,V=2+H+1+1+z,O=V<oJ,F=sJ.allocUnsafe((O?2:3)+V),I=0;if(F[I++]=bG,O)F[I++]=V;else F[I++]=oJ|1,F[I++]=V&255;if(F[I++]=lJ,F[I++]=H,Y<0)F[I++]=0,I+=$.copy(F,I,0,Z);else I+=$.copy(F,I,Y,Z);if(F[I++]=lJ,F[I++]=z,G<0)F[I++]=0,$.copy(F,I,Z);else $.copy(F,I,Z+G);return F}pG.exports={derToJose:mz,joseToDer:dz}});var SX=s((NU,ZW)=>{var LX=vG(),{createHmac:nG,createVerify:nz,createSign:sz,timingSafeEqual:oz,createPublicKey:lz,constants:{RSA_PKCS1_PSS_PADDING:sG,RSA_PSS_SALTLEN_DIGEST:oG,RSA_PKCS1_PADDING:lG,RSA_PSS_SALTLEN_MAX_SIGN:rz,RSA_PSS_SALTLEN_AUTO:iz},sign:mG,verify:dG}=A$("crypto"),{joseToDer:tz,derToJose:az}=uG(),rG=GX(),{TokenError:J0}=c$(),iG=/[=+/]/g,ez={"=":"","+":"-","/":"_"},tG=/^-----BEGIN(?: (RSA|EC|ENCRYPTED))? PRIVATE KEY-----/,aG=/^-----BEGIN(?: (RSA))? PUBLIC KEY-----/,rJ=new rG(1000),jX=new rG(1000),eG=["HS256","HS384","HS512"],$6=["ES256","ES384","ES512"],BX=["RS256","RS384","RS512","PS256","PS384","PS512"],J6=["EdDSA"],$W={"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"]}},Z6=LX.define("PrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),X6=LX.define("PublicKey",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),Y6=LX.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 JW($){return ez[$]}function QJ($,J,Z,X){return $.set(J,[Z,X]),Z||X}function G6($){if($.match(aG)||$.includes("-----BEGIN CERTIFICATE-----"))throw new J0(J0.codes.invalidKey,"Public keys are not supported for signing.");let J=$.trim().match(tG);if(!J)return"HS256";let Z,X,Y;switch(J[1]){case"RSA":return"RS256";case"EC":Z=Y6.decode($,"pem",{label:"EC PRIVATE KEY"}),Y=Z.parameters.value.join(".");break;case"ENCRYPTED":return"ENCRYPTED";default:switch(Z=Z6.decode($,"pem",{label:"PRIVATE KEY"}),X=Z.algorithm.algorithm.join("."),X){case"1.2.840.113549.1.1.1":return"RS256";case"1.2.840.10045.2.1":Y=Z.algorithm.parameters.join(".");break;case"1.3.101.112":case"1.3.101.113":return"EdDSA";default:throw new J0(J0.codes.invalidKey,`Unsupported PEM PCKS8 private key with OID ${X}.`)}}let G=$W[Y];if(!G)throw new J0(J0.codes.invalidKey,`Unsupported EC private key with curve ${Y}.`);return`ES${G.bits}`}function W6($){let J=$.match(aG);if($.match(tG))throw new J0(J0.codes.invalidKey,"Private keys are not supported for verifying.");else if(J&&J[1]==="RSA")return BX;else if(!J&&!$.includes("-----BEGIN CERTIFICATE-----"))return eG;if($.includes("-----BEGIN CERTIFICATE-----"))$=lz($).export({type:"spki",format:"pem"});let Z=X6.decode($,"pem",{label:"PUBLIC KEY"}),X=Z.algorithm.algorithm.join("."),Y;switch(X){case"1.2.840.113549.1.1.1":return BX;case"1.2.840.10045.2.1":Y=Z.algorithm.parameters.join(".");break;case"1.3.101.112":case"1.3.101.113":return["EdDSA"];default:throw new J0(J0.codes.invalidKey,`Unsupported PEM PCKS8 public key with OID ${X}.`)}let G=$W[Y];if(!G)throw new J0(J0.codes.invalidKey,`Unsupported EC public key with curve ${Y}.`);return[`ES${G.bits}`]}function H6($,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]=rJ.get($)||[];if(Z)return Z;else if(X)throw X;try{let Y=G6($);if(Y==="ENCRYPTED")return QJ(rJ,$,J);return QJ(rJ,$,Y)}catch(Y){throw QJ(rJ,$,null,J0.wrap(Y,J0.codes.invalidKey,"Unsupported PEM private key."))}}function Q6($){if(!$)return"none";let[J,Z]=jX.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(jX,$,W6($))}catch(X){throw QJ(jX,$,null,J0.wrap(X,J0.codes.invalidKey,"Unsupported PEM public key."))}}function z6($,J,Z){try{let X=$.slice(0,2),Y=`sha${$.slice(2)}`,G,H;switch(X){case"HS":G=nG(Y,J).update(Z).digest("base64");break;case"ES":G=az(mG(Y,Buffer.from(Z,"utf-8"),J),$).toString("base64");break;case"RS":case"PS":if(H={key:J,padding:lG,saltLength:rz},X==="PS")H.padding=sG,H.saltLength=oG;G=sz(Y).update(Z).sign(H).toString("base64");break;case"Ed":G=mG(void 0,Buffer.from(Z,"utf-8"),J).toString("base64")}return G.replace(iG,JW)}catch(X){throw new J0(J0.codes.signError,"Cannot create the signature.",{originalError:X})}}function U6($,J,Z,X){try{let Y=$.slice(0,2),G=`SHA${$.slice(2)}`;if(X=Buffer.from(X,"base64"),Y==="HS")try{return oz(nG(G,J).update(Z).digest(),X)}catch{return!1}else if(Y==="Ed")if(typeof dG==="function")return dG(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:lG,saltLength:iz};if(Y==="PS")H.padding=sG,H.saltLength=oG;else if(Y==="ES")X=tz(X,$);return nz("RSA-"+G).update(Z).verify(H,X)}catch(Y){throw new J0(J0.codes.verifyError,"Cannot verify the signature.",{originalError:Y})}}ZW.exports={base64UrlMatcher:iG,base64UrlReplacer:JW,hsAlgorithms:eG,rsaAlgorithms:BX,esAlgorithms:$6,edAlgorithms:J6,detectPrivateKeyAlgorithm:H6,detectPublicKeyAlgorithms:Q6,createSignature:z6,verifySignature:U6}});var CX=s((DU,YW)=>{var{createHash:XW}=A$("crypto"),V6=/"alg"\s*:\s*"[HERP]S(256|384)"/m,O6=/"alg"\s*:\s*"EdDSA"/m,_6=/"crv"\s*:\s*"Ed448"/m;function A6($,J,Z){let X=$(J,Z);if(X&&typeof X.then==="function")X.then((Y)=>{process.nextTick(()=>Z(null,Y))}).catch(Z)}function K6($){if(typeof $==="function")return[$];let J,Z,X=new Promise((Y,G)=>{J=Y,Z=G});return[function(Y,G){if(Y)return Z(Y);return J(G)},X]}function F6($){let J=$.split(".",1)[0],Z=Buffer.from(J,"base64").toString("utf-8"),X=null;if(Z.match(O6)&&Z.match(_6))X=XW("shake256",{outputLength:114});else{let Y=Z.match(V6);X=XW(`sha${Y?Y[1]:"512"}`)}return X.update($).digest("hex")}YW.exports={getAsyncKey:A6,ensurePromiseCallback:K6,hashToken:F6}});var VW=s((kU,UW)=>{var{createPublicKey:M6,createSecretKey:R6}=A$("crypto"),I6=GX(),{hsAlgorithms:WW,verifySignature:q6,detectPublicKeyAlgorithms:HW}=SX(),P6=$X(),{TokenError:m}=c$(),{getAsyncKey:j6,ensurePromiseCallback:B6,hashToken:L6}=CX();function S6($,J){return $===J}function QW($,J){for(let Z of $)if(J.includes(Z))return;throw new m(m.codes.invalidKey,`Invalid public key provided for algorithms ${$.join(", ")}.`)}function zW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J?R6($):M6($)}function zJ($){if(!Array.isArray($))$=[$];return $.filter((J)=>J).map((J)=>{if(J&&typeof J.test==="function")return J;return{test:S6.bind(null,J)}})}function C6($){let J=parseInt($===!0?1000:$,10);return J>0?new I6(J):null}function r$({cache:$,token:J,cacheTTL:Z,payload:X,ignoreExpiration:Y,ignoreNotBefore:G,maxAge:H,clockTimestamp:z=Date.now(),clockTolerance:V,errorCacheTTL:O,cacheKeyBuilder:F},I){if(!$)return I;let B=[I,0,0];if(I instanceof m){let w=typeof O==="function"?O(I):O;return B[2]=z+V+w,$.set(F(J),B),I}if(X&&typeof X.iat==="number"){if(B[1]=!G&&typeof X.nbf==="number"?X.nbf*1000-V:0,!Y){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(F(J),B),I}function E6($,J,Z){if($ instanceof m){if(!J)throw $;J($)}else{if(!J)return $;J(null,$)}return Z}function w6($,J,Z,X,Y){if(!Y.includes(J.alg))throw new m(m.codes.invalidAlgorithm,"The token algorithm is invalid.");if(Z&&!q6(J.alg,X,$,Z))throw new m(m.codes.invalidSignature,"The token signature is invalid.")}function T6($,J,Z,X,Y){let G=Z?`The ${J} claim must be a ${Y} or an array of ${Y}s.`:`The ${J} claim must be a ${Y}.`;if(X&&!Z)throw new m(m.codes.invalidClaimValue,G);if($.map((H)=>typeof H).some((H)=>H!==Y))throw new m(m.codes.invalidClaimType,G)}function v6($,J,Z,X){let Y=X?`None of ${J} claim values are allowed.`:`The ${J} claim value is not allowed.`;if(!$.some((G)=>Z.some((H)=>H.test(G))))throw new m(m.codes.invalidClaimValue,Y)}function N6($,J,Z,X,Y,G){let H=$*1000+(J||0);if(!(X?Z>=H:Z<=H))throw new m(m.codes[Y],`The token ${G} at ${new Date(H).toISOString()}.`)}function GW($,{input:J,header:Z,payload:X,signature:Y},{validators:G,allowedAlgorithms:H,checkTyp:z,clockTimestamp:V,requiredClaims:O}){let F=$ instanceof Buffer?$.length:!!$;if(F&&!Y)throw new m(m.codes.missingSignature,"The token signature is missing.");else if(!F&&Y)throw new m(m.codes.missingKey,"The key option is missing.");if(w6(J,Z,Y,$,H),z&&(typeof Z.typ!=="string"||z!==Z.typ.toLowerCase().replace(/^application\//,"")))throw new m(m.codes.invalidType,"Invalid typ.");if(O){for(let B of O)if(!(B in X))throw new m(m.codes.missingRequiredClaim,`The ${B} claim is required.`)}let I=V||Date.now();for(let{type:B,claim:L,allowed:C,array:w,modifier:T,greater:N,errorCode:E,errorVerb:D}of G){let h=X[L],v=Array.isArray(h),f=v?h:[h];if(!(L in X))continue;if(T6(f,L,w,v,B==="date"?"number":"string"),B==="date")N6(h,T,I,N,E,D);else v6(f,L,C,v)}}function D6({key:$,allowedAlgorithms:J,complete:Z,cacheTTL:X,checkTyp:Y,clockTimestamp:G,clockTolerance:H,ignoreExpiration:z,ignoreNotBefore:V,maxAge:O,isAsync:F,validators:I,decode:B,cache:L,requiredClaims:C,errorCacheTTL:w,cacheKeyBuilder:T},N,E){let[D,h]=F?B6(E):[];if(L){let[U,_,A]=L.get(T(N))||[void 0,0,0],R=G||Date.now();if(typeof U<"u"&&(_===0||R<_&&U.code==="FAST_JWT_INACTIVE"||R>=_&&U.code!=="FAST_JWT_INACTIVE")&&(A===0||R<=A))return E6(U,D,h)}let v;try{v=B(N)}catch(U){if(D)return D(U),h;throw U}let{header:f,payload:l,signature:r,input:u0}=v,q={cache:L,token:N,cacheTTL:X,errorCacheTTL:w,ignoreExpiration:z,ignoreNotBefore:V,maxAge:O,clockTimestamp:G,clockTolerance:H,payload:l,cacheKeyBuilder:T},W={validators:I,allowedAlgorithms:J,checkTyp:Y,clockTimestamp:G,clockTolerance:H,requiredClaims:C};if(!D)try{return GW($,v,W),r$(q,Z?{header:f,payload:l,signature:r,input:u0}:l)}catch(U){throw r$(q,U)}return j6($,{header:f,payload:l,signature:r},(U,_)=>{if(U)return D(r$(q,m.wrap(U,m.codes.keyFetchingError,"Cannot fetch key.")));if(typeof _==="string")_=Buffer.from(_,"utf-8");else if(!(_ instanceof Buffer))return D(r$(q,new m(m.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a public key.")));try{let A=HW(_);if(W.allowedAlgorithms.length)QW(J,A);else W.allowedAlgorithms=A;_=zW(_,A[0]===WW[0]),GW(_,v,W)}catch(A){return D(r$(q,A))}D(null,r$(q,Z?{header:f,payload:l,signature:r,input:N}:l))}),h}UW.exports=function(J){let{key:Z,algorithms:X,complete:Y,cache:G,cacheTTL:H,errorCacheTTL:z,checkTyp:V,clockTimestamp:O,clockTolerance:F,ignoreExpiration:I,ignoreNotBefore:B,maxAge:L,allowedJti:C,allowedAud:w,allowedIss:T,allowedSub:N,allowedNonce:E,requiredClaims:D,cacheKeyBuilder:h}={cacheTTL:600000,clockTolerance:0,errorCacheTTL:-1,cacheKeyBuilder:L6,...J};if(!Array.isArray(X))X=[];let v=typeof Z;if(v!=="string"&&v!=="object"&&v!=="function")throw new m(m.codes.INVALID_OPTION,"The key option must be a string, a buffer or a function returning the algorithm secret or public key.");if(Z&&v!=="function"){let q=HW(Z);if(X.length)QW(X,q);else X=q;Z=zW(Z,q[0]===WW[0])}if(O&&(typeof O!=="number"||O<0))throw new m(m.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(F&&(typeof F!=="number"||F<0))throw new m(m.codes.invalidOption,"The clockTolerance option must be a positive number.");if(H&&(typeof H!=="number"||H<0))throw new m(m.codes.invalidOption,"The cacheTTL option must be a positive number.");if(z&&typeof z!=="function"&&typeof z!=="number"||z<-1)throw new m(m.codes.invalidOption,"The errorCacheTTL option must be a number greater than -1 or a function.");if(D&&!Array.isArray(D))throw new m(m.codes.invalidOption,"The requiredClaims option must be an array.");let f=[];if(!B)f.push({type:"date",claim:"nbf",errorCode:"inactive",errorVerb:"will be active",greater:!0,modifier:-F});if(!I)f.push({type:"date",claim:"exp",errorCode:"expired",errorVerb:"has expired",modifier:+F});if(typeof L==="number")f.push({type:"date",claim:"iat",errorCode:"expired",errorVerb:"has expired",modifier:L});if(C)f.push({type:"string",claim:"jti",allowed:zJ(C)});if(w)f.push({type:"string",claim:"aud",allowed:zJ(w),array:!0});if(T)f.push({type:"string",claim:"iss",allowed:zJ(T)});if(N)f.push({type:"string",claim:"sub",allowed:zJ(N)});if(E)f.push({type:"string",claim:"nonce",allowed:zJ(E)});let l=V?V.toLowerCase().replace(/^application\//,""):null,r={key:Z,allowedAlgorithms:X,complete:Y,cacheTTL:H,errorCacheTTL:z,checkTyp:l,clockTimestamp:O,clockTolerance:F,ignoreExpiration:I,ignoreNotBefore:B,maxAge:L,isAsync:v==="function",validators:f,decode:P6({complete:!0}),cache:C6(G),requiredClaims:D,cacheKeyBuilder:h},u0=D6.bind(null,r);return u0.cache=r.cache,u0}});var OW=s((f6)=>{var k6=/^(-?(?:\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?)?)?$/,iJ=1000,tJ=iJ*60,aJ=tJ*60,VJ=aJ*24,EX=VJ*365.25;function y6($){var J,Z=$.toLowerCase().match(k6);if(Z!=null&&(J=parseFloat(Z[1]))){if(Z[3]!=null)return J*iJ;if(Z[4]!=null)return J*tJ;if(Z[5]!=null)return J*aJ;if(Z[6]!=null)return J*VJ;if(Z[7]!=null)return J*VJ*7;if(Z[8]!=null)return J*EX;return J}}function UJ($,J,Z,X){var Y=($|0)===$?$:~~($+0.5);return J+Y+(X?" "+Z+(Y!=1?"s":""):Z[0])}function x6($,J){var Z=$<0?"-":"",X=$<0?-$:$;if(X<iJ)return $+(J?" ms":"ms");if(X<tJ)return UJ(X/iJ,Z,"second",J);if(X<aJ)return UJ(X/tJ,Z,"minute",J);if(X<VJ)return UJ(X/aJ,Z,"hour",J);if(X<EX)return UJ(X/VJ,Z,"day",J);return UJ(X/EX,Z,"year",J)}f6.format=x6;f6.parse=y6});var qW=s((xU,IW)=>{var{base64UrlMatcher:wX,base64UrlReplacer:TX,hsAlgorithms:b6,esAlgorithms:c6,rsaAlgorithms:p6,edAlgorithms:u6,detectPrivateKeyAlgorithm:KW,createSignature:_W}=SX(),{TokenError:d}=c$(),{getAsyncKey:m6,ensurePromiseCallback:d6}=CX(),{createPrivateKey:n6,createSecretKey:s6}=A$("crypto"),{parse:AW}=OW(),FW=new Set([...b6,...c6,...p6,...u6,"none"]),o6=Array.from(FW).join(", ");function MW($,J){let Z=$.slice(0,2),X=J.slice(0,2),Y=!0;if(Z==="RS"||Z==="PS")Y=X==="RS"||Z==="RS"&&J==="ENCRYPTED";else if(Z==="ES"||Z==="Ed")Y=Z===X||Z==="ES"&&J==="ENCRYPTED";if(!Y)throw new d(d.codes.invalidKey,`Invalid private key provided for algorithm ${$}.`)}function RW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J[0]==="H"?s6($):n6($)}function l6({key:$,algorithm:J,noTimestamp:Z,mutatePayload:X,clockTimestamp:Y,expiresIn:G,notBefore:H,kid:z,typ:V,isAsync:O,additionalHeader:F,fixedPayload:I},B,L){let[C,w]=O?d6(L):[];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 T={alg:J,typ:V||"JWT",kid:z,...F},N="",E=B.iat*1000||Y||Date.now(),D={...B,...I,iat:Z?void 0:Math.floor(E/1000),exp:B.exp?B.exp:G?Math.floor((E+G)/1000):void 0,nbf:B.nbf?B.nbf:H?Math.floor((E+H)/1000):void 0};if(X)Object.assign(B,D);if(N=Buffer.from(JSON.stringify(D),"utf-8").toString("base64").replace(wX,TX),!C){let v=Buffer.from(JSON.stringify(T),"utf-8").toString("base64").replace(wX,TX)+"."+N,f=J==="none"?"":_W(J,$,v);return v+"."+f}return m6($,{header:T,payload:B},(h,v)=>{if(h){let l=d.wrap(h,d.codes.keyFetchingError,"Cannot fetch key.");return C(l)}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 f;try{let l=KW(v,J);if(J)MW(J,l);else T.alg=J=l;v=RW(v,J);let u0=Buffer.from(JSON.stringify(T),"utf-8").toString("base64").replace(wX,TX)+"."+N;f=u0+"."+_W(J,v,u0)}catch(l){return C(l)}C(null,f)}),w}IW.exports=function(J){let{key:Z,algorithm:X,noTimestamp:Y,mutatePayload:G,clockTimestamp:H,expiresIn:z,notBefore:V,jti:O,aud:F,iss:I,sub:B,nonce:L,kid:C,typ:w,header:T}={clockTimestamp:0,...J};if(X&&!FW.has(X))throw new d(d.codes.invalidOption,`The algorithm option must be one of the following values: ${o6}.`);let N=typeof Z,E=N==="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||N!=="string"&&!(Z instanceof Buffer)&&N!=="function"&&!E)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(E&&!X)throw new d(d.codes.invalidAlgorithm,"When using password protected key you must provide the algorithm option.");if(Z&&N!=="function"){let v=KW(E?Z.key:Z,X);if(X)MW(X,v);else X=v;Z=RW(Z,X)}if(z){if(typeof z==="string")z=AW(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=AW(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(F&&typeof F!=="string"&&!Array.isArray(F))throw new d(d.codes.invalidOption,"The aud option must be a string or an array of strings.");if(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(L&&typeof L!=="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(T&&typeof T!=="object")throw new d(d.codes.invalidOption,"The header option must be a object.");let h=Object.entries({jti:O,aud:F,iss:I,sub:B,nonce:L}).reduce((v,[f,l])=>{if(l!==void 0)v[f]=l;return v},{});return l6.bind(null,{key:Z,algorithm:X,noTimestamp:Y,mutatePayload:G,clockTimestamp:H,expiresIn:z,notBefore:V,kid:C,typ:w,isAsync:N==="function",additionalHeader:T,fixedPayload:h})}});var jW=s((fU,PW)=>{var{TokenError:r6,TOKEN_ERROR_CODES:i6}=c$(),t6=$X(),a6=VW(),e6=qW();PW.exports={TokenError:r6,TOKEN_ERROR_CODES:i6,createDecoder:t6,createVerifier:a6,createSigner:e6}});var{Glob:gW}=globalThis.Bun;var iX=new Map;function hW($){if(typeof $>"u")return[];if(!Array.isArray($))throw Error("disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A\u5FC5\u987B\u662F string[]");let J=[];for(let Z of $){if(typeof Z!=="string")throw Error("disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A\u6570\u7EC4\u5143\u7D20\u5FC5\u987B\u662F string");let X=Z.trim();if(!X)throw Error("disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A\u4E0D\u5141\u8BB8\u7A7A\u5B57\u7B26\u4E32");J.push(X)}return J}function bW($){let J=iX.get($);if(J)return J;let Z=new gW($);return iX.set($,Z),Z}function N$($){let J=hW($);if(J.length===0)return[];let Z=[];for(let X of J)try{let Y=bW(X);Z.push({type:"glob",raw:X,glob:Y})}catch(Y){throw Error(`disableMenus \u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1Aglob \u89C4\u5219 ${X} \u89E3\u6790\u5931\u8D25\uFF1A${Y?.message||String(Y)}`)}return Z}function i$($,J){for(let Z of J)if(Z.glob.match($))return!0;return!1}import{existsSync as mW}from"fs";import{isAbsolute as dW,join as Z1}from"path";import{pathToFileURL as nW}from"url";m0();function F$($){if(Array.isArray($)){let J=[];for(let Z of $)J.push(F$(Z));return J}if(o($)){let J={};for(let Z of Object.keys($))J[Z]=F$($[Z]);return J}return $}function J1($,J){if(J===void 0)return $;if(Array.isArray($)&&Array.isArray(J)){for(let Z of J)$.push(F$(Z));return $}if(o($)&&o(J)){for(let Z of Object.keys(J)){let X=J[Z];if(X===void 0)continue;let Y=$[Z];if(Array.isArray(Y)&&Array.isArray(X)){let G=[];for(let H of Y)G.push(F$(H));for(let H of X)G.push(F$(H));$[Z]=G;continue}if(o(Y)&&o(X)){$[Z]=J1(F$(Y),X);continue}$[Z]=F$(X)}return $}return F$(J)}function jZ(...$){let J={};for(let Z of $){if(Z===void 0)continue;J=J1(J,Z)}return J}m0();async function X1($){let{cwd:J=process.cwd(),dirs:Z,files:X,extensions:Y=[".ts",".js",".json"],mode:G="first",paths:H,defaults:z={}}=$;if(!Array.isArray(Z)||Z.length===0)throw Error("dirs \u5FC5\u987B\u662F\u975E\u7A7A\u6570\u7EC4");if(!Array.isArray(X)||X.length===0)throw Error("files \u5FC5\u987B\u662F\u975E\u7A7A\u6570\u7EC4");let V=[];for(let F of Z){let I=dW(F)?F:Z1(J,F);for(let B of X)for(let L of Y){let C=B.endsWith(L)?B:B+L,w=Z1(I,C);if(mW(w))try{let T=nW(w).href+`?t=${Date.now()}`,N;if(L===".json")N=(await import(T,{with:{type:"json"}})).default;else{let E=await import(T);if(N=E.default||E,N instanceof Promise)N=await N}if(!o(N))continue;if(V.push(N),G==="first"){let E=jZ(z,N);if(H&&H.length>0){let D={};for(let h of H){let v=qZ(E,h);if(v!==void 0)PZ(D,h,v)}return D}return E}break}catch{}}}let O=jZ(z,...V);if(H&&H.length>0){let F={};for(let I of H){let B=qZ(O,I);if(B!==void 0)PZ(F,I,B)}return F}return O}var sW={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:{}},BZ=new Map;async function Y1(){let X=BZ.get("development");if(X)return await X;let Y=(async()=>{let G=await X1({dirs:["configs"],files:["befly.common","befly.development"],extensions:[".json"],mode:"merge",defaults:sW}),H=G?.redis?.prefix;if(typeof H==="string"){if(H.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=${H}`)}return N$(G?.disableMenus),G})();BZ.set("development",Y);try{return await Y}catch(G){throw BZ.delete("development"),G}}a();m0();async function F1($){let J=!1;for(let Z of $)try{if(typeof Z?.name!=="string"||Z.name.trim()===""){P.warn(Object.assign({},b(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"){P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}if(typeof Z?.routePath!=="string"||Z.routePath.trim()==="")P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 routePath \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;else{let X=Z.routePath.trim();if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(X))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 routePath \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09"})),J=!0;if(!X.startsWith("/api/"))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 routePath \u5FC5\u987B\u4EE5 /api/ \u5F00\u5934"})),J=!0;if(X.includes(" "))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 routePath \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C"})),J=!0;if(X.includes("/api//"))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 routePath \u4E0D\u5141\u8BB8\u51FA\u73B0 /api//\uFF08\u91CD\u590D\u659C\u6760\uFF09"})),J=!0}if(typeof Z?.routePrefix!=="string"||Z.routePrefix.trim()==="")P.warn(Object.assign({},b(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()))P.warn(Object.assign({},b(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")P.warn(Object.assign({},b(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&&!o(Z.fields))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 fields \u5C5E\u6027\u5FC5\u987B\u662F\u5BF9\u8C61"})),J=!0;if(Z.required&&!Array.isArray(Z.required))P.warn(Object.assign({},b(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"))P.warn(Object.assign({},b(Z,["handler"]),{msg:"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0}catch(X){P.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();m0();var M1=["name","enable","deps","handler"];async function R1($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let X of $)try{if(!o(X)){P.warn(Object.assign({},b(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()===""){P.warn(Object.assign({},b(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 Y=X.customKeys;if(!Array.isArray(Y)){P.warn(Object.assign({},b(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(Y.some((V)=>typeof V!=="string")){P.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let G=Y.filter((V)=>!M1.includes(V));if(G.length>0){P.warn(Object.assign({},b(X,["handler"]),{msg:`\u94A9\u5B50\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${G.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${M1.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${Y.join(", ")}`})),J=!0;continue}let H=Y.includes("enable"),z=Y.includes("deps");if(H){if(typeof X.enable!=="boolean"){P.warn(Object.assign({},b(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===""){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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){P.warn(Object.assign({},b(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}`)){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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")){P.warn(Object.assign({},b(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"){P.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(Y){P.error({err:Y,item:X,msg:"\u94A9\u5B50\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u94A9\u5B50\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();gZ();function CH($){if(!$)return{ok:!1,reason:"path \u4E0D\u80FD\u4E3A\u7A7A"};if(!$.startsWith("/"))return{ok:!1,reason:"path \u5FC5\u987B\u4EE5 / \u5F00\u5934"};if($.length>1&&$.endsWith("/"))return{ok:!1,reason:"path \u672B\u5C3E\u4E0D\u80FD\u662F /\uFF08\u6839\u8DEF\u5F84 / \u9664\u5916\uFF09"};if($.includes("//"))return{ok:!1,reason:"path \u4E0D\u80FD\u5305\u542B //"};if($.includes(".."))return{ok:!1,reason:"path \u4E0D\u80FD\u5305\u542B .."};return{ok:!0,reason:""}}function w1($,J){if(J.length===0)return $;let Z=[];for(let X of $){let Y=typeof X?.path==="string"?String(X.path).trim():"";if(Y&&i$(Y,J))continue;let G=Array.isArray(X?.children)?X.children:null;if(G&&G.length>0){let H=w1(G,J);if(H.length>0)X.children=H;else delete X.children}Z.push(X)}return Z}var T1=async($,J={})=>{let Z=!1,X=await E1($),Y=N$(J.disableMenus),G=w1(X,Y),H=[];for(let V of G)H.push({menu:V,depth:1});let z=new Set;while(H.length>0){let V=H.pop(),O=V?.menu,F=typeof V?.depth==="number"?V.depth:0;if(O===null||typeof O!=="object"){Z=!0,P.warn({menu:O,msg:"\u83DC\u5355\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61"});continue}if(F>3){Z=!0,P.warn({path:O?.path,depth:F,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});continue}let I=O.children;if(typeof I<"u"&&!Array.isArray(I)){Z=!0,P.warn({path:O?.path,childrenType:typeof I,msg:"\u83DC\u5355 children \u5FC5\u987B\u662F\u6570\u7EC4"});continue}if(Array.isArray(I)&&I.length>0)if(F>=3)Z=!0,P.warn({path:O?.path,depth:F,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});else for(let T of I)H.push({menu:T,depth:F+1});let B=typeof O.path==="string"?O.path.trim():"",L=typeof O.name==="string"?O.name.trim():"",C=typeof O.sort==="number"?O.sort:999999;if(typeof O.path==="string")O.path=B;if(typeof O.name==="string")O.name=L;if(typeof O.sort>"u")O.sort=C;if(!B){Z=!0,P.warn({menu:O,msg:"\u83DC\u5355\u7F3A\u5C11 path\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});continue}let w=CH(B);if(!w.ok)Z=!0,P.warn({path:B,reason:w.reason,msg:"\u83DC\u5355 path \u4E0D\u5408\u6CD5"});if(!L)Z=!0,P.warn({path:B,menu:O,msg:"\u83DC\u5355\u7F3A\u5C11 name\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});if(typeof O.sort<"u"&&typeof O.sort!=="number")Z=!0,P.warn({path:B,sort:O.sort,msg:"\u83DC\u5355 sort \u5FC5\u987B\u662F number"});if(typeof O.sort==="number"&&(!Number.isFinite(O.sort)||O.sort<1))Z=!0,P.warn({path:B,sort:O.sort,msg:"\u83DC\u5355 sort \u6700\u5C0F\u503C\u4E3A 1"});if(z.has(B)){Z=!0,P.warn({path:B,msg:"\u83DC\u5355 path \u91CD\u590D\uFF08\u4E25\u683C\u6A21\u5F0F\u7981\u6B62\u91CD\u590D path\uFF09"});continue}z.add(B)}if(Z)throw Error("\u83DC\u5355\u7ED3\u6784\u68C0\u67E5\u5931\u8D25");return G};a();m0();var v1=["name","enable","deps","handler"];async function N1($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let X of $)try{if(!o(X)){P.warn(Object.assign({},b(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()===""){P.warn(Object.assign({},b(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 Y=X.customKeys;if(!Array.isArray(Y)){P.warn(Object.assign({},b(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(Y.some((V)=>typeof V!=="string")){P.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let G=Y.filter((V)=>!v1.includes(V));if(G.length>0){P.warn(Object.assign({},b(X,["handler"]),{msg:`\u63D2\u4EF6\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${G.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${v1.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${Y.join(", ")}`})),J=!0;continue}let H=Y.includes("enable"),z=Y.includes("deps");if(H){if(typeof X.enable!=="boolean"){P.warn(Object.assign({},b(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===""){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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){P.warn(Object.assign({},b(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}`)){P.warn(Object.assign({},b(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)){P.warn(Object.assign({},b(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")){P.warn(Object.assign({},b(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"){P.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(Y){P.error({err:Y,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 D1=["id","created_at","updated_at","deleted_at","state"],k1=["string","number","text","array_string","array_text","array_number_string","array_number_text"],y1=["name","type","min","max","default","detail","index","unique","nullable","unsigned","regexp"],EH=/^_?[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)*$/,wH=/^[\u4e00-\u9fa5a-zA-Z0-9 _-]+$/,x1=65535;async function f1($){let J=!1;for(let Z of $){if(Z.type!=="table")continue;let X=typeof Z.sourceName==="string"?Z.sourceName:"",Y=X?`${X}\u8868 `:"\u8868 ";try{let G=Z.fileName,H=Z.content||{};if(!EH.test(G)){P.warn(`${Y}${G} \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)){P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u89C4\u5219\u5FC5\u987B\u4E3A\u5BF9\u8C61`),J=!0;continue}if(D1.includes(z))P.warn(`${Y}${G} \u6587\u4EF6\u5305\u542B\u4FDD\u7559\u5B57\u6BB5 ${z}\uFF0C`+`\u4E0D\u80FD\u5728\u8868\u5B9A\u4E49\u4E2D\u4F7F\u7528\u4EE5\u4E0B\u5B57\u6BB5: ${D1.join(", ")}`),J=!0;let O=V,I=Object.keys(O).filter((N)=>!y1.includes(N));if(I.length>0)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u5305\u542B\u975E\u6CD5\u5C5E\u6027: ${I.join(", ")}\uFF0C`+`\u5141\u8BB8\u7684\u5C5E\u6027\u4E3A: ${y1.join(", ")}`),J=!0;if(!O.name||typeof O.name!=="string"){P.warn(`${Y}${G} \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"){P.warn(`${Y}${G} \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"))P.warn(`${Y}${G} \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"))P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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")P.warn(`${Y}${G} \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:L,min:C,max:w,default:T}=O;if(!wH.test(B))P.warn(`${Y}${G} \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(!k1.includes(L))P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u5B57\u6BB5\u7C7B\u578B "${L}" \u683C\u5F0F\u9519\u8BEF\uFF0C`+`\u5FC5\u987B\u4E3A${k1.join("\u3001")}\u4E4B\u4E00`),J=!0;if(L!=="number"&&O.unsigned!==void 0)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u5B57\u6BB5\u7C7B\u578B\u4E3A ${L}\uFF0C\u4E0D\u5141\u8BB8\u8BBE\u7F6E unsigned\uFF08\u4EC5 number \u7C7B\u578B\u6709\u6548\uFF09`),J=!0;if(O.unique===!0&&O.index===!0)P.warn(`${Y}${G} \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&&w!==void 0&&C!==null&&w!==null){if(C>w)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u6700\u5C0F\u503C "${C}" \u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u503C "${w}"`),J=!0}if(L==="text"||L==="array_text"||L==="array_number_text"){if(C!==void 0&&C!==null)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u7684 ${L} \u7C7B\u578B\u6700\u5C0F\u503C\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${C}"`),J=!0;if(w!==void 0&&w!==null)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u7684 ${L} \u7C7B\u578B\u6700\u5927\u957F\u5EA6\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${w}"`),J=!0;if(T!==void 0&&T!==null)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u4E3A ${L} \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0;if(O.index===!0)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u4E3A ${L} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u521B\u5EFA\u7D22\u5F15\uFF08index=true \u65E0\u6548\uFF09`),J=!0;if(O.unique===!0)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u4E3A ${L} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u552F\u4E00\u7EA6\u675F\uFF08unique=true \u65E0\u6548\uFF09`),J=!0}else if(L==="string"||L==="array_string"||L==="array_number_string"){if(w!==void 0&&(w===null||typeof w!=="number"))P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u4E3A ${L} \u7C7B\u578B\uFF0C`+`\u6700\u5927\u957F\u5EA6\u5FC5\u987B\u4E3A\u6570\u5B57\uFF0C\u5F53\u524D\u4E3A "${w}"`),J=!0;else if(w!==void 0&&w>x1)P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u6700\u5927\u957F\u5EA6 ${w} \u8D8A\u754C\uFF0C`+`${L} \u7C7B\u578B\u957F\u5EA6\u5FC5\u987B\u5728 1..${x1} \u8303\u56F4\u5185`),J=!0}else if(L==="number"){if(T!==void 0&&T!==null&&typeof T!=="number")P.warn(`${Y}${G} \u6587\u4EF6 ${z} \u4E3A number \u7C7B\u578B\uFF0C`+`\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A\u6570\u5B57\u6216 null\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0}}}catch(G){P.error({msg:`${Y}${Z.fileName} \u89E3\u6790\u5931\u8D25`,err:G}),J=!0}}if(J)throw Error("\u8868\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var{SQL:g1,RedisClient:TH}=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",X=J.host||"127.0.0.1",Y=J.port||3306,G=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}://${G}:${H}@${X}:${Y}/${z}`}let O;if(Z==="sqlite")O=new g1(V);else O=new g1({url:V,max:J.poolMax??1,bigint:!1});try{let I=(async()=>{let L="";if(Z==="sqlite")L=(await O`SELECT sqlite_version() AS version`)?.[0]?.version;else if(Z==="postgresql"||Z==="postgres")L=(await O`SELECT version() AS version`)?.[0]?.version;else L=(await O`SELECT VERSION() AS version`)?.[0]?.version;return L})(),B=new Promise((L,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(F){P.error({err:F,msg:"[Connect] SQL \u8FDE\u63A5\u5931\u8D25"});try{await O?.close()}catch{}throw F}}static async disconnectSql(){if(this.sqlClient){try{await this.sqlClient.close()}catch($){P.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,Y=J.username||"",G=J.password||"",H=J.db||0,z="";if(Y&&G)z=`${Y}:${G}@`;else if(G)z=`:${G}@`;let V=`redis://${z}${Z}:${X}/${H}`,O=new TH(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 P.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($){P.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 P.error({env:$.nodeEnv,err:J,msg:"\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25"}),await this.disconnect(),J}}static async disconnect(){await this.disconnectSql(),await this.disconnectRedis()}static isConnected(){return{sql:this.sqlClient!==null,redis:this.redisClient!==null}}static getStatus(){let $=Date.now();return{sql:{connected:this.sqlClient!==null,connectedAt:this.sqlConnectedAt,uptime:this.sqlConnectedAt?$-this.sqlConnectedAt:null,poolMax:this.sqlPoolMax},redis:{connected:this.redisClient!==null,connectedAt:this.redisConnectedAt,uptime:this.redisConnectedAt?$-this.redisConnectedAt:null}}}static __setMockSql($){this.sqlClient=$}static __setMockRedis($){this.redisClient=$}static __reset(){this.sqlClient=null,this.redisClient=null,this.sqlConnectedAt=null,this.redisConnectedAt=null,this.sqlPoolMax=1}}a();a();var PJ={"@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 h1($,J,Z){if(!$||typeof $!=="object")return $;let X={};for(let[Y,G]of Object.entries($)){if(typeof G==="string"&&G.startsWith("@")){if(PJ[G]){X[Y]=PJ[G];continue}let H=Object.keys(PJ).join(", ");throw Error(`API [${J}] (${Z}) \u5B57\u6BB5 [${Y}] \u5F15\u7528\u4E86\u672A\u5B9A\u4E49\u7684\u9884\u8BBE\u5B57\u6BB5 "${G}"\u3002\u53EF\u7528\u7684\u9884\u8BBE\u5B57\u6BB5\u6709: ${H}`)}X[Y]=G}return X}async function b1($){let J=new Map;for(let Z of $){let X=Z.type;if(X&&X!=="api")continue;try{let Y=Z;Y.fields=h1(Y.fields||{},Y.name,Y.routePath),J.set(Y.routePath,Y)}catch(Y){throw P.error({err:Y,api:Z.relativePath,file:Z.filePath,msg:"\u63A5\u53E3\u52A0\u8F7D\u5931\u8D25"}),Y}}return J}a();m0();function jJ($,J={}){let Z=J.moduleLabel||"\u6A21\u5757",X=J.getName||((I)=>{let B=I.moduleName;if(typeof B==="string"&&B.trim()!=="")return B;return K$(I.fileName)}),Y=J.getDeps||((I)=>I.deps),G=[],H=new Set,z=new Set,V={},O=!0;for(let I of $){let B=X(I);if(typeof B!=="string"||B.trim()===""){P.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]){P.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),L=Y(I);if(!Array.isArray(L)){P.error({module:B,item:I,msg:`${Z} \u7684 deps \u5FC5\u987B\u662F\u6570\u7EC4`}),O=!1;continue}for(let C of L){if(typeof C!=="string"){P.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])P.error({module:B,dependency:C,msg:`${Z} \u4F9D\u8D56\u672A\u627E\u5230`}),O=!1}}if(!O)return!1;let F=(I)=>{if(H.has(I))return;if(z.has(I)){P.error({module:I,msg:`${Z} \u5FAA\u73AF\u4F9D\u8D56`}),O=!1;return}let B=V[I];if(!B)return;let L=Y(B);z.add(I);for(let C of L)F(C);z.delete(I),H.add(I),G.push(B)};for(let I of $){let B=X(I);F(B)}return O?G:!1}async function c1($){let J=[],Z=$.filter((Y)=>{let G=Y?.moduleName;if(typeof G!=="string"||G.trim()==="")return!1;if(Y?.enable===!1)return!1;return!0}),X=jJ(Z,{moduleLabel:"\u94A9\u5B50"});if(X===!1)throw Error("\u94A9\u5B50\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let Y of X){let G=Y.moduleName,H=Y;J.push({name:G,enable:!0,deps:H.deps,handler:H.handler})}return J}a();async function p1($,J){let Z=[],X=$.filter((G)=>{let H=G?.moduleName;if(typeof H!=="string"||H.trim()==="")return!1;if(G?.enable===!1)return!1;return!0}),Y=jJ(X,{moduleLabel:"\u63D2\u4EF6"});if(Y===!1)throw Error("\u63D2\u4EF6\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let G of Y){let H=G.moduleName,z=G;try{let V=typeof z.handler==="function"?await z.handler(J):{};J[H]=V,Z.push({name:H,enable:!0,deps:z.deps,handler:z.handler})}catch(V){throw P.error({err:V,plugin:H,msg:"\u63D2\u4EF6\u521D\u59CB\u5316\u5931\u8D25"}),V}}return Z}KJ();a();function u1($,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 Y=$.headers.get("cf-connecting-ip");if(typeof Y==="string"&&Y.trim())return Y.trim();let G=$.headers.get("x-client-ip");if(typeof G==="string"&&G.trim())return G.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 q$($,J,Z=1,X=null,Y=null,G=null){if($.requestId)P.info({event:"request_blocked",reason:J,reasonCode:G,code:Z,detail:Y,msg:"request blocked"});return Response.json({code:Z,msg:J,data:X,detail:Y},{headers:$.corsHeaders})}function hZ($){if($.api&&$.requestId)P.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,Y)=>typeof Y==="bigint"?Y.toString():Y);return new Response(Z,{headers:{...$.corsHeaders,"Content-Type":"application/json"}})}else return Response.json(J,{headers:$.corsHeaders})}return Response.json({code:1,msg:"\u672A\u751F\u6210\u54CD\u5E94"},{headers:$.corsHeaders})}m0();function m1($,J,Z){return async(X,Y)=>{let G=$1(),z=new URL(X.url).pathname||"/",V=u1(X,Y),O=Date.now(),F={method:X.method,body:{},user:{},req:X,now:O,ip:V,headers:X.headers,route:z,requestId:G,corsHeaders:{"X-Request-ID":G},api:$.get(z),response:void 0,result:void 0};return H1({requestId:G,method:X.method,route:z,ip:V,now:O},async()=>{try{for(let I of J)if(await I.handler(Z,F),F.response)return F.response;if(F.api&&X.method!=="OPTIONS"){let I={event:"request",apiName:F.api.name};if(F.body&&Object.keys(F.body).length>0)I.body=F.body;I.msg="request",P.info(I)}if(!F.api){if(X.method!=="OPTIONS")F.response=Response.json({code:1,msg:"\u63A5\u53E3\u4E0D\u5B58\u5728"},{headers:F.corsHeaders})}else if(F.api.handler){let I=await F.api.handler(Z,F);if(I instanceof Response)F.response=I;else F.result=I}return hZ(F)}catch(I){let B=F.api?z:X.url;return P.error({err:I,path:B,msg:"\u8BF7\u6C42\u9519\u8BEF"}),F.result={code:1,msg:"\u5185\u90E8\u670D\u52A1\u9519\u8BEF"},hZ(F)}})}}I$();a();I$();import{fileURLToPath as vH}from"url";var NH=vH(import.meta.url),P$=IJ(NH);var n8=L$(P$).endsWith("/dist")?P$:n(P$,"dist"),s8=n(P$,"checks"),o8=n(P$,"plugins"),l8=n(P$,"hooks"),r8=n(P$,"apis"),i8=n(P$,"tables"),n0=process.cwd(),t8=n(n0,"checks"),a8=n(n0,"plugins"),e8=n(n0,"hooks"),$4=n(n0,"apis"),J4=n(n0,"tables"),d1=n(n0,"addons");function BJ($,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 n1($=void 0){return async(J)=>{let Z=BJ(J,$),X=new URL(J.url),Y=n(n0,"public",X.pathname);try{if(J.method==="OPTIONS")return new Response(null,{status:204,headers:Z});let G=Bun.file(Y);if(await G.exists())return new Response(G,{headers:{"Content-Type":G.type||"application/octet-stream",...Z}});else return Response.json({code:1,msg:"\u6587\u4EF6\u672A\u627E\u5230"},{headers:Z})}catch(G){return P.error({err:G,msg:"\u9759\u6001\u6587\u4EF6\u5904\u7406\u5931\u8D25"}),Response.json({code:1,msg:"\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25"},{headers:Z})}}}a();m0();async function s1($,J){if(!$.db)throw Error("syncApi: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncApi: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_api")).data){P.debug(`${"addon_admin_api"} \u8868\u4E0D\u5B58\u5728`);return}let Y=(await $.db.getAll({table:"addon_admin_api",fields:["id","routePath","name","addonName","state"],where:{state$gte:0}})).data.lists||[],G=eX(Y,(F)=>F.routePath),H=[],z=[],V=[],O=new Set;for(let F of J){let I=F.type;if(I&&I!=="api")continue;let B=F.routePath;O.add(F.routePath);let L=G[B];if(L){if(F.name!==L.name||F.routePath!==L.routePath||F.addonName!==L.addonName)z.push({id:L.id,api:F})}else H.push(F)}for(let F of Y)if(!O.has(F.routePath))V.push(F.id);if(z.length>0)try{await $.db.updBatch("addon_admin_api",z.map((F)=>{return{id:F.id,data:{name:F.api.name,routePath:F.api.routePath,addonName:F.api.addonName}}}))}catch(F){P.error({err:F,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u66F4\u65B0\u5931\u8D25"})}if(H.length>0)try{await $.db.insBatch("addon_admin_api",H.map((F)=>{return{name:F.name,routePath:F.routePath,addonName:F.addonName}}))}catch(F){P.error({err:F,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u65B0\u589E\u5931\u8D25"})}if(V.length>0)try{await $.db.delForceBatch("addon_admin_api",V)}catch(F){P.error({err:F,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u5220\u9664\u5931\u8D25"})}}async function o1($){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 DH}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=DH("RSA-SHA256");return X.update($),X.sign(J,Z)}static hmacSha256($,J,Z="hex"){let X=new Bun.CryptoHasher("sha256",$);return X.update(J),X.digest(Z)}static sha512($,J="hex"){let Z=new Bun.CryptoHasher("sha512");return Z.update($),Z.digest(J)}static hmacSha512($,J,Z="hex"){let X=new Bun.CryptoHasher("sha512",$);return X.update(J),X.digest(Z)}static hash($,J,Z="hex"){let X=new Bun.CryptoHasher($);return X.update(J),X.digest(Z)}static hmac($,J,Z,X="hex"){let Y=new Bun.CryptoHasher($,J);return Y.update(Z),Y.digest(X)}static async hashFile($,J="sha256",Z="hex"){let X=Bun.file($),Y=new Bun.CryptoHasher(J),H=X.stream().getReader();try{while(!0){let{done:z,value:V}=await H.read();if(z)break;Y.update(V)}return Y.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 Y=0;Y<Z.length;Y++)X+=Z[Y].toString(16).padStart(2,"0");return X.slice(0,$)}static fastHash($,J=0){let Z=Bun.hash($,J);return typeof Z==="bigint"?Number(Z):Z}}a();async function l1($,J={}){if(!J.devPassword)return;let Z=typeof J.devEmail==="string"&&J.devEmail.length>0?J.devEmail:"dev@qq.com";if(!$.db)throw Error("syncDev: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncDev: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_admin")).data){P.debug("addon_admin_admin \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_role")).data){P.debug("addon_admin_role \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_menu")).data){P.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}let X=await $.db.getAll({table:"addon_admin_menu",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),Y=Array.from(new Set((X.data.lists||[]).map((L)=>typeof L?.path==="string"?L.path.trim():"").filter((L)=>L.length>0))),G=await $.db.tableExists("addon_admin_api"),H=[];if(G.data){let L=await $.db.getAll({table:"addon_admin_api",fields:["routePath"],where:{state$gte:0},orderBy:["id#ASC"]});H=Array.from(new Set((L.data.lists||[]).map((C)=>{if(typeof C?.routePath!=="string")throw Error("syncDev: addon_admin_api.routePath \u5FC5\u987B\u662F\u5B57\u7B26\u4E32");let w=C.routePath.trim();if(w.length===0)throw Error("syncDev: addon_admin_api.routePath \u4E0D\u5141\u8BB8\u4E3A\u7A7A\u5B57\u7B26\u4E32");if(!w.startsWith("/"))throw Error(`syncDev: addon_admin_api.routePath \u5FC5\u987B\u662F pathname\uFF08\u4EE5 / \u5F00\u5934\uFF09\uFF0C\u5F53\u524D\u503C=${w}`);return w})))}let z=[{code:"dev",name:"\u5F00\u53D1\u8005\u89D2\u8272",description:"\u62E5\u6709\u6240\u6709\u83DC\u5355\u548C\u63A5\u53E3\u6743\u9650\u7684\u5F00\u53D1\u8005\u89D2\u8272",menus:Y,apis:H,sort:0},{code:"user",name:"\u7528\u6237\u89D2\u8272",description:"\u666E\u901A\u7528\u6237\u89D2\u8272",menus:[],apis:[],sort:1},{code:"admin",name:"\u7BA1\u7406\u5458\u89D2\u8272",description:"\u7BA1\u7406\u5458\u89D2\u8272",menus:[],apis:[],sort:2},{code:"guest",name:"\u8BBF\u5BA2\u89D2\u8272",description:"\u8BBF\u5BA2\u89D2\u8272",menus:[],apis:[],sort:3}],V=null;for(let L of z){let C=await $.db.getOne({table:"addon_admin_role",where:{code:L.code}});if(C.data){let{menus:w,apis:T}=L,N=Array.isArray(C.data.menus)?C.data.menus:[],E=Array.isArray(C.data.apis)?C.data.apis:[],D=N.length!==w.length||N.some((f,l)=>f!==w[l]),h=E.length!==T.length||E.some((f,l)=>f!==T[l]);if(C.data.name!==L.name||C.data.description!==L.description||D||h||C.data.sort!==L.sort)await $.db.updData({table:"addon_admin_role",where:{code:L.code},data:{name:L.name,description:L.description,menus:L.menus,apis:L.apis,sort:L.sort}});if(L.code==="dev")V=C.data}else{let w=await $.db.insData({table:"addon_admin_role",data:L});if(L.code==="dev")V={id:w.data}}}if(!V){P.error("dev \u89D2\u8272\u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u521B\u5EFA\u5F00\u53D1\u8005\u8D26\u53F7");return}let O=y$.sha256(J.devPassword+"befly"),F=await y$.hashPassword(O),I={nickname:"\u5F00\u53D1\u8005",email:Z,username:"dev",password:F,roleCode:"dev",roleType:"admin"};if((await $.db.getOne({table:"addon_admin_admin",where:{email:Z}})).data)await $.db.updData({table:"addon_admin_admin",where:{email:Z},data:I});else await $.db.insData({table:"addon_admin_admin",data:I})}a();gZ();function kH($){let J=new Map,Z=[];for(let X of $)Z.push({menu:X,parentPathFromTree:""});while(Z.length>0){let X=Z.pop(),Y=X?X.menu:null;if(!Y)continue;let G=typeof Y.path==="string"?Y.path:"",H=Y.children;if(H&&Array.isArray(H)&&H.length>0){let I=typeof G==="string"?G:"";for(let B of H)Z.push({menu:B,parentPathFromTree:I})}if(!G)continue;let z=typeof Y.name==="string"?Y.name:"";if(!z)continue;let V=typeof Y.sort==="number"?Y.sort:999999,F=typeof Y.parentPath==="string"?Y.parentPath:typeof X?.parentPathFromTree==="string"?X.parentPathFromTree:C1(G);J.set(G,{path:G,name:z,sort:V,parentPath:F})}return J}async function r1($,J){if(!$.db)throw Error("syncMenu: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncMenu: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.config)throw Error("syncMenu: ctx.config \u672A\u521D\u59CB\u5316\uFF08config \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_menu")).data){P.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}let Z=N$($.config?.disableMenus),X=Z.length===0?J:(()=>{let z=(V)=>{let O=[];for(let F of V){let I=typeof F?.path==="string"?String(F.path).trim():"";if(I&&i$(I,Z))continue;let B=Array.isArray(F?.children)?F.children:null;if(B&&B.length>0){let L=z(B);if(L.length>0)F.children=L;else delete F.children}O.push(F)}return O};return z(J)})(),Y=kH(X),G=new Set;for(let z of Y.keys())G.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||[],F=O.filter((E)=>typeof E?.state==="number"&&E.state>=0),I=new Map,B=new Set,L=new Map;for(let E of F){if(typeof E?.path!=="string"||!E.path)continue;if(typeof E?.id!=="number")continue;let D=I.get(E.path);if(!D){I.set(E.path,E);continue}let h=typeof D?.id==="number"?D.id:0,v=E.id;if(v>h){if(I.set(E.path,E),h>0)B.add(h);let f=L.get(E.path)||{keptId:v,removedIds:[]};if(f.keptId=v,h>0)f.removedIds.push(h);L.set(E.path,f)}else{if(v>0)B.add(v);let f=L.get(E.path)||{keptId:h,removedIds:[]};if(f.keptId=h,v>0)f.removedIds.push(v);L.set(E.path,f)}}if(L.size>0){let E=[];for(let D of L.entries()){let h=D[0],v=D[1];if(E.push({path:h,keptId:v.keptId,removedIds:v.removedIds}),E.length>=10)break}P.warn({table:H,duplicatePaths:L.size,duplicateIds:B.size,examples:E,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=[],w=[];for(let E of Y.values()){let D=I.get(E.path);if(D){let h=typeof D.parentPath==="string"?D.parentPath:"";if(D.name!==E.name||D.sort!==E.sort||h!==E.parentPath)C.push({id:D.id,data:{name:E.name,path:E.path,parentPath:E.parentPath,sort:E.sort}})}else w.push({name:E.name,path:E.path,parentPath:E.parentPath,sort:E.sort})}if(C.length>0)await z.updBatch(H,C);if(w.length>0)await z.insBatch(H,w);let T=new Set;if(Z.length>0)for(let E of O){let D=typeof E?.path==="string"?String(E.path).trim():"";if(!D)continue;if(i$(D,Z)){if(typeof E?.id==="number"&&E.id>0)T.add(E.id)}}for(let E of F){if(typeof E?.path!=="string"||!E.path)continue;if(!G.has(E.path)){if(typeof E?.id==="number")T.add(E.id)}}for(let E of B)if(typeof E==="number"&&E>0)T.add(E);let N=Array.from(T);if(N.length>0)await z.delForceBatch(H,N)})}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 x$=null;function f$($){let J=Error(`\u672A\u77E5\u6570\u636E\u5E93\u65B9\u8A00: ${String($)}`);if($!=="mysql"&&$!=="postgresql"&&$!=="sqlite")throw J;if(!x$)x$=new Map,x$.set("mysql",new SJ),x$.set("postgresql",new i1),x$.set("sqlite",new t1);let Z=x$.get($);if(!Z)throw J;return Z}function LJ($){if($.dialect==="mysql")return{columns:{sql:"SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION",params:[$.dbName,$.table]}};if($.dialect==="postgresql"){let X=$.schema&&$.schema.trim()!==""?$.schema:"public",Y={sql:"SELECT column_name, data_type, character_maximum_length, is_nullable, column_default FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position",params:[X,$.table]},G={sql:"SELECT a.attname AS column_name, col_description(c.oid, a.attnum) AS column_comment FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname = ? AND c.relname = ? AND a.attnum > 0",params:[X,$.table]};return{columns:Y,comments:G}}return{columns:f$("sqlite").getTableColumnsQuery($.table)}}function bZ($){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 SJ{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 i1{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 t1{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();m0();var EJ=async($,J)=>{try{let Z=[];if(!Array.isArray(J))throw Error("syncTable(items) \u53C2\u6570\u5FC5\u987B\u662F\u6570\u7EC4");if(!$)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx");if(!$.db)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.db");if(!$.redis)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.redis");if(!$.config)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.config");let X=String($.config.db?.type||"mysql").toLowerCase(),Y="mysql";if(X==="postgres"||X==="postgresql")Y="postgresql";else if(X==="sqlite")Y="sqlite";await yH(Y,$.db);let G=$.config.db?.database||"",H={dbDialect:Y,db:$.db,dbName:G};for(let z of J){if(!z||z.type!=="table")continue;if(z.source!=="app"&&z.source!=="addon"&&z.source!=="core"){P.warn(`syncTable \u8DF3\u8FC7\u672A\u77E5\u6765\u6E90\u8868\u5B9A\u4E49: source=${String(z.source)} fileName=${String(z.fileName)}`);continue}let V=u(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_${u(z.addonName)}_${V}`}let F=z.content;if(!F||typeof F!=="object")throw Error(`syncTable \u8868\u5B9A\u4E49\u65E0\u6548: table=${O}`);for(let B of Object.values(F))XY(B);if(await QY(H,O))await gH(H,O,F);else await VY(H,O,F);Z.push(O)}if(Z.length>0){let z=Z.map((V)=>X0.tableColumns(V));await $.redis.delBatch(z)}}catch(Z){throw P.error({err:Z,msg:"\u6570\u636E\u5E93\u540C\u6B65\u5931\u8D25"}),Z}},S$={MYSQL_MIN_MAJOR:8,POSTGRES_MIN_MAJOR:17,SQLITE_MIN_VERSION:"3.50.0",SQLITE_MIN_VERSION_NUM:35000},e1={length:"\u957F\u5EA6",datatype:"\u7C7B\u578B",comment:"\u6CE8\u91CA",default:"\u9ED8\u8BA4\u503C",nullable:"\u53EF\u7A7A\u7EA6\u675F",unique:"\u552F\u4E00\u7EA6\u675F"},$Y={ENGINE:"InnoDB",CHARSET:"utf8mb4",COLLATE:"utf8mb4_0900_ai_ci"},XJ=[{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"}],pZ=XJ.filter(($)=>$.needsIndex).map(($)=>$.name),JY={};for(let $ of XJ)JY[$.name]=$;var ZY={DB_VERSION_REQUIREMENTS:S$,CHANGE_TYPE_LABELS:e1,MYSQL_TABLE_CONFIG:$Y,SYSTEM_INDEX_FIELDS:pZ,getTypeMapping:wJ,quoteIdentifier:Y0,escapeComment:TJ,applyFieldDefaults:XY,isStringOrArrayType:ZJ,getSqlType:uZ,resolveDefaultValue:YJ,generateDefaultSql:vJ,buildIndexSQL:CJ,buildSystemColumnDefs:GY,buildBusinessColumnDefs:WY,generateDDLClause:cZ,isCompatibleTypeChange:HY,compareFieldDefinition:UY,tableExistsRuntime:QY,getTableColumnsRuntime:zY,getTableIndexesRuntime:mZ,createRuntime:($,J,Z="")=>{return{dbDialect:$,db:J,dbName:Z}}};EJ.TestKit=ZY;Object.defineProperty(EJ,"TestKit",{value:ZY,writable:!1,enumerable:!0,configurable:!1});function wJ($){return{number:$==="sqlite"?"INTEGER":$==="postgresql"?"BIGINT":"BIGINT",string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",text:$==="mysql"?"MEDIUMTEXT":"TEXT",array_string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",array_text:$==="mysql"?"MEDIUMTEXT":"TEXT",array_number_string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",array_number_text:$==="mysql"?"MEDIUMTEXT":"TEXT"}}function Y0($,J){return f$($).quoteIdent(J)}function TJ($){return String($).replace(/"/g,"\\\"")}function XY($){$.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 ZJ($){return $==="string"||$==="array_string"||$==="array_number_string"}function uZ($,J,Z,X=!1){let Y=wJ($);if(ZJ(J))return`${Y[J]}(${Z})`;let G=Y[J]||"TEXT";if($==="mysql"&&J==="number"&&X)return`${G} UNSIGNED`;return G}function YJ($,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 vJ($,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 CJ($,J,Z,X,Y){let G=Y0($,J),H=Y0($,Z),z=Y0($,X);if($==="mysql"){let V=[];if(Y==="create")V.push(`ADD INDEX ${H} (${z})`);else V.push(`DROP INDEX ${H}`);return`ALTER TABLE ${G} ALGORITHM=INPLACE, LOCK=NONE, ${V.join(", ")}`}if($==="postgresql"){if(Y==="create")return`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${H} ON ${G}(${z})`;return`DROP INDEX CONCURRENTLY IF EXISTS ${H}`}if(Y==="create")return`CREATE INDEX IF NOT EXISTS ${H} ON ${G}(${z})`;return`DROP INDEX IF EXISTS ${H}`}function YY($,J){let Z=JY[J];if(!Z)return null;let X=Y0($,Z.name);if($==="mysql")return`${X} ${Z.mysqlDdl} COMMENT "${TJ(Z.comment)}"`;if($==="postgresql")return`${X} ${Z.pgDdl}`;return`${X} ${Z.sqliteDdl}`}function GY($){let J=[];for(let Z of XJ){let X=YY($,Z.name);if(X)J.push(X)}return J}function WY($,J){let Z=[];for(let[X,Y]of Object.entries(J)){let G=u(X),H=Y0($,G),z=uZ($,Y.type,Y.max,Y.unsigned),V=YJ(Y.default,Y.type),O=vJ(V,Y.type),F=Y.unique?" UNIQUE":"",I=Y.nullable?" NULL":" NOT NULL";if($==="mysql")Z.push(`${H} ${z}${F}${I}${O} COMMENT "${TJ(Y.name)}"`);else Z.push(`${H} ${z}${F}${I}${O}`)}return Z}function cZ($,J,Z,X=!1){let Y=u(J),G=Y0($,Y),H=uZ($,Z.type,Z.max,Z.unsigned),z=YJ(Z.default,Z.type),V=vJ(z,Z.type),O=Z.unique?" UNIQUE":"",F=Z.nullable?" NULL":" NOT NULL";if($==="mysql")return`${X?"ADD COLUMN":"MODIFY COLUMN"} ${G} ${H}${O}${F}${V} COMMENT "${TJ(Z.name)}"`;if($==="postgresql"){if(X)return`ADD COLUMN IF NOT EXISTS ${G} ${H}${O}${F}${V}`;return`ALTER COLUMN ${G} TYPE ${H}`}if(X)return`ADD COLUMN IF NOT EXISTS ${G} ${H}${O}${F}${V}`;return""}async function a1($,J){try{return await $.unsafe(J),!0}catch(Z){if(J.includes("ALGORITHM=INSTANT")){let X=J.replace(/ALGORITHM=INSTANT/g,"ALGORITHM=INPLACE");try{return await $.unsafe(X),!0}catch{let Y=J;return Y=Y.replace(/\bALGORITHM\s*=\s*(INPLACE|INSTANT)\b\s*,?\s*/g,"").replace(/\bLOCK\s*=\s*(NONE|SHARED|EXCLUSIVE)\b\s*,?\s*/g,""),Y=Y.replace(/,\s*,/g,", ").replace(/,\s*$/g,"").replace(/\s{2,}/g," ").trim(),await $.unsafe(Y),!0}}else throw Z}}function HY($,J){let Z=String($||"").toLowerCase(),X=String(J||"").toLowerCase();if(Z===X)return!1;let Y=Z.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),G=X.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),H=["tinyint","smallint","mediumint","int","integer","bigint"],z=H.indexOf(Y),V=H.indexOf(G);if(z!==-1&&V!==-1&&V>z)return!0;if(Y==="varchar"&&(G==="text"||G==="mediumtext"||G==="longtext"))return!0;if(Y==="character varying"&&G==="text")return!0;return!1}async function QY($,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=f$($.dbDialect).tableExistsQuery(J,Z);return((await $.db.unsafe(X.sql,X.params)).data?.[0]?.count||0)>0}catch(Z){let X=String(Z?.message||Z),Y=Error(`runtime I/O \u5931\u8D25: op=tableExists table=${J} err=${X}`);if(Z?.sqlInfo)Y.sqlInfo=Z.sqlInfo;throw Y}}async function zY($,J){let Z={};try{if($.dbDialect==="mysql"){let X=LJ({dialect:"mysql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.columns.sql,X.columns.params);for(let G of Y.data){let H=G.COLUMN_DEFAULT;Z[G.COLUMN_NAME]={type:G.DATA_TYPE,columnType:G.COLUMN_TYPE,length:G.CHARACTER_MAXIMUM_LENGTH,max:G.CHARACTER_MAXIMUM_LENGTH,nullable:G.IS_NULLABLE==="YES",defaultValue:H,comment:G.COLUMN_COMMENT}}}else if($.dbDialect==="postgresql"){let X=LJ({dialect:"postgresql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.columns.sql,X.columns.params),G=X.comments?(await $.db.unsafe(X.comments.sql,X.comments.params)).data:[],H={};for(let z of G)H[z.column_name]=z.column_comment;for(let z of Y.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=LJ({dialect:"sqlite",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.columns.sql,X.columns.params);for(let G of Y.data){let H=String(G.type||"").toUpperCase(),z=null,V=/^(\w+)\s*\((\d+)\)/.exec(H);if(V)H=V[1],z=Number(V[2]);Z[G.name]={type:H.toLowerCase(),columnType:H.toLowerCase(),length:z,max:z,nullable:G.notnull===0,defaultValue:G.dflt_value,comment:null}}}return Z}catch(X){let Y=String(X?.message||X),G=Error(`runtime I/O \u5931\u8D25: op=getTableColumns table=${J} err=${Y}`);if(X?.sqlInfo)G.sqlInfo=X.sqlInfo;throw G}}async function mZ($,J){let Z={};try{if($.dbDialect==="mysql"){let X=bZ({dialect:"mysql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.sql,X.params);for(let G of Y.data){if(!Z[G.INDEX_NAME])Z[G.INDEX_NAME]=[];Z[G.INDEX_NAME].push(G.COLUMN_NAME)}}else if($.dbDialect==="postgresql"){let X=bZ({dialect:"postgresql",table:J,dbName:$.dbName}),Y=await $.db.unsafe(X.sql,X.params);for(let G of Y.data){let H=/\(([^)]+)\)/.exec(G.indexdef);if(H){let z=H[1].replace(/"/g,"").trim();Z[G.indexname]=[z]}}}else if($.dbDialect==="sqlite"){let X=Y0("sqlite",J),Y=await $.db.unsafe(`PRAGMA index_list(${X})`);for(let G of Y.data){let H=Y0("sqlite",G.name),V=(await $.db.unsafe(`PRAGMA index_info(${H})`)).data.map((O)=>O.name);if(V.length===1)Z[G.name]=V}}return Z}catch(X){let Y=String(X?.message||X),G=Error(`runtime I/O \u5931\u8D25: op=getTableIndexes table=${J} err=${Y}`);if(X?.sqlInfo)G.sqlInfo=X.sqlInfo;throw G}}async function yH($,J){if(!J)throw Error("SQL \u6267\u884C\u5668\u672A\u521D\u59CB\u5316");if($==="mysql"){let Z=await J.unsafe("SELECT VERSION() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 MySQL \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,Y=parseInt(String(X).split(".")[0],10);if(!Number.isFinite(Y)||Y<S$.MYSQL_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u4EC5\u652F\u6301 MySQL ${S$.MYSQL_MIN_MAJOR}.0+\uFF0C\u5F53\u524D\u7248\u672C: ${X}`);return}if($==="postgresql"){let Z=await J.unsafe("SELECT version() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 PostgreSQL \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,Y=/PostgreSQL\s+(\d+)/i.exec(X),G=Y?parseInt(Y[1],10):NaN;if(!Number.isFinite(G)||G<S$.POSTGRES_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 PostgreSQL >= ${S$.POSTGRES_MIN_MAJOR}\uFF0C\u5F53\u524D: ${X}`);return}if($==="sqlite"){let Z=await J.unsafe("SELECT sqlite_version() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 SQLite \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,[Y,G,H]=String(X).split(".").map((V)=>parseInt(V,10)||0),z=Y*1e4+G*100+H;if(!Number.isFinite(z)||z<S$.SQLITE_MIN_VERSION_NUM)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 SQLite >= ${S$.SQLITE_MIN_VERSION}\uFF0C\u5F53\u524D: ${X}`);return}}function UY($,J,Z){let X=[];if($!=="sqlite"&&ZJ(Z.type)){if(J.max!==Z.max)X.push({type:"length",current:J.max,expected:Z.max})}if($!=="sqlite"){let O=J.comment||"";if(O!==Z.name)X.push({type:"comment",current:O,expected:Z.name})}let G=wJ($)[Z.type].toLowerCase(),H=J.type.toLowerCase();if(H!==G)X.push({type:"datatype",current:H,expected:G});let z=Z.nullable;if(J.nullable!==z)X.push({type:"nullable",current:J.nullable,expected:z});let V=YJ(Z.default,Z.type);if(String(J.defaultValue)!==String(V))X.push({type:"default",current:J.defaultValue,expected:V});return X}async function xH($,J,Z){if($.dbDialect!=="sqlite")throw Error(`rebuildSqliteTable \u4EC5\u652F\u6301 sqlite \u65B9\u8A00\uFF0C\u5F53\u524D: ${String($.dbDialect)}`);let X=Y0("sqlite",J),G=(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)=>u(I))],V=`${J}__tmp__${Date.now()}`;await VY($,V,Z);let O=z.filter((I)=>G.includes(I));if(O.length>0){let I=O.map((L)=>Y0("sqlite",L)).join(", "),B=Y0("sqlite",V);await $.db.unsafe(`INSERT INTO ${B} (${I}) SELECT ${I} FROM ${X}`)}await $.db.unsafe(`DROP TABLE ${X}`);let F=Y0("sqlite",V);await $.db.unsafe(`ALTER TABLE ${F} RENAME TO ${X}`)}async function fH($,J,Z,X){if(!X||!X.changed)return;if($.dbDialect==="sqlite")if(X.modifyClauses.length>0||X.defaultClauses.length>0)await xH($,J,Z);else for(let Y of X.addClauses){let G=`ALTER TABLE ${Y0($.dbDialect,J)} ${Y}`;await $.db.unsafe(G)}else{let Y=[...X.addClauses,...X.modifyClauses];if(Y.length>0){let G=Y0($.dbDialect,J),H=$.dbDialect==="mysql"?`ALTER TABLE ${G} ALGORITHM=INSTANT, LOCK=NONE, ${Y.join(", ")}`:`ALTER TABLE ${G} ${Y.join(", ")}`;if($.dbDialect==="mysql")await a1($.db,H);else await $.db.unsafe(H)}}if(X.defaultClauses.length>0)if($.dbDialect==="sqlite")P.warn(`SQLite \u4E0D\u652F\u6301\u4FEE\u6539\u9ED8\u8BA4\u503C\uFF0C\u8868 ${J} \u7684\u9ED8\u8BA4\u503C\u53D8\u66F4\u5DF2\u8DF3\u8FC7`);else{let Y=Y0($.dbDialect,J),G=$.dbDialect==="mysql"?`ALTER TABLE ${Y} ALGORITHM=INSTANT, LOCK=NONE, ${X.defaultClauses.join(", ")}`:`ALTER TABLE ${Y} ${X.defaultClauses.join(", ")}`;if($.dbDialect==="mysql")await a1($.db,G);else await $.db.unsafe(G)}for(let Y of X.indexActions){let G=CJ($.dbDialect,J,Y.indexName,Y.fieldName,Y.action);try{if(await $.db.unsafe(G),Y.action==="create")P.debug(`[\u7D22\u5F15\u53D8\u5316] \u65B0\u5EFA\u7D22\u5F15 ${J}.${Y.indexName} (${Y.fieldName})`);else P.debug(`[\u7D22\u5F15\u53D8\u5316] \u5220\u9664\u7D22\u5F15 ${J}.${Y.indexName} (${Y.fieldName})`)}catch(H){throw P.error({err:H,table:J,index:Y.indexName,field:Y.fieldName,msg:`${Y.action==="create"?"\u521B\u5EFA":"\u5220\u9664"}\u7D22\u5F15\u5931\u8D25`}),H}}if($.dbDialect==="postgresql"&&X.commentActions&&X.commentActions.length>0)for(let Y of X.commentActions)await $.db.unsafe(Y)}async function VY($,J,Z,X=pZ){let G=[...GY($.dbDialect),...WY($.dbDialect,Z)].join(`,
|
|
7
7
|
`),H=Y0($.dbDialect,J),{ENGINE:z,CHARSET:V,COLLATE:O}=$Y,F=$.dbDialect==="mysql"?`CREATE TABLE ${H} (
|
|
8
8
|
${G}
|
|
9
9
|
) ENGINE=${z} DEFAULT CHARSET=${V} COLLATE=${O}`:`CREATE TABLE ${H} (
|
|
10
10
|
${G}
|
|
11
11
|
)`;if(await $.db.unsafe(F),$.dbDialect==="postgresql"){for(let L of XJ){let C=String(L.comment).replace(/'/g,"''"),w=Y0($.dbDialect,L.name),T=`COMMENT ON COLUMN ${H}.${w} IS '${C}'`;await $.db.unsafe(T)}for(let[L,C]of Object.entries(Z)){let w=u(L),T=Y0($.dbDialect,w),N=C.name&&C.name!=="null"?String(C.name):"",E=N.replace(/'/g,"''"),D=N?`'${E}'`:"NULL",h=`COMMENT ON COLUMN ${H}.${T} IS ${D}`;await $.db.unsafe(h)}}let I=[],B={};if($.dbDialect==="mysql")B=await mZ($,J);for(let L of X){let C=`idx_${L}`;if($.dbDialect==="mysql"&&B[C])continue;let w=CJ($.dbDialect,J,C,L,"create");I.push($.db.unsafe(w))}for(let[L,C]of Object.entries(Z)){let w=u(L);if(C.index===!0&&C.unique!==!0){let T=`idx_${w}`;if($.dbDialect==="mysql"&&B[T])continue;let N=CJ($.dbDialect,J,T,w,"create");I.push($.db.unsafe(N))}}if(I.length>0)await Promise.all(I)}async function gH($,J,Z){let X=await zY($,J),Y=await mZ($,J),G=!1,H=[],z=[],V=[],O=[];for(let[L,C]of Object.entries(Z)){let w=u(L);if(X[w]){let T=UY($.dbDialect,X[w],C);if(T.length>0){for(let v of T){let f=e1[v.type]||"\u672A\u77E5";P.debug(` ~ \u4FEE\u6539 ${w} ${f}: ${v.current} -> ${v.expected}`)}if(ZJ(C.type)&&X[w].max&&C.max!==null){if(X[w].max>C.max)P.warn(`[\u8DF3\u8FC7\u5371\u9669\u53D8\u66F4] ${J}.${w} \u957F\u5EA6\u6536\u7F29 ${X[w].max} -> ${C.max} \u5DF2\u88AB\u8DF3\u8FC7\uFF08\u9700\u624B\u52A8\u5904\u7406\uFF09`)}let N=T.some((v)=>v.type==="datatype"),E=T.some((v)=>v.type==="length"),D=T.every((v)=>v.type==="default"),h=T.some((v)=>v.type==="default");if(N){let v=T.find((u0)=>u0.type==="datatype"),f=String(v?.current||"").toLowerCase(),r=wJ($.dbDialect)[C.type]?.toLowerCase()||"";if(!HY(f,r)){let u0=[`\u7981\u6B62\u5B57\u6BB5\u7C7B\u578B\u53D8\u66F4: ${J}.${w}`,`\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)}P.debug(`[\u517C\u5BB9\u7C7B\u578B\u53D8\u66F4] ${J}.${w} ${f} -> ${r}`)}if(h){let v=YJ(C.default,C.type),f=null;if(v!=="null")f=vJ(v,C.type).trim().replace(/^DEFAULT\s+/,"");if(f!==null&&f!==""){if($.dbDialect==="postgresql"){let l=Y0($.dbDialect,w);V.push(`ALTER COLUMN ${l} SET DEFAULT ${f}`)}else if($.dbDialect==="mysql"&&D){if(C.type!=="text"){let l=Y0($.dbDialect,w);V.push(`ALTER COLUMN ${l} SET DEFAULT ${f}`)}}}}if(!D){let v=!1;if(E&&ZJ(C.type)&&X[w].max&&C.max!==null){if(X[w].max>C.max)v=!0}if(!v)z.push(cZ($.dbDialect,L,C,!1))}G=!0}}else H.push(cZ($.dbDialect,L,C,!0)),G=!0}let F=XJ.filter((L)=>L.name!=="id").map((L)=>L.name);for(let L of F)if(!X[L]){let C=YY($.dbDialect,L);if(C)P.debug(` + \u65B0\u589E\u7CFB\u7EDF\u5B57\u6BB5 ${L}`),H.push(`ADD COLUMN ${C}`),G=!0}for(let L of pZ){let C=`idx_${L}`;if((X[L]||F.includes(L))&&!Y[C])O.push({action:"create",indexName:C,fieldName:L}),G=!0}for(let[L,C]of Object.entries(Z)){let w=u(L),T=`idx_${w}`;if(C.index&&!C.unique&&!Y[T])O.push({action:"create",indexName:T,fieldName:w}),G=!0;else if(!C.index&&Y[T]&&Y[T].length===1)O.push({action:"drop",indexName:T,fieldName:w}),G=!0}let I=[];if($.dbDialect==="postgresql"){let L=Y0($.dbDialect,J);for(let[C,w]of Object.entries(Z)){let T=u(C),N=Y0($.dbDialect,T);if(X[T]){let E=X[T].comment||"",D=w.name&&w.name!=="null"?String(w.name):"";if(D!==E){let h=D.replace(/'/g,"''");I.push(`COMMENT ON COLUMN ${L}.${N} IS ${D?`'${h}'`:"NULL"}`),G=!0}}}}G=H.length>0||z.length>0||V.length>0||O.length>0||I.length>0;let B={changed:G,addClauses:H,modifyClauses:z,defaultClauses:V,indexActions:O,commentActions:I};if(B.changed)await fH($,J,Z,B);return B}var OY=($,J=Bun.nanoseconds())=>{let Z=(J-$)/1e6;if(Z<1000)return`${Z.toFixed(2)} \u6BEB\u79D2`;else return`${(Z/1000).toFixed(2)} \u79D2`};function _Y(){let $=process.env.BUN_WORKER_ID,J=process.env.PM2_INSTANCE_ID;if($!==void 0)return{role:$===""?"primary":"worker",instanceId:$||"0",env:"bun-cluster"};if(J!==void 0)return{role:J==="0"?"primary":"worker",instanceId:J,env:"pm2-cluster"};return{role:"primary",instanceId:null,env:"standalone"}}I$();I$();import{existsSync as hH,readdirSync as bH}from"fs";fZ();m0();var AY=()=>{let $=new Map,J=(Z,X,Y)=>{if(!hH(Z))return;let G=bH(Z,{withFileTypes:!0});for(let H of G){if(H.name.startsWith("_"))continue;if(!qJ(Z,H))continue;let z=a$(Z,H.name),V={source:X,sourceName:Y,name:H.name,camelName:K$(H.name),rootDir:z,fullPath:z};$.set(H.name,V)}};return J(
|
|
12
|
+
`);throw Error(u0)}P.debug(`[\u517C\u5BB9\u7C7B\u578B\u53D8\u66F4] ${J}.${w} ${f} -> ${r}`)}if(h){let v=YJ(C.default,C.type),f=null;if(v!=="null")f=vJ(v,C.type).trim().replace(/^DEFAULT\s+/,"");if(f!==null&&f!==""){if($.dbDialect==="postgresql"){let l=Y0($.dbDialect,w);V.push(`ALTER COLUMN ${l} SET DEFAULT ${f}`)}else if($.dbDialect==="mysql"&&D){if(C.type!=="text"){let l=Y0($.dbDialect,w);V.push(`ALTER COLUMN ${l} SET DEFAULT ${f}`)}}}}if(!D){let v=!1;if(E&&ZJ(C.type)&&X[w].max&&C.max!==null){if(X[w].max>C.max)v=!0}if(!v)z.push(cZ($.dbDialect,L,C,!1))}G=!0}}else H.push(cZ($.dbDialect,L,C,!0)),G=!0}let F=XJ.filter((L)=>L.name!=="id").map((L)=>L.name);for(let L of F)if(!X[L]){let C=YY($.dbDialect,L);if(C)P.debug(` + \u65B0\u589E\u7CFB\u7EDF\u5B57\u6BB5 ${L}`),H.push(`ADD COLUMN ${C}`),G=!0}for(let L of pZ){let C=`idx_${L}`;if((X[L]||F.includes(L))&&!Y[C])O.push({action:"create",indexName:C,fieldName:L}),G=!0}for(let[L,C]of Object.entries(Z)){let w=u(L),T=`idx_${w}`;if(C.index&&!C.unique&&!Y[T])O.push({action:"create",indexName:T,fieldName:w}),G=!0;else if(!C.index&&Y[T]&&Y[T].length===1)O.push({action:"drop",indexName:T,fieldName:w}),G=!0}let I=[];if($.dbDialect==="postgresql"){let L=Y0($.dbDialect,J);for(let[C,w]of Object.entries(Z)){let T=u(C),N=Y0($.dbDialect,T);if(X[T]){let E=X[T].comment||"",D=w.name&&w.name!=="null"?String(w.name):"";if(D!==E){let h=D.replace(/'/g,"''");I.push(`COMMENT ON COLUMN ${L}.${N} IS ${D?`'${h}'`:"NULL"}`),G=!0}}}}G=H.length>0||z.length>0||V.length>0||O.length>0||I.length>0;let B={changed:G,addClauses:H,modifyClauses:z,defaultClauses:V,indexActions:O,commentActions:I};if(B.changed)await fH($,J,Z,B);return B}var OY=($,J=Bun.nanoseconds())=>{let Z=(J-$)/1e6;if(Z<1000)return`${Z.toFixed(2)} \u6BEB\u79D2`;else return`${(Z/1000).toFixed(2)} \u79D2`};function _Y(){let $=process.env.BUN_WORKER_ID,J=process.env.PM2_INSTANCE_ID;if($!==void 0)return{role:$===""?"primary":"worker",instanceId:$||"0",env:"bun-cluster"};if(J!==void 0)return{role:J==="0"?"primary":"worker",instanceId:J,env:"pm2-cluster"};return{role:"primary",instanceId:null,env:"standalone"}}I$();I$();import{existsSync as hH,readdirSync as bH}from"fs";fZ();m0();var AY=()=>{let $=new Map,J=(Z,X,Y)=>{if(!hH(Z))return;let G=bH(Z,{withFileTypes:!0});for(let H of G){if(H.name.startsWith("_"))continue;if(!qJ(Z,H))continue;let z=a$(Z,H.name),V={source:X,sourceName:Y,name:H.name,camelName:K$(H.name),rootDir:z,fullPath:z};$.set(H.name,V)}};return J(n(n0,"node_modules","@befly-addon"),"addon","\u7EC4\u4EF6"),J(d1,"app","\u9879\u76EE"),Array.from($.values())};KJ();var cH={name:"auth",enable:!0,deps:["cors"],handler:async($,J)=>{let Z=J.req.headers.get("authorization");if(Z&&Z.startsWith("Bearer ")){let X=Z.substring(7);try{let Y=await $.jwt.verify(X);J.user=Y,z1(Y.id,Y.roleCode,Y.nickname,Y.roleType)}catch{J.user={}}}else J.user={}}},KY=cH;var pH={name:"cors",enable:!0,deps:[],handler:async($,J)=>{let Z=J.req,Y=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:{}),G=BJ(Z,Y);if(J.corsHeaders=G,Z.method==="OPTIONS"){J.response=new Response(null,{status:204,headers:G});return}}},FY=pH;var uH=":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",mH="[: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]["+uH+"]*",dH=new RegExp("^"+mH+"$");function NJ($,J){let Z=[],X=J.exec($);while(X){let Y=[];Y.startIndex=J.lastIndex-X[0].length;let G=X.length;for(let H=0;H<G;H++)Y.push(X[H]);Z.push(Y),X=J.exec($)}return Z}var g$=function($){let J=dH.exec($);return!(J===null||typeof J>"u")};function MY($){return typeof $<"u"}var nH={allowBooleanAttributes:!1,unpairedTags:[]};function jY($,J){J=Object.assign({},nH,J);let Z=[],X=!1,Y=!1;if($[0]==="\uFEFF")$=$.substr(1);for(let G=0;G<$.length;G++)if($[G]==="<"&&$[G+1]==="?"){if(G+=2,G=IY($,G),G.err)return G}else if($[G]==="<"){let H=G;if(G++,$[G]==="!"){G=qY($,G);continue}else{let z=!1;if($[G]==="/")z=!0,G++;let V="";for(;G<$.length&&$[G]!==">"&&$[G]!==" "&&$[G]!=="\t"&&$[G]!==`
|
|
13
13
|
`&&$[G]!=="\r";G++)V+=$[G];if(V=V.trim(),V[V.length-1]==="/")V=V.substring(0,V.length-1),G--;if(!eH(V)){let I;if(V.trim().length===0)I="Invalid space after '<'.";else I="Tag '"+V+"' is an invalid name.";return G0("InvalidTag",I,s0($,G))}let O=lH($,G);if(O===!1)return G0("InvalidAttr","Attributes for '"+V+"' have open quote.",s0($,G));let F=O.value;if(G=O.index,F[F.length-1]==="/"){let I=G-F.length;F=F.substring(0,F.length-1);let B=PY(F,J);if(B===!0)X=!0;else return G0(B.err.code,B.err.msg,s0($,I+B.err.line))}else if(z)if(!O.tagClosed)return G0("InvalidTag","Closing tag '"+V+"' doesn't have proper closing.",s0($,G));else if(F.trim().length>0)return G0("InvalidTag","Closing tag '"+V+"' can't have attributes or invalid starting.",s0($,H));else if(Z.length===0)return G0("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 G0("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)Y=!0}else{let I=PY(F,J);if(I!==!0)return G0(I.err.code,I.err.msg,s0($,G-F.length+I.err.line));if(Y===!0)return G0("InvalidXml","Multiple possible root nodes found.",s0($,G));else if(J.unpairedTags.indexOf(V)!==-1);else Z.push({tagName:V,tagStartPos:H});X=!0}for(G++;G<$.length;G++)if($[G]==="<")if($[G+1]==="!"){G++,G=qY($,G);continue}else if($[G+1]==="?"){if(G=IY($,++G),G.err)return G}else break;else if($[G]==="&"){let I=tH($,G);if(I==-1)return G0("InvalidChar","char '&' is not expected.",s0($,G));G=I}else if(Y===!0&&!RY($[G]))return G0("InvalidXml","Extra text at the end",s0($,G));if($[G]==="<")G--}}else{if(RY($[G]))continue;return G0("InvalidChar","char '"+$[G]+"' is not expected.",s0($,G))}if(!X)return G0("InvalidXml","Start tag expected.",1);else if(Z.length==1)return G0("InvalidTag","Unclosed tag '"+Z[0].tagName+"'.",s0($,Z[0].tagStartPos));else if(Z.length>0)return G0("InvalidXml","Invalid '"+JSON.stringify(Z.map((G)=>G.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function RY($){return $===" "||$==="\t"||$===`
|
|
14
|
-
`||$==="\r"}function IY($,J){let Z=J;for(;J<$.length;J++)if($[J]=="?"||$[J]==" "){let X=$.substr(Z,J-Z);if(J>5&&X==="xml")return G0("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 qY($,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 sH='"',oH="'";function lH($,J){let Z="",X="",Y=!1;for(;J<$.length;J++){if($[J]===sH||$[J]===oH)if(X==="")X=$[J];else if(X!==$[J]);else X="";else if($[J]===">"){if(X===""){Y=!0;break}}Z+=$[J]}if(X!=="")return!1;return{value:Z,index:J,tagClosed:Y}}var rH=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function PY($,J){let Z=NJ($,rH),X={};for(let Y=0;Y<Z.length;Y++){if(Z[Y][1].length===0)return G0("InvalidAttr","Attribute '"+Z[Y][2]+"' has no space in starting.",GJ(Z[Y]));else if(Z[Y][3]!==void 0&&Z[Y][4]===void 0)return G0("InvalidAttr","Attribute '"+Z[Y][2]+"' is without value.",GJ(Z[Y]));else if(Z[Y][3]===void 0&&!J.allowBooleanAttributes)return G0("InvalidAttr","boolean attribute '"+Z[Y][2]+"' is not allowed.",GJ(Z[Y]));let G=Z[Y][2];if(!aH(G))return G0("InvalidAttr","Attribute '"+G+"' is an invalid name.",GJ(Z[Y]));if(!X.hasOwnProperty(G))X[G]=1;else return G0("InvalidAttr","Attribute '"+G+"' is repeated.",GJ(Z[Y]))}return!0}function iH($,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 tH($,J){if(J++,$[J]===";")return-1;if($[J]==="#")return J++,iH($,J);let Z=0;for(;J<$.length;J++,Z++){if($[J].match(/\w/)&&Z<20)continue;if($[J]===";")break;return-1}return J}function G0($,J,Z){return{err:{code:$,msg:J,line:Z.line||Z,col:Z.col}}}function aH($){return g$($)}function eH($){return g$($)}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 $Q={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},BY=function($){return Object.assign({},$Q,$)};var DJ;if(typeof Symbol!=="function")DJ="@@xmlMetadata";else DJ=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][DJ]={startIndex:J}}static getMetaDataSymbol(){return DJ}}class kJ{constructor($){this.suppressValidationErr=!$}readDocType($,J){let Z={};if($[J+3]==="O"&&$[J+4]==="C"&&$[J+5]==="T"&&$[J+6]==="Y"&&$[J+7]==="P"&&$[J+8]==="E"){J=J+9;let X=1,Y=!1,G=!1,H="";for(;J<$.length;J++)if($[J]==="<"&&!G){if(Y&&C$($,"!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(Y&&C$($,"!ELEMENT",J)){J+=8;let{index:z}=this.readElementExp($,J+1);J=z}else if(Y&&C$($,"!ATTLIST",J))J+=8;else if(Y&&C$($,"!NOTATION",J)){J+=9;let{index:z}=this.readNotationExp($,J+1,this.suppressValidationErr);J=z}else if(C$($,"!--",J))G=!0;else throw Error("Invalid DOCTYPE");X++,H=""}else if($[J]===">"){if(G){if($[J-1]==="-"&&$[J-2]==="-")G=!1,X--}else X--;if(X===0)break}else if($[J]==="[")Y=!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(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 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&&WJ(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 Y=null,G=null;if(X==="PUBLIC"){if([J,Y]=this.readIdentifierVal($,J,"publicIdentifier"),J=l0($,J),$[J]==='"'||$[J]==="'")[J,G]=this.readIdentifierVal($,J,"systemIdentifier")}else if(X==="SYSTEM"){if([J,G]=this.readIdentifierVal($,J,"systemIdentifier"),!this.suppressValidationErr&&!G)throw Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:Z,publicIdentifier:Y,systemIdentifier:G,index:--J}}readIdentifierVal($,J,Z){let X="",Y=$[J];if(Y!=='"'&&Y!=="'")throw Error(`Expected quoted string, found "${Y}"`);J++;while(J<$.length&&$[J]!==Y)X+=$[J],J++;if($[J]!==Y)throw Error(`Unterminated ${Z} value`);return J++,[J,X]}readElementExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;if(!this.suppressValidationErr&&!g$(Z))throw Error(`Invalid element name: "${Z}"`);J=l0($,J);let X="";if($[J]==="E"&&C$($,"MPTY",J))J+=4;else if($[J]==="A"&&C$($,"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++;WJ(Z),J=l0($,J);let X="";while(J<$.length&&!/\s/.test($[J]))X+=$[J],J++;if(!WJ(X))throw Error(`Invalid attribute name: "${X}"`);J=l0($,J);let Y="";if($.substring(J,J+8).toUpperCase()==="NOTATION"){if(Y="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(),!WJ(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++,Y+=" ("+H.join("|")+")"}else{while(J<$.length&&!/\s/.test($[J]))Y+=$[J],J++;let H=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!H.includes(Y.toUpperCase()))throw Error(`Invalid attribute type: "${Y}"`)}J=l0($,J);let G="";if($.substring(J,J+8).toUpperCase()==="#REQUIRED")G="#REQUIRED",J+=8;else if($.substring(J,J+7).toUpperCase()==="#IMPLIED")G="#IMPLIED",J+=7;else[J,G]=this.readIdentifierVal($,J,"ATTLIST");return{elementName:Z,attributeName:X,attributeType:Y,defaultValue:G,index:J}}}var l0=($,J)=>{while(J<$.length&&/\s/.test($[J]))J++;return J};function C$($,J,Z){for(let X=0;X<J.length;X++)if(J[X]!==$[Z+X+1])return!1;return!0}function WJ($){if(g$($))return $;else throw Error(`Invalid entity name ${$}`)}var JQ=/^[-+]?0x[a-fA-F0-9]+$/,ZQ=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,XQ={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function nZ($,J={}){if(J=Object.assign({},XQ,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&&JQ.test(Z))return HQ(Z,16);else if(Z.includes("e")||Z.includes("E"))return GQ($,Z,J);else{let X=ZQ.exec(Z);if(X){let Y=X[1]||"",G=X[2],H=WQ(X[3]),z=Y?$[G.length+1]===".":$[G.length]===".";if(!J.leadingZeros&&(G.length>1||G.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===`${Y}${H}`)return V;else return $;let F=G?H:Z;if(G)return F===O||Y+F===O?V:$;else return F===O||F===Y+O?V:$}}else return $}}var YQ=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function GQ($,J,Z){if(!Z.eNotation)return $;let X=J.match(YQ);if(X){let Y=X[1]||"",G=X[3].indexOf("e")===-1?"E":"e",H=X[2],z=Y?$[H.length+1]===G:$[H.length]===G;if(H.length>1&&z)return $;else if(H.length===1&&(X[3].startsWith(`.${G}`)||X[3][0]===G))return Number(J);else if(Z.leadingZeros&&!z)return J=(X[1]||"")+X[3],Number(J);else return $}else return $}function WQ($){if($&&$.indexOf(".")!==-1){if($=$.replace(/0+$/,""),$===".")$="0";else if($[0]===".")$="0"+$;else if($[$.length-1]===".")$=$.substring(0,$.length-1);return $}return $}function HQ($,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 dZ($){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 yJ{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=QQ,this.parseXml=_Q,this.parseTextData=zQ,this.resolveNameSpace=UQ,this.buildAttributesMap=OQ,this.isItStopNode=MQ,this.replaceEntitiesValue=KQ,this.readStopNodeData=IQ,this.saveTextToParentTag=FQ,this.addChild=AQ,this.ignoreAttributesFn=dZ(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 QQ($){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 zQ($,J,Z,X,Y,G,H){if($!==void 0){if(this.options.trimValues&&!X)$=$.trim();if($.length>0){if(!H)$=this.replaceEntitiesValue($);let z=this.options.tagValueProcessor(J,$,Z,Y,G);if(z===null||z===void 0)return $;else if(typeof z!==typeof $||z!==$)return z;else if(this.options.trimValues)return oZ($,this.options.parseTagValue,this.options.numberParseOptions);else if($.trim()===$)return oZ($,this.options.parseTagValue,this.options.numberParseOptions);else return $}}}function UQ($){if(this.options.removeNSPrefix){let J=$.split(":"),Z=$.charAt(0)==="/"?"/":"";if(J[0]==="xmlns")return"";if(J.length===2)$=Z+J[1]}return $}var VQ=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function OQ($,J){if(this.options.ignoreAttributes!==!0&&typeof $==="string"){let Z=NJ($,VQ),X=Z.length,Y={};for(let G=0;G<X;G++){let H=this.resolveNameSpace(Z[G][1]);if(this.ignoreAttributesFn(H,J))continue;let z=Z[G][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)Y[V]=z;else if(typeof O!==typeof z||O!==z)Y[V]=O;else Y[V]=oZ(z,this.options.parseAttributeValue,this.options.numberParseOptions)}else if(this.options.allowBooleanAttributes)Y[V]=!0}}if(!Object.keys(Y).length)return;if(this.options.attributesGroupName){let G={};return G[this.options.attributesGroupName]=Y,G}return Y}}var _Q=function($){$=$.replace(/\r\n?/g,`
|
|
15
|
-
`);let J=new i0("!xml"),Z=J,X="",Y="",G=new kJ(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,Y);let F=Y.substring(Y.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(F&&this.options.unpairedTags.indexOf(F)!==-1)I=Y.lastIndexOf(".",Y.lastIndexOf(".")-1),this.tagsNodeStack.pop();else I=Y.lastIndexOf(".");Y=Y.substring(0,I),Z=this.tagsNodeStack.pop(),X="",H=V}else if($[H+1]==="?"){let V=sZ($,H,!1,"?>");if(!V)throw Error("Pi Tag is not closed.");if(X=this.saveTextToParentTag(X,Z,Y),this.options.ignoreDeclaration&&V.tagName==="?xml"||this.options.ignorePiTags);else{let O=new i0(V.tagName);if(O.add(this.options.textNodeName,""),V.tagName!==V.tagExp&&V.attrExpPresent)O[":@"]=this.buildAttributesMap(V.tagExp,Y);this.addChild(Z,O,Y,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,Y),Z.add(this.options.commentPropName,[{[this.options.textNodeName]:O}])}H=V}else if($.substr(H+1,2)==="!D"){let V=G.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,Y);let F=this.parseTextData(O,Z.tagname,Y,!0,!1,!0,!0);if(F==null)F="";if(this.options.cdataPropName)Z.add(this.options.cdataPropName,[{[this.options.textNodeName]:O}]);else Z.add(this.options.textNodeName,F);H=V+2}else{let V=sZ($,H,this.options.removeNSPrefix),O=V.tagName,F=V.rawTagName,I=V.tagExp,B=V.attrExpPresent,L=V.closeIndex;if(this.options.transformTagName){let T=this.options.transformTagName(O);if(I===O)I=T;O=T}if(Z&&X){if(Z.tagname!=="!xml")X=this.saveTextToParentTag(X,Z,Y,!1)}let C=Z;if(C&&this.options.unpairedTags.indexOf(C.tagname)!==-1)Z=this.tagsNodeStack.pop(),Y=Y.substring(0,Y.lastIndexOf("."));if(O!==J.tagname)Y+=Y?"."+O:O;let w=H;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,Y,O)){let T="";if(I.length>0&&I.lastIndexOf("/")===I.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),Y=Y.substr(0,Y.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 E=this.readStopNodeData($,F,L+1);if(!E)throw Error(`Unexpected end of ${F}`);H=E.i,T=E.tagContent}let N=new i0(O);if(O!==I&&B)N[":@"]=this.buildAttributesMap(I,Y);if(T)T=this.parseTextData(T,O,Y,!0,B,!0,!0);Y=Y.substr(0,Y.lastIndexOf(".")),N.add(this.options.textNodeName,T),this.addChild(Z,N,Y,w)}else{if(I.length>0&&I.lastIndexOf("/")===I.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),Y=Y.substr(0,Y.length-1),I=O;else I=I.substr(0,I.length-1);if(this.options.transformTagName){let N=this.options.transformTagName(O);if(I===O)I=N;O=N}let T=new i0(O);if(O!==I&&B)T[":@"]=this.buildAttributesMap(I,Y);this.addChild(Z,T,Y,w),Y=Y.substr(0,Y.lastIndexOf("."))}else{let T=new i0(O);if(this.tagsNodeStack.push(Z),O!==I&&B)T[":@"]=this.buildAttributesMap(I,Y);this.addChild(Z,T,Y,w),Z=T}X="",H=L}}else X+=$[H];return J.child};function AQ($,J,Z,X){if(!this.options.captureMetaData)X=void 0;let Y=this.options.updateTag(J.tagname,Z,J[":@"]);if(Y===!1);else if(typeof Y==="string")J.tagname=Y,$.addChild(J,X);else $.addChild(J,X)}var KQ=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 FQ($,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 MQ($,J,Z,X){if(J&&J.has(X))return!0;if($&&$.has(Z))return!0;return!1}function RQ($,J,Z=">"){let X,Y="";for(let G=J;G<$.length;G++){let H=$[G];if(X){if(H===X)X=""}else if(H==='"'||H==="'")X=H;else if(H===Z[0])if(Z[1]){if($[G+1]===Z[1])return{data:Y,index:G}}else return{data:Y,index:G};else if(H==="\t")H=" ";Y+=H}}function E$($,J,Z,X){let Y=$.indexOf(J,Z);if(Y===-1)throw Error(X);else return Y+J.length-1}function sZ($,J,Z,X=">"){let Y=RQ($,J+1,X);if(!Y)return;let{data:G,index:H}=Y,z=G.search(/\s/),V=G,O=!0;if(z!==-1)V=G.substring(0,z),G=G.substring(z+1).trimStart();let F=V;if(Z){let I=V.indexOf(":");if(I!==-1)V=V.substr(I+1),O=V!==Y.data.substr(I+1)}return{tagName:V,tagExp:G,closeIndex:H,attrExpPresent:O,rawTagName:F}}function IQ($,J,Z){let X=Z,Y=1;for(;Z<$.length;Z++)if($[Z]==="<")if($[Z+1]==="/"){let G=E$($,">",Z,`${J} is not closed`);if($.substring(Z+2,G).trim()===J){if(Y--,Y===0)return{tagContent:$.substring(X,Z),i:G}}Z=G}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 G=sZ($,Z,">");if(G){if((G&&G.tagName)===J&&G.tagExp[G.tagExp.length-1]!=="/")Y++;Z=G.closeIndex}}}function oZ($,J,Z){if(J&&typeof $==="string"){let X=$.trim();if(X==="true")return!0;else if(X==="false")return!1;else return nZ($,Z)}else if(MY($))return $;else return""}var lZ=i0.getMetaDataSymbol();function rZ($,J){return LY($,J)}function LY($,J,Z){let X,Y={};for(let G=0;G<$.length;G++){let H=$[G],z=qQ(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=LY(H[z],J,V),F=jQ(O,J);if(H[lZ]!==void 0)O[lZ]=H[lZ];if(H[":@"])PQ(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(Y[z]!==void 0&&Y.hasOwnProperty(z)){if(!Array.isArray(Y[z]))Y[z]=[Y[z]];Y[z].push(O)}else if(J.isArray(z,V,F))Y[z]=[O];else Y[z]=O}}if(typeof X==="string"){if(X.length>0)Y[J.textNodeName]=X}else if(X!==void 0)Y[J.textNodeName]=X;return Y}function qQ($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X!==":@")return X}}function PQ($,J,Z,X){if(J){let Y=Object.keys(J),G=Y.length;for(let H=0;H<G;H++){let z=Y[H];if(X.isArray(z,Z+"."+z,!0,!0))$[z]=[J[z]];else $[z]=J[z]}}}function jQ($,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 HJ{constructor($){this.externalEntities={},this.options=BY($)}parse($,J){if(typeof $!=="string"&&$.toString)$=$.toString();else if(typeof $!=="string")throw Error("XML data is accepted in String or Bytes[] form.");if(J){if(J===!0)J={};let Y=jY($,J);if(Y!==!0)throw Error(`${Y.err.msg}:${Y.err.line}:${Y.err.col}`)}let Z=new yJ(this.options);Z.addExternalEntities(this.externalEntities);let X=Z.parseXml($);if(this.options.preserveOrder||X===void 0)return X;else return rZ(X,this.options)}addEntity($,J){if(J.indexOf("&")!==-1)throw Error("Entity value can't have '&'");else if($.indexOf("&")!==-1||$.indexOf(";")!==-1)throw Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");else if(J==="&")throw Error("An entity with value '&' is not permitted");else this.externalEntities[$]=J}static getMetaDataSymbol(){return i0.getMetaDataSymbol()}}m0();var BQ=new HJ,LQ={name:"parser",enable:!0,deps:["auth"],handler:async($,J)=>{if(!J.api)return;if(J.api.rawBody){J.body={};return}if(J.req.method==="GET"){let Z=new URL(J.req.url),X=Object.fromEntries(Z.searchParams);if(o(J.api.fields)&&!OJ(J.api.fields))J.body=_J(X,Object.keys(J.api.fields));else J.body=X}else if(J.req.method==="POST"){let Z=J.req.headers.get("content-type")||"",X=new URL(J.req.url),Y=Object.fromEntries(X.searchParams);try{if(Z.includes("application/json")){let G=await J.req.json(),H={...Y,...G};if(o(J.api.fields)&&!OJ(J.api.fields))J.body=_J(H,Object.keys(J.api.fields));else J.body=H}else if(Z.includes("application/xml")||Z.includes("text/xml")){let G=await J.req.text(),H=BQ.parse(G),z=Object.keys(H)[0],V=z&&typeof H[z]==="object"?H[z]:H,O={...Y,...V};if(o(J.api.fields)&&!OJ(J.api.fields))J.body=_J(O,Object.keys(J.api.fields));else J.body=O}else{J.response=q$(J,"\u65E0\u6548\u7684\u8BF7\u6C42\u53C2\u6570\u683C\u5F0F",1,null,{location:"content-type",value:Z},"parser");return}}catch{J.response=q$(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}}}},SY=LQ;a();var SQ={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=q$(J,"\u672A\u767B\u5F55",1,null,null,"auth");return}if(J.user.roleCode==="dev")return;let Z=J.route,X=J.user.roleCode,Y=!1;if(X&&$.redis)try{let G=X0.roleApis(X);Y=await $.redis.sismember(G,Z)}catch(G){P.error({event:"hook_permission_redis_error",apiPath:Z,roleCode:X,err:G,msg:"hook permission redis error"}),Y=!1}if(!Y){let G=typeof J.api.name==="string"&&J.api.name.length>0?J.api.name:null,H=typeof Z==="string"&&Z.length>0?Z:null,z=G?G:H?H:"\u672A\u77E5\u63A5\u53E3";J.response=q$(J,`\u65E0\u6743\u8BBF\u95EE ${z} \u63A5\u53E3`,1,null,{apiLabel:z},"permission");return}}},CY=SQ;var iZ={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:".+"},EY=new Map;function CQ($){if($.startsWith("@")){let J=$.slice(1);return iZ[J]||$}return $}function wY($,J){let Z=CQ($),X=`${Z}:${J||""}`,Y=EY.get(X);if(!Y)Y=new RegExp(Z,J),EY.set(X,Y);return Y}class tZ{static validate($,J,Z=[]){let X={};if(!$||typeof $!=="object"||Array.isArray($))return this.buildResult({_error:"\u6570\u636E\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F"});if(!J||typeof J!=="object")return this.buildResult({_error:"\u9A8C\u8BC1\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F"});for(let Y of Z){let G=$[Y];if(G===void 0||G===null||G===""){let H=J[Y]?.name||Y;X[Y]=`${H}\u4E3A\u5FC5\u586B\u9879`}}for(let[Y,G]of Object.entries(J)){if(X[Y])continue;if($[Y]===void 0&&!Z.includes(Y))continue;let H=this.checkField($[Y],G,Y);if(H)X[Y]=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 Y=this.convert($,Z);if(Y.error)return{value:null,error:Y.error};let G=this.checkRule(Y.value,J);if(G)return{value:null,error:G};return{value:Y.value,error:null}}static buildResult($){let J=Object.values($),Z=Object.keys($),X=J.length>0;return{code:X?1:0,failed:X,firstError:X?J[0]:null,errors:J,errorFields:Z,fieldErrors:$}}static checkField($,J,Z){let X=J.name||Z,Y=this.convert($,J.type);if(Y.error)return`${X}${Y.error}`;let G=this.checkRule(Y.value,J);return G?`${X}${G}`:null}static convert($,J){switch(J.toLowerCase()){case"number":if(typeof $==="number")return Number.isNaN($)||!isFinite($)?{value:null,error:"\u5FC5\u987B\u662F\u6709\u6548\u6570\u5B57"}:{value:$,error:null};if(typeof $==="string"){let Z=Number($);return Number.isNaN(Z)||!isFinite(Z)?{value:null,error:"\u5FC5\u987B\u662F\u6570\u5B57"}:{value:Z,error:null}}return{value:null,error:"\u5FC5\u987B\u662F\u6570\u5B57"};case"string":case"text":return typeof $==="string"?{value:$,error:null}:{value:null,error:"\u5FC5\u987B\u662F\u5B57\u7B26\u4E32"};case"array_string":case"array_text":return Array.isArray($)?{value:$,error:null}:{value:null,error:"\u5FC5\u987B\u662F\u6570\u7EC4"};case"array_number_string":case"array_number_text":if(!Array.isArray($))return{value:null,error:"\u5FC5\u987B\u662F\u6570\u7EC4"};for(let Z of $)if(typeof Z!=="number"||!isFinite(Z))return{value:null,error:"\u6570\u7EC4\u5143\u7D20\u5FC5\u987B\u662F\u6570\u5B57"};return{value:$,error:null};default:return{value:$,error:null}}}static checkRule($,J){let{type:Z,min:X,max:Y,regexp:G}=J,H=this.resolveRegex(G);switch(Z.toLowerCase()){case"number":if(X!==null&&$<X)return`\u4E0D\u80FD\u5C0F\u4E8E${X}`;if(Y!==null&&Y>0&&$>Y)return`\u4E0D\u80FD\u5927\u4E8E${Y}`;if(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(Y!==null&&Y>0&&$.length>Y)return`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7${Y}\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(Y!==null&&Y>0&&$.length>Y)return`\u6700\u591A\u53EA\u80FD\u6709${Y}\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 iZ[J]||$}return $}static testRegex($,J){try{return wY($).test(J)}catch{return!1}}static defaultFor($,J){if(J!==null&&J!==void 0){if(($==="array_string"||$==="array_text"||$==="array_number_string"||$==="array_number_text")&&typeof J==="string"){if(J==="[]")return[];try{let Z=JSON.parse(J);return Array.isArray(Z)?Z:[]}catch{return[]}}if($==="number"&&typeof J==="string"){let Z=Number(J);return isNaN(Z)?0:Z}return J}switch($.toLowerCase()){case"number":return 0;case"array_string":case"array_text":case"array_number_string":case"array_number_text":return[];default:return""}}}var EQ={name:"validator",enable:!0,deps:["parser"],handler:async($,J)=>{if(!J.api)return;if(!J.api.fields)return;for(let[X,Y]of Object.entries(J.api.fields))if(J.body[X]===void 0&&Y?.default!==void 0&&Y?.default!==null)J.body[X]=Y.default;let Z=tZ.validate(J.body,J.api.fields,J.api.required||[]);if(Z.code!==0){J.response=q$(J,Z.firstError||"\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25",1,null,Z.fieldErrors,"validator");return}}},TY=EQ;a();class aZ{db;redis;constructor($){this.db=$.db,this.redis=$.redis}assertApiPathname($,J){if(typeof $!=="string")throw Error(`${J} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32`);let Z=$.trim();if(!Z)throw Error(`${J} \u4E0D\u5141\u8BB8\u4E3A\u7A7A\u5B57\u7B26\u4E32`);if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(Z))throw Error(`${J} \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09`);if(!Z.startsWith("/"))throw Error(`${J} \u5FC5\u987B\u662F pathname\uFF08\u4EE5 / \u5F00\u5934\uFF09`);if(Z.includes(" "))throw Error(`${J} \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C`);return Z}assertApiPathList($,J){if($===null||$===void 0)return[];let Z=$;if(typeof Z==="string"){let Y=Z.trim();if(Y===""||Y==="null")return[];if(Y.startsWith("[")&&Y.endsWith("]"))try{Z=JSON.parse(Y)}catch{throw Error(`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis JSON \u89E3\u6790\u5931\u8D25\uFF0CroleCode=${J}`)}}if(!Array.isArray(Z))throw Error(`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\u6216 JSON \u6570\u7EC4\u5B57\u7B26\u4E32\uFF0CroleCode=${J}\uFF0Ctype=${typeof Z}`);let X=[];for(let Y of Z)X.push(this.assertApiPathname(Y,`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5143\u7D20\uFF0CroleCode=${J}`));return X}async cacheApis(){try{if(!(await this.db.tableExists("addon_admin_api")).data){P.warn("\u26A0\uFE0F \u63A5\u53E3\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u63A5\u53E3\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_api"});if(await this.redis.setObject(X0.apisAll(),J.data.lists)===null)P.warn("\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5931\u8D25")}catch($){P.error({err:$,msg:"\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5F02\u5E38"})}}async cacheMenus(){try{if(!(await this.db.tableExists("addon_admin_menu")).data){P.warn("\u26A0\uFE0F \u83DC\u5355\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u83DC\u5355\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_menu"});if(await this.redis.setObject(X0.menusAll(),J.data.lists)===null)P.warn("\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5931\u8D25")}catch($){P.warn({err:$,msg:"\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5F02\u5E38"})}}async rebuildRoleApiPermissions(){try{if(!(await this.db.tableExists("addon_admin_role")).data){P.warn("\u26A0\uFE0F \u89D2\u8272\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u89D2\u8272\u6743\u9650\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_role",fields:["code","apis"]}),Z=new Map;for(let 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){P.info("\u2705 \u6CA1\u6709\u9700\u8981\u7F13\u5B58\u7684\u89D2\u8272\u6743\u9650");return}let Y=X.map((H)=>X0.roleApis(H));await this.redis.delBatch(Y);let G=[];for(let H of X){let z=Z.get(H)||[],V=Array.from(new Set(z)).sort();if(V.length>0)G.push({key:X0.roleApis(H),members:V})}if(G.length>0)await this.redis.saddBatch(G)}catch($){throw P.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((G)=>this.assertApiPathname(G,`refreshRoleApiPermissions: apiPaths \u5143\u7D20\uFF0CroleCode=${$}`)),X=X0.roleApis($);if(Z.length===0){await this.redis.del(X);return}let Y=Array.from(new Set(Z));if(await this.redis.del(X),Y.length>0)await this.redis.sadd(X,Y)}async cacheAll(){await this.cacheApis(),await this.cacheMenus(),await this.rebuildRoleApiPermissions()}async getApis(){try{return await this.redis.getObject(X0.apisAll())||[]}catch($){return P.error({err:$,msg:"\u83B7\u53D6\u63A5\u53E3\u7F13\u5B58\u5931\u8D25"}),[]}}async getMenus(){try{return await this.redis.getObject(X0.menusAll())||[]}catch($){return P.error({err:$,msg:"\u83B7\u53D6\u83DC\u5355\u7F13\u5B58\u5931\u8D25"}),[]}}async getRolePermissions($){try{return await this.redis.smembers(X0.roleApis($))||[]}catch(J){return P.error({err:J,roleCode:$,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 P.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 P.info(`\u2705 \u5DF2\u5220\u9664\u89D2\u8272 ${$} \u7684\u6743\u9650\u7F13\u5B58`),!0;return!1}catch(J){return P.error({err:J,roleCode:$,msg:"\u5220\u9664\u89D2\u8272\u6743\u9650\u7F13\u5B58\u5931\u8D25"}),!1}}}var wQ={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 aZ({db:$.db,redis:$.redis})}},vY=wQ;var TQ={name:"cipher",enable:!0,deps:[],handler:()=>{return y$}},NY=TQ;var vQ={name:"config",enable:!0,deps:[],handler:($)=>{return $.config}},DY=vQ;function xJ($,J=["id","pid","sort"]){if(!$||!Array.isArray($))return $;return $.map((Z)=>{let X={};for(let[Y,G]of Object.entries(Z))X[Y]=G;for(let[Y,G]of Object.entries(X)){if(G===void 0||G===null)continue;if((J.includes(Y)||Y.endsWith("Id")||Y.endsWith("_id")||Y.endsWith("At")||Y.endsWith("_at"))&&typeof G==="string"){let z=Number(G);if(!isNaN(z))X[Y]=z}}return X})}function eZ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function NQ($){return Array.isArray($)}function w$($,J={}){let{pickKeys:Z,omitKeys:X,keepValues:Y,excludeValues:G,keepMap:H}=J,z=(V)=>{let O={},F=Object.keys(V);if(Z&&Z.length)F=F.filter((I)=>Z.includes(I));if(X&&X.length)F=F.filter((I)=>!X.includes(I));for(let I of F){let B=V[I];if(H&&I in H){if(Object.is(H[I],B)){O[I]=B;continue}}if(Y&&Y.length&&!Y.includes(B))continue;if(G&&G.length&&G.includes(B))continue;O[I]=B}return O};if(NQ($))return $.map((V)=>eZ(V)?z(V):V).filter((V)=>{if(eZ(V))return Object.keys(V).length>0;return!0});if(eZ($))return z($);return $}m0();m0();class g{static parseTableRef($){if(typeof $!=="string")throw Error(`tableRef \u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (tableRef: ${String($)})`);let J=$.trim();if(!J)throw Error("tableRef \u4E0D\u80FD\u4E3A\u7A7A");let Z=J.split(/\s+/).filter((V)=>V.length>0);if(Z.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08\u5305\u542B\u8FC7\u591A\u7247\u6BB5\uFF09\u3002\u8BF7\u4F7F\u7528\u6700\u7B80\u5F62\u5F0F\uFF1Atable \u6216 table alias \u6216 schema.table \u6216 schema.table alias (tableRef: ${J})`);let X=Z[0],Y=Z.length===2?Z[1]:null,G=X.split(".");if(G.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09 (tableRef: ${J})`);let H=G.length===2?G[0]:null,z=G.length===2?G[1]:G[0];return{schema:H,table:z,alias:Y}}static normalizeTableRef($){let J=g.parseTableRef($),Z=J.schema?u(J.schema):null,X=u(J.table),Y=Z?`${Z}.${X}`:X;if(J.alias)Y=`${Y} ${J.alias}`;return Y}static getJoinMainQualifier($){let J=g.parseTableRef($);if(J.alias)return J.alias;return u(J.table)}static async fieldsToSnake($,J,Z){if(!J||!Array.isArray(J))return["*"];let X=g.validateAndClassifyFields(J);if(X.type==="all")return["*"];if(X.type==="include")return X.fields.map((Y)=>{if(Y.includes("(")||Y.includes(" "))return Y;return u(Y)});if(X.type==="exclude"){let Y=await Z($),G=X.fields.map((z)=>u(z)),H=Y.filter((z)=>!G.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: ${G.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((Y)=>Y.substring(1))};throw Error(`fields \u4E0D\u80FD\u540C\u65F6\u5305\u542B\u666E\u901A\u5B57\u6BB5\u548C\u6392\u9664\u5B57\u6BB5\uFF08! \u5F00\u5934\uFF09\u3002\u53EA\u80FD\u4F7F\u7528\u4EE5\u4E0B3\u79CD\u65B9\u5F0F\u4E4B\u4E00\uFF1A
|
|
14
|
+
`||$==="\r"}function IY($,J){let Z=J;for(;J<$.length;J++)if($[J]=="?"||$[J]==" "){let X=$.substr(Z,J-Z);if(J>5&&X==="xml")return G0("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 qY($,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 sH='"',oH="'";function lH($,J){let Z="",X="",Y=!1;for(;J<$.length;J++){if($[J]===sH||$[J]===oH)if(X==="")X=$[J];else if(X!==$[J]);else X="";else if($[J]===">"){if(X===""){Y=!0;break}}Z+=$[J]}if(X!=="")return!1;return{value:Z,index:J,tagClosed:Y}}var rH=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function PY($,J){let Z=NJ($,rH),X={};for(let Y=0;Y<Z.length;Y++){if(Z[Y][1].length===0)return G0("InvalidAttr","Attribute '"+Z[Y][2]+"' has no space in starting.",GJ(Z[Y]));else if(Z[Y][3]!==void 0&&Z[Y][4]===void 0)return G0("InvalidAttr","Attribute '"+Z[Y][2]+"' is without value.",GJ(Z[Y]));else if(Z[Y][3]===void 0&&!J.allowBooleanAttributes)return G0("InvalidAttr","boolean attribute '"+Z[Y][2]+"' is not allowed.",GJ(Z[Y]));let G=Z[Y][2];if(!aH(G))return G0("InvalidAttr","Attribute '"+G+"' is an invalid name.",GJ(Z[Y]));if(!X.hasOwnProperty(G))X[G]=1;else return G0("InvalidAttr","Attribute '"+G+"' is repeated.",GJ(Z[Y]))}return!0}function iH($,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 tH($,J){if(J++,$[J]===";")return-1;if($[J]==="#")return J++,iH($,J);let Z=0;for(;J<$.length;J++,Z++){if($[J].match(/\w/)&&Z<20)continue;if($[J]===";")break;return-1}return J}function G0($,J,Z){return{err:{code:$,msg:J,line:Z.line||Z,col:Z.col}}}function aH($){return g$($)}function eH($){return g$($)}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 $Q={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},BY=function($){return Object.assign({},$Q,$)};var DJ;if(typeof Symbol!=="function")DJ="@@xmlMetadata";else DJ=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][DJ]={startIndex:J}}static getMetaDataSymbol(){return DJ}}class kJ{constructor($){this.suppressValidationErr=!$}readDocType($,J){let Z={};if($[J+3]==="O"&&$[J+4]==="C"&&$[J+5]==="T"&&$[J+6]==="Y"&&$[J+7]==="P"&&$[J+8]==="E"){J=J+9;let X=1,Y=!1,G=!1,H="";for(;J<$.length;J++)if($[J]==="<"&&!G){if(Y&&C$($,"!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(Y&&C$($,"!ELEMENT",J)){J+=8;let{index:z}=this.readElementExp($,J+1);J=z}else if(Y&&C$($,"!ATTLIST",J))J+=8;else if(Y&&C$($,"!NOTATION",J)){J+=9;let{index:z}=this.readNotationExp($,J+1,this.suppressValidationErr);J=z}else if(C$($,"!--",J))G=!0;else throw Error("Invalid DOCTYPE");X++,H=""}else if($[J]===">"){if(G){if($[J-1]==="-"&&$[J-2]==="-")G=!1,X--}else X--;if(X===0)break}else if($[J]==="[")Y=!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(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 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&&WJ(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 Y=null,G=null;if(X==="PUBLIC"){if([J,Y]=this.readIdentifierVal($,J,"publicIdentifier"),J=l0($,J),$[J]==='"'||$[J]==="'")[J,G]=this.readIdentifierVal($,J,"systemIdentifier")}else if(X==="SYSTEM"){if([J,G]=this.readIdentifierVal($,J,"systemIdentifier"),!this.suppressValidationErr&&!G)throw Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:Z,publicIdentifier:Y,systemIdentifier:G,index:--J}}readIdentifierVal($,J,Z){let X="",Y=$[J];if(Y!=='"'&&Y!=="'")throw Error(`Expected quoted string, found "${Y}"`);J++;while(J<$.length&&$[J]!==Y)X+=$[J],J++;if($[J]!==Y)throw Error(`Unterminated ${Z} value`);return J++,[J,X]}readElementExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;if(!this.suppressValidationErr&&!g$(Z))throw Error(`Invalid element name: "${Z}"`);J=l0($,J);let X="";if($[J]==="E"&&C$($,"MPTY",J))J+=4;else if($[J]==="A"&&C$($,"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++;WJ(Z),J=l0($,J);let X="";while(J<$.length&&!/\s/.test($[J]))X+=$[J],J++;if(!WJ(X))throw Error(`Invalid attribute name: "${X}"`);J=l0($,J);let Y="";if($.substring(J,J+8).toUpperCase()==="NOTATION"){if(Y="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(),!WJ(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++,Y+=" ("+H.join("|")+")"}else{while(J<$.length&&!/\s/.test($[J]))Y+=$[J],J++;let H=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!H.includes(Y.toUpperCase()))throw Error(`Invalid attribute type: "${Y}"`)}J=l0($,J);let G="";if($.substring(J,J+8).toUpperCase()==="#REQUIRED")G="#REQUIRED",J+=8;else if($.substring(J,J+7).toUpperCase()==="#IMPLIED")G="#IMPLIED",J+=7;else[J,G]=this.readIdentifierVal($,J,"ATTLIST");return{elementName:Z,attributeName:X,attributeType:Y,defaultValue:G,index:J}}}var l0=($,J)=>{while(J<$.length&&/\s/.test($[J]))J++;return J};function C$($,J,Z){for(let X=0;X<J.length;X++)if(J[X]!==$[Z+X+1])return!1;return!0}function WJ($){if(g$($))return $;else throw Error(`Invalid entity name ${$}`)}var JQ=/^[-+]?0x[a-fA-F0-9]+$/,ZQ=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,XQ={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function dZ($,J={}){if(J=Object.assign({},XQ,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&&JQ.test(Z))return HQ(Z,16);else if(Z.includes("e")||Z.includes("E"))return GQ($,Z,J);else{let X=ZQ.exec(Z);if(X){let Y=X[1]||"",G=X[2],H=WQ(X[3]),z=Y?$[G.length+1]===".":$[G.length]===".";if(!J.leadingZeros&&(G.length>1||G.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===`${Y}${H}`)return V;else return $;let F=G?H:Z;if(G)return F===O||Y+F===O?V:$;else return F===O||F===Y+O?V:$}}else return $}}var YQ=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function GQ($,J,Z){if(!Z.eNotation)return $;let X=J.match(YQ);if(X){let Y=X[1]||"",G=X[3].indexOf("e")===-1?"E":"e",H=X[2],z=Y?$[H.length+1]===G:$[H.length]===G;if(H.length>1&&z)return $;else if(H.length===1&&(X[3].startsWith(`.${G}`)||X[3][0]===G))return Number(J);else if(Z.leadingZeros&&!z)return J=(X[1]||"")+X[3],Number(J);else return $}else return $}function WQ($){if($&&$.indexOf(".")!==-1){if($=$.replace(/0+$/,""),$===".")$="0";else if($[0]===".")$="0"+$;else if($[$.length-1]===".")$=$.substring(0,$.length-1);return $}return $}function HQ($,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 nZ($){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 yJ{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=QQ,this.parseXml=_Q,this.parseTextData=zQ,this.resolveNameSpace=UQ,this.buildAttributesMap=OQ,this.isItStopNode=MQ,this.replaceEntitiesValue=KQ,this.readStopNodeData=IQ,this.saveTextToParentTag=FQ,this.addChild=AQ,this.ignoreAttributesFn=nZ(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 QQ($){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 zQ($,J,Z,X,Y,G,H){if($!==void 0){if(this.options.trimValues&&!X)$=$.trim();if($.length>0){if(!H)$=this.replaceEntitiesValue($);let z=this.options.tagValueProcessor(J,$,Z,Y,G);if(z===null||z===void 0)return $;else if(typeof z!==typeof $||z!==$)return z;else if(this.options.trimValues)return oZ($,this.options.parseTagValue,this.options.numberParseOptions);else if($.trim()===$)return oZ($,this.options.parseTagValue,this.options.numberParseOptions);else return $}}}function UQ($){if(this.options.removeNSPrefix){let J=$.split(":"),Z=$.charAt(0)==="/"?"/":"";if(J[0]==="xmlns")return"";if(J.length===2)$=Z+J[1]}return $}var VQ=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function OQ($,J){if(this.options.ignoreAttributes!==!0&&typeof $==="string"){let Z=NJ($,VQ),X=Z.length,Y={};for(let G=0;G<X;G++){let H=this.resolveNameSpace(Z[G][1]);if(this.ignoreAttributesFn(H,J))continue;let z=Z[G][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)Y[V]=z;else if(typeof O!==typeof z||O!==z)Y[V]=O;else Y[V]=oZ(z,this.options.parseAttributeValue,this.options.numberParseOptions)}else if(this.options.allowBooleanAttributes)Y[V]=!0}}if(!Object.keys(Y).length)return;if(this.options.attributesGroupName){let G={};return G[this.options.attributesGroupName]=Y,G}return Y}}var _Q=function($){$=$.replace(/\r\n?/g,`
|
|
15
|
+
`);let J=new i0("!xml"),Z=J,X="",Y="",G=new kJ(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,Y);let F=Y.substring(Y.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(F&&this.options.unpairedTags.indexOf(F)!==-1)I=Y.lastIndexOf(".",Y.lastIndexOf(".")-1),this.tagsNodeStack.pop();else I=Y.lastIndexOf(".");Y=Y.substring(0,I),Z=this.tagsNodeStack.pop(),X="",H=V}else if($[H+1]==="?"){let V=sZ($,H,!1,"?>");if(!V)throw Error("Pi Tag is not closed.");if(X=this.saveTextToParentTag(X,Z,Y),this.options.ignoreDeclaration&&V.tagName==="?xml"||this.options.ignorePiTags);else{let O=new i0(V.tagName);if(O.add(this.options.textNodeName,""),V.tagName!==V.tagExp&&V.attrExpPresent)O[":@"]=this.buildAttributesMap(V.tagExp,Y);this.addChild(Z,O,Y,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,Y),Z.add(this.options.commentPropName,[{[this.options.textNodeName]:O}])}H=V}else if($.substr(H+1,2)==="!D"){let V=G.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,Y);let F=this.parseTextData(O,Z.tagname,Y,!0,!1,!0,!0);if(F==null)F="";if(this.options.cdataPropName)Z.add(this.options.cdataPropName,[{[this.options.textNodeName]:O}]);else Z.add(this.options.textNodeName,F);H=V+2}else{let V=sZ($,H,this.options.removeNSPrefix),O=V.tagName,F=V.rawTagName,I=V.tagExp,B=V.attrExpPresent,L=V.closeIndex;if(this.options.transformTagName){let T=this.options.transformTagName(O);if(I===O)I=T;O=T}if(Z&&X){if(Z.tagname!=="!xml")X=this.saveTextToParentTag(X,Z,Y,!1)}let C=Z;if(C&&this.options.unpairedTags.indexOf(C.tagname)!==-1)Z=this.tagsNodeStack.pop(),Y=Y.substring(0,Y.lastIndexOf("."));if(O!==J.tagname)Y+=Y?"."+O:O;let w=H;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,Y,O)){let T="";if(I.length>0&&I.lastIndexOf("/")===I.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),Y=Y.substr(0,Y.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 E=this.readStopNodeData($,F,L+1);if(!E)throw Error(`Unexpected end of ${F}`);H=E.i,T=E.tagContent}let N=new i0(O);if(O!==I&&B)N[":@"]=this.buildAttributesMap(I,Y);if(T)T=this.parseTextData(T,O,Y,!0,B,!0,!0);Y=Y.substr(0,Y.lastIndexOf(".")),N.add(this.options.textNodeName,T),this.addChild(Z,N,Y,w)}else{if(I.length>0&&I.lastIndexOf("/")===I.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),Y=Y.substr(0,Y.length-1),I=O;else I=I.substr(0,I.length-1);if(this.options.transformTagName){let N=this.options.transformTagName(O);if(I===O)I=N;O=N}let T=new i0(O);if(O!==I&&B)T[":@"]=this.buildAttributesMap(I,Y);this.addChild(Z,T,Y,w),Y=Y.substr(0,Y.lastIndexOf("."))}else{let T=new i0(O);if(this.tagsNodeStack.push(Z),O!==I&&B)T[":@"]=this.buildAttributesMap(I,Y);this.addChild(Z,T,Y,w),Z=T}X="",H=L}}else X+=$[H];return J.child};function AQ($,J,Z,X){if(!this.options.captureMetaData)X=void 0;let Y=this.options.updateTag(J.tagname,Z,J[":@"]);if(Y===!1);else if(typeof Y==="string")J.tagname=Y,$.addChild(J,X);else $.addChild(J,X)}var KQ=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 FQ($,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 MQ($,J,Z,X){if(J&&J.has(X))return!0;if($&&$.has(Z))return!0;return!1}function RQ($,J,Z=">"){let X,Y="";for(let G=J;G<$.length;G++){let H=$[G];if(X){if(H===X)X=""}else if(H==='"'||H==="'")X=H;else if(H===Z[0])if(Z[1]){if($[G+1]===Z[1])return{data:Y,index:G}}else return{data:Y,index:G};else if(H==="\t")H=" ";Y+=H}}function E$($,J,Z,X){let Y=$.indexOf(J,Z);if(Y===-1)throw Error(X);else return Y+J.length-1}function sZ($,J,Z,X=">"){let Y=RQ($,J+1,X);if(!Y)return;let{data:G,index:H}=Y,z=G.search(/\s/),V=G,O=!0;if(z!==-1)V=G.substring(0,z),G=G.substring(z+1).trimStart();let F=V;if(Z){let I=V.indexOf(":");if(I!==-1)V=V.substr(I+1),O=V!==Y.data.substr(I+1)}return{tagName:V,tagExp:G,closeIndex:H,attrExpPresent:O,rawTagName:F}}function IQ($,J,Z){let X=Z,Y=1;for(;Z<$.length;Z++)if($[Z]==="<")if($[Z+1]==="/"){let G=E$($,">",Z,`${J} is not closed`);if($.substring(Z+2,G).trim()===J){if(Y--,Y===0)return{tagContent:$.substring(X,Z),i:G}}Z=G}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 G=sZ($,Z,">");if(G){if((G&&G.tagName)===J&&G.tagExp[G.tagExp.length-1]!=="/")Y++;Z=G.closeIndex}}}function oZ($,J,Z){if(J&&typeof $==="string"){let X=$.trim();if(X==="true")return!0;else if(X==="false")return!1;else return dZ($,Z)}else if(MY($))return $;else return""}var lZ=i0.getMetaDataSymbol();function rZ($,J){return LY($,J)}function LY($,J,Z){let X,Y={};for(let G=0;G<$.length;G++){let H=$[G],z=qQ(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=LY(H[z],J,V),F=jQ(O,J);if(H[lZ]!==void 0)O[lZ]=H[lZ];if(H[":@"])PQ(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(Y[z]!==void 0&&Y.hasOwnProperty(z)){if(!Array.isArray(Y[z]))Y[z]=[Y[z]];Y[z].push(O)}else if(J.isArray(z,V,F))Y[z]=[O];else Y[z]=O}}if(typeof X==="string"){if(X.length>0)Y[J.textNodeName]=X}else if(X!==void 0)Y[J.textNodeName]=X;return Y}function qQ($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X!==":@")return X}}function PQ($,J,Z,X){if(J){let Y=Object.keys(J),G=Y.length;for(let H=0;H<G;H++){let z=Y[H];if(X.isArray(z,Z+"."+z,!0,!0))$[z]=[J[z]];else $[z]=J[z]}}}function jQ($,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 HJ{constructor($){this.externalEntities={},this.options=BY($)}parse($,J){if(typeof $!=="string"&&$.toString)$=$.toString();else if(typeof $!=="string")throw Error("XML data is accepted in String or Bytes[] form.");if(J){if(J===!0)J={};let Y=jY($,J);if(Y!==!0)throw Error(`${Y.err.msg}:${Y.err.line}:${Y.err.col}`)}let Z=new yJ(this.options);Z.addExternalEntities(this.externalEntities);let X=Z.parseXml($);if(this.options.preserveOrder||X===void 0)return X;else return rZ(X,this.options)}addEntity($,J){if(J.indexOf("&")!==-1)throw Error("Entity value can't have '&'");else if($.indexOf("&")!==-1||$.indexOf(";")!==-1)throw Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");else if(J==="&")throw Error("An entity with value '&' is not permitted");else this.externalEntities[$]=J}static getMetaDataSymbol(){return i0.getMetaDataSymbol()}}m0();var BQ=new HJ,LQ={name:"parser",enable:!0,deps:["auth"],handler:async($,J)=>{if(!J.api)return;if(J.api.rawBody){J.body={};return}if(J.req.method==="GET"){let Z=new URL(J.req.url),X=Object.fromEntries(Z.searchParams);if(o(J.api.fields)&&!OJ(J.api.fields))J.body=_J(X,Object.keys(J.api.fields));else J.body=X}else if(J.req.method==="POST"){let Z=J.req.headers.get("content-type")||"",X=new URL(J.req.url),Y=Object.fromEntries(X.searchParams);try{if(Z.includes("application/json")){let G=await J.req.json(),H={...Y,...G};if(o(J.api.fields)&&!OJ(J.api.fields))J.body=_J(H,Object.keys(J.api.fields));else J.body=H}else if(Z.includes("application/xml")||Z.includes("text/xml")){let G=await J.req.text(),H=BQ.parse(G),z=Object.keys(H)[0],V=z&&typeof H[z]==="object"?H[z]:H,O={...Y,...V};if(o(J.api.fields)&&!OJ(J.api.fields))J.body=_J(O,Object.keys(J.api.fields));else J.body=O}else{J.response=q$(J,"\u65E0\u6548\u7684\u8BF7\u6C42\u53C2\u6570\u683C\u5F0F",1,null,{location:"content-type",value:Z},"parser");return}}catch{J.response=q$(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}}}},SY=LQ;a();var SQ={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=q$(J,"\u672A\u767B\u5F55",1,null,null,"auth");return}if(J.user.roleCode==="dev")return;let Z=J.route,X=J.user.roleCode,Y=!1;if(X&&$.redis)try{let G=X0.roleApis(X);Y=await $.redis.sismember(G,Z)}catch(G){P.error({event:"hook_permission_redis_error",apiPath:Z,roleCode:X,err:G,msg:"hook permission redis error"}),Y=!1}if(!Y){let G=typeof J.api.name==="string"&&J.api.name.length>0?J.api.name:null,H=typeof Z==="string"&&Z.length>0?Z:null,z=G?G:H?H:"\u672A\u77E5\u63A5\u53E3";J.response=q$(J,`\u65E0\u6743\u8BBF\u95EE ${z} \u63A5\u53E3`,1,null,{apiLabel:z},"permission");return}}},CY=SQ;var iZ={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:".+"},EY=new Map;function CQ($){if($.startsWith("@")){let J=$.slice(1);return iZ[J]||$}return $}function wY($,J){let Z=CQ($),X=`${Z}:${J||""}`,Y=EY.get(X);if(!Y)Y=new RegExp(Z,J),EY.set(X,Y);return Y}class tZ{static validate($,J,Z=[]){let X={};if(!$||typeof $!=="object"||Array.isArray($))return this.buildResult({_error:"\u6570\u636E\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F"});if(!J||typeof J!=="object")return this.buildResult({_error:"\u9A8C\u8BC1\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F"});for(let Y of Z){let G=$[Y];if(G===void 0||G===null||G===""){let H=J[Y]?.name||Y;X[Y]=`${H}\u4E3A\u5FC5\u586B\u9879`}}for(let[Y,G]of Object.entries(J)){if(X[Y])continue;if($[Y]===void 0&&!Z.includes(Y))continue;let H=this.checkField($[Y],G,Y);if(H)X[Y]=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 Y=this.convert($,Z);if(Y.error)return{value:null,error:Y.error};let G=this.checkRule(Y.value,J);if(G)return{value:null,error:G};return{value:Y.value,error:null}}static buildResult($){let J=Object.values($),Z=Object.keys($),X=J.length>0;return{code:X?1:0,failed:X,firstError:X?J[0]:null,errors:J,errorFields:Z,fieldErrors:$}}static checkField($,J,Z){let X=J.name||Z,Y=this.convert($,J.type);if(Y.error)return`${X}${Y.error}`;let G=this.checkRule(Y.value,J);return G?`${X}${G}`:null}static convert($,J){switch(J.toLowerCase()){case"number":if(typeof $==="number")return Number.isNaN($)||!isFinite($)?{value:null,error:"\u5FC5\u987B\u662F\u6709\u6548\u6570\u5B57"}:{value:$,error:null};if(typeof $==="string"){let Z=Number($);return Number.isNaN(Z)||!isFinite(Z)?{value:null,error:"\u5FC5\u987B\u662F\u6570\u5B57"}:{value:Z,error:null}}return{value:null,error:"\u5FC5\u987B\u662F\u6570\u5B57"};case"string":case"text":return typeof $==="string"?{value:$,error:null}:{value:null,error:"\u5FC5\u987B\u662F\u5B57\u7B26\u4E32"};case"array_string":case"array_text":return Array.isArray($)?{value:$,error:null}:{value:null,error:"\u5FC5\u987B\u662F\u6570\u7EC4"};case"array_number_string":case"array_number_text":if(!Array.isArray($))return{value:null,error:"\u5FC5\u987B\u662F\u6570\u7EC4"};for(let Z of $)if(typeof Z!=="number"||!isFinite(Z))return{value:null,error:"\u6570\u7EC4\u5143\u7D20\u5FC5\u987B\u662F\u6570\u5B57"};return{value:$,error:null};default:return{value:$,error:null}}}static checkRule($,J){let{type:Z,min:X,max:Y,regexp:G}=J,H=this.resolveRegex(G);switch(Z.toLowerCase()){case"number":if(X!==null&&$<X)return`\u4E0D\u80FD\u5C0F\u4E8E${X}`;if(Y!==null&&Y>0&&$>Y)return`\u4E0D\u80FD\u5927\u4E8E${Y}`;if(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(Y!==null&&Y>0&&$.length>Y)return`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7${Y}\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(Y!==null&&Y>0&&$.length>Y)return`\u6700\u591A\u53EA\u80FD\u6709${Y}\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 iZ[J]||$}return $}static testRegex($,J){try{return wY($).test(J)}catch{return!1}}static defaultFor($,J){if(J!==null&&J!==void 0){if(($==="array_string"||$==="array_text"||$==="array_number_string"||$==="array_number_text")&&typeof J==="string"){if(J==="[]")return[];try{let Z=JSON.parse(J);return Array.isArray(Z)?Z:[]}catch{return[]}}if($==="number"&&typeof J==="string"){let Z=Number(J);return isNaN(Z)?0:Z}return J}switch($.toLowerCase()){case"number":return 0;case"array_string":case"array_text":case"array_number_string":case"array_number_text":return[];default:return""}}}var EQ={name:"validator",enable:!0,deps:["parser"],handler:async($,J)=>{if(!J.api)return;if(!J.api.fields)return;for(let[X,Y]of Object.entries(J.api.fields))if(J.body[X]===void 0&&Y?.default!==void 0&&Y?.default!==null)J.body[X]=Y.default;let Z=tZ.validate(J.body,J.api.fields,J.api.required||[]);if(Z.code!==0){J.response=q$(J,Z.firstError||"\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25",1,null,Z.fieldErrors,"validator");return}}},TY=EQ;a();class aZ{db;redis;constructor($){this.db=$.db,this.redis=$.redis}assertApiPathname($,J){if(typeof $!=="string")throw Error(`${J} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32`);let Z=$.trim();if(!Z)throw Error(`${J} \u4E0D\u5141\u8BB8\u4E3A\u7A7A\u5B57\u7B26\u4E32`);if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(Z))throw Error(`${J} \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09`);if(!Z.startsWith("/"))throw Error(`${J} \u5FC5\u987B\u662F pathname\uFF08\u4EE5 / \u5F00\u5934\uFF09`);if(Z.includes(" "))throw Error(`${J} \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C`);return Z}assertApiPathList($,J){if($===null||$===void 0)return[];let Z=$;if(typeof Z==="string"){let Y=Z.trim();if(Y===""||Y==="null")return[];if(Y.startsWith("[")&&Y.endsWith("]"))try{Z=JSON.parse(Y)}catch{throw Error(`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis JSON \u89E3\u6790\u5931\u8D25\uFF0CroleCode=${J}`)}}if(!Array.isArray(Z))throw Error(`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\u6216 JSON \u6570\u7EC4\u5B57\u7B26\u4E32\uFF0CroleCode=${J}\uFF0Ctype=${typeof Z}`);let X=[];for(let Y of Z)X.push(this.assertApiPathname(Y,`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5143\u7D20\uFF0CroleCode=${J}`));return X}async cacheApis(){try{if(!(await this.db.tableExists("addon_admin_api")).data){P.warn("\u26A0\uFE0F \u63A5\u53E3\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u63A5\u53E3\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_api"});if(await this.redis.setObject(X0.apisAll(),J.data.lists)===null)P.warn("\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5931\u8D25")}catch($){P.error({err:$,msg:"\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5F02\u5E38"})}}async cacheMenus(){try{if(!(await this.db.tableExists("addon_admin_menu")).data){P.warn("\u26A0\uFE0F \u83DC\u5355\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u83DC\u5355\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_menu"});if(await this.redis.setObject(X0.menusAll(),J.data.lists)===null)P.warn("\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5931\u8D25")}catch($){P.warn({err:$,msg:"\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5F02\u5E38"})}}async rebuildRoleApiPermissions(){try{if(!(await this.db.tableExists("addon_admin_role")).data){P.warn("\u26A0\uFE0F \u89D2\u8272\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u89D2\u8272\u6743\u9650\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_role",fields:["code","apis"]}),Z=new Map;for(let 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){P.info("\u2705 \u6CA1\u6709\u9700\u8981\u7F13\u5B58\u7684\u89D2\u8272\u6743\u9650");return}let Y=X.map((H)=>X0.roleApis(H));await this.redis.delBatch(Y);let G=[];for(let H of X){let z=Z.get(H)||[],V=Array.from(new Set(z)).sort();if(V.length>0)G.push({key:X0.roleApis(H),members:V})}if(G.length>0)await this.redis.saddBatch(G)}catch($){throw P.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((G)=>this.assertApiPathname(G,`refreshRoleApiPermissions: apiPaths \u5143\u7D20\uFF0CroleCode=${$}`)),X=X0.roleApis($);if(Z.length===0){await this.redis.del(X);return}let Y=Array.from(new Set(Z));if(await this.redis.del(X),Y.length>0)await this.redis.sadd(X,Y)}async cacheAll(){await this.cacheApis(),await this.cacheMenus(),await this.rebuildRoleApiPermissions()}async getApis(){try{return await this.redis.getObject(X0.apisAll())||[]}catch($){return P.error({err:$,msg:"\u83B7\u53D6\u63A5\u53E3\u7F13\u5B58\u5931\u8D25"}),[]}}async getMenus(){try{return await this.redis.getObject(X0.menusAll())||[]}catch($){return P.error({err:$,msg:"\u83B7\u53D6\u83DC\u5355\u7F13\u5B58\u5931\u8D25"}),[]}}async getRolePermissions($){try{return await this.redis.smembers(X0.roleApis($))||[]}catch(J){return P.error({err:J,roleCode:$,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 P.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 P.info(`\u2705 \u5DF2\u5220\u9664\u89D2\u8272 ${$} \u7684\u6743\u9650\u7F13\u5B58`),!0;return!1}catch(J){return P.error({err:J,roleCode:$,msg:"\u5220\u9664\u89D2\u8272\u6743\u9650\u7F13\u5B58\u5931\u8D25"}),!1}}}var wQ={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 aZ({db:$.db,redis:$.redis})}},vY=wQ;var TQ={name:"cipher",enable:!0,deps:[],handler:()=>{return y$}},NY=TQ;var vQ={name:"config",enable:!0,deps:[],handler:($)=>{return $.config}},DY=vQ;function xJ($,J=["id","pid","sort"]){if(!$||!Array.isArray($))return $;return $.map((Z)=>{let X={};for(let[Y,G]of Object.entries(Z))X[Y]=G;for(let[Y,G]of Object.entries(X)){if(G===void 0||G===null)continue;if((J.includes(Y)||Y.endsWith("Id")||Y.endsWith("_id")||Y.endsWith("At")||Y.endsWith("_at"))&&typeof G==="string"){let z=Number(G);if(!isNaN(z))X[Y]=z}}return X})}function eZ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function NQ($){return Array.isArray($)}function w$($,J={}){let{pickKeys:Z,omitKeys:X,keepValues:Y,excludeValues:G,keepMap:H}=J,z=(V)=>{let O={},F=Object.keys(V);if(Z&&Z.length)F=F.filter((I)=>Z.includes(I));if(X&&X.length)F=F.filter((I)=>!X.includes(I));for(let I of F){let B=V[I];if(H&&I in H){if(Object.is(H[I],B)){O[I]=B;continue}}if(Y&&Y.length&&!Y.includes(B))continue;if(G&&G.length&&G.includes(B))continue;O[I]=B}return O};if(NQ($))return $.map((V)=>eZ(V)?z(V):V).filter((V)=>{if(eZ(V))return Object.keys(V).length>0;return!0});if(eZ($))return z($);return $}m0();m0();class g{static parseTableRef($){if(typeof $!=="string")throw Error(`tableRef \u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (tableRef: ${String($)})`);let J=$.trim();if(!J)throw Error("tableRef \u4E0D\u80FD\u4E3A\u7A7A");let Z=J.split(/\s+/).filter((V)=>V.length>0);if(Z.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08\u5305\u542B\u8FC7\u591A\u7247\u6BB5\uFF09\u3002\u8BF7\u4F7F\u7528\u6700\u7B80\u5F62\u5F0F\uFF1Atable \u6216 table alias \u6216 schema.table \u6216 schema.table alias (tableRef: ${J})`);let X=Z[0],Y=Z.length===2?Z[1]:null,G=X.split(".");if(G.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09 (tableRef: ${J})`);let H=G.length===2?G[0]:null,z=G.length===2?G[1]:G[0];return{schema:H,table:z,alias:Y}}static normalizeTableRef($){let J=g.parseTableRef($),Z=J.schema?u(J.schema):null,X=u(J.table),Y=Z?`${Z}.${X}`:X;if(J.alias)Y=`${Y} ${J.alias}`;return Y}static getJoinMainQualifier($){let J=g.parseTableRef($);if(J.alias)return J.alias;return u(J.table)}static async fieldsToSnake($,J,Z){if(!J||!Array.isArray(J))return["*"];let X=g.validateAndClassifyFields(J);if(X.type==="all")return["*"];if(X.type==="include")return X.fields.map((Y)=>{if(Y.includes("(")||Y.includes(" "))return Y;return u(Y)});if(X.type==="exclude"){let Y=await Z($),G=X.fields.map((z)=>u(z)),H=Y.filter((z)=>!G.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: ${G.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((Y)=>Y.substring(1))};throw Error(`fields \u4E0D\u80FD\u540C\u65F6\u5305\u542B\u666E\u901A\u5B57\u6BB5\u548C\u6392\u9664\u5B57\u6BB5\uFF08! \u5F00\u5934\uFF09\u3002\u53EA\u80FD\u4F7F\u7528\u4EE5\u4E0B3\u79CD\u65B9\u5F0F\u4E4B\u4E00\uFF1A
|
|
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,X]=J.split("#");return`${u(Z.trim())}#${X.trim()}`})}static processJoinField($){if($.includes("(")||$==="*"||$.startsWith("`"))return $;if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i),Z=J[0].trim(),X=J[1].trim();return`${g.processJoinField(Z)} AS ${X}`}if($.includes(".")){let J=$.split("."),Z=J[0],X=J[1];return`${Z.trim()}.${u(X)}`}return u($)}static processJoinWhereKey($){if($==="$or"||$==="$and")return $;if($.includes("$")){let J=$.lastIndexOf("$"),Z=$.substring(0,J),X=$.substring(J);if(Z.includes(".")){let Y=Z.split("."),G=Y[0],H=Y[1];return`${G.trim()}.${u(H)}${X}`}return`${u(Z)}${X}`}if($.includes(".")){let J=$.split("."),Z=J[0],X=J[1];return`${Z.trim()}.${u(X)}`}return u($)}static processJoinWhere($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>g.processJoinWhere(Z));let J={};for(let[Z,X]of Object.entries($)){let Y=g.processJoinWhereKey(Z);if(Z==="$or"||Z==="$and")J[Y]=X.map((G)=>g.processJoinWhere(G));else if(typeof X==="object"&&X!==null&&!Array.isArray(X))J[Y]=g.processJoinWhere(X);else J[Y]=X}return J}static processJoinOrderBy($){if(!$||!Array.isArray($))return $;return $.map((J)=>{if(typeof J!=="string"||!J.includes("#"))return J;let[Z,X]=J.split("#");return`${g.processJoinField(Z.trim())}#${X.trim()}`})}static addDefaultStateFilter($={},J,Z=!1){if(Object.keys($).some((G)=>G.startsWith("state")||G.includes(".state")))return $;if(Z&&J){let G={};for(let[H,z]of Object.entries($))G[H]=z;return G[`${J}.state$gt`]=0,G}let Y={};for(let[G,H]of Object.entries($))Y[G]=H;return Y.state$gt=0,Y}static whereKeysToSnake($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>g.whereKeysToSnake(Z));let J={};for(let[Z,X]of Object.entries($)){if(Z==="$or"||Z==="$and"){J[Z]=X.map((G)=>g.whereKeysToSnake(G));continue}if(Z.includes("$")){let G=Z.lastIndexOf("$"),H=Z.substring(0,G),z=Z.substring(G),V=u(H)+z;J[V]=X;continue}let Y=u(Z);if(typeof X==="object"&&X!==null&&!Array.isArray(X))J[Y]=g.whereKeysToSnake(X);else J[Y]=X}return J}static serializeArrayFields($){let J={};for(let[Z,X]of Object.entries($)){if(X===null||X===void 0){J[Z]=X;continue}if(Array.isArray(X)){J[Z]=JSON.stringify(X);continue}J[Z]=X}return J}static deserializeArrayFields($){if(!$)return null;let J={};for(let[Z,X]of Object.entries($))J[Z]=X;for(let[Z,X]of Object.entries(J)){if(typeof X!=="string")continue;if(X.startsWith("[")&&X.endsWith("]"))try{let Y=JSON.parse(X);if(Array.isArray(Y))J[Z]=Y}catch{}}return J}static cleanAndSnakeAndSerializeWriteData($,J=[null,void 0]){let Z=w$($,{excludeValues:J}),X=aX(Z);return g.serializeArrayFields(X)}static stripSystemFieldsForWrite($,J){let Z={};for(let[X,Y]of Object.entries($)){if(X==="id")continue;if(X==="created_at")continue;if(X==="updated_at")continue;if(X==="deleted_at")continue;if(!J.allowState&&X==="state")continue;Z[X]=Y}return Z}static buildInsertRow($){let J=g.cleanAndSnakeAndSerializeWriteData($.data),Z=g.stripSystemFieldsForWrite(J,{allowState:!1}),X={};for(let[Y,G]of Object.entries(Z))X[Y]=G;return X.id=$.id,X.created_at=$.now,X.updated_at=$.now,X.state=1,X}static buildUpdateRow($){let J=g.cleanAndSnakeAndSerializeWriteData($.data),Z=g.stripSystemFieldsForWrite(J,{allowState:$.allowState}),X={};for(let[Y,G]of Object.entries(Z))X[Y]=G;return X.updated_at=$.now,X}static buildPartialUpdateData($){let J=g.cleanAndSnakeAndSerializeWriteData($.data);return g.stripSystemFieldsForWrite(J,{allowState:$.allowState})}}a();class c0{static SAFE_IDENTIFIER_RE=/^[a-zA-Z_][a-zA-Z0-9_]*$/;static assertNonEmptyString($,J){if(typeof $!=="string")throw Error(`${J} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (value: ${String($)})`);if(!$.trim())throw Error(`${J} \u4E0D\u80FD\u4E3A\u7A7A`)}static assertNoUndefinedParam($,J){if($===void 0)throw Error(`${J} \u4E0D\u80FD\u4E3A undefined`)}static startsWithQuote($){let J=$.trim();return J.startsWith("`")||J.startsWith('"')}static isQuotedIdentPaired($){let J=$.trim();if(J.length<2)return!1;let Z=J[0],X=J[J.length-1];if(Z==="`"&&X==="`")return!0;if(Z==='"'&&X==='"')return!0;return!1}static assertPairedQuotedIdentIfStartsWithQuote($,J){if(c0.startsWithQuote($)&&!c0.isQuotedIdentPaired($))throw Error(`${J} \u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (value: ${$})`)}static assertSafeIdentifierPart($,J){if(!c0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684 ${J} \u6807\u8BC6\u7B26: ${$}`)}static assertSafeAlias($){if(c0.isQuotedIdentPaired($))return;if(!c0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u522B\u540D: ${$}`)}static assertNoExprField($){if(typeof $!=="string")return;let J=$.trim();if(!J)return;if(J.includes("(")||J.includes(")"))throw Error(`\u5B57\u6BB5\u5305\u542B\u51FD\u6570/\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${J})`)}static assertNoUndefinedInRecord($,J){for(let[Z,X]of Object.entries($))if(X===void 0)throw Error(`${J} \u5B58\u5728 undefined \u5B57\u6BB5\u503C (field: ${Z})`)}static assertBatchInsertRowsConsistent($,J){if(!Array.isArray($))throw Error("\u6279\u91CF\u63D2\u5165 rows \u5FC5\u987B\u662F\u6570\u7EC4");if($.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A (table: ${J.table})`);let Z=$[0];if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`\u6279\u91CF\u63D2\u5165\u7684\u6BCF\u4E00\u884C\u5FC5\u987B\u662F\u5BF9\u8C61 (table: ${J.table}, rowIndex: 0)`);let X=Object.keys(Z);if(X.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${J.table})`);let Y=new Set(X);for(let G=0;G<$.length;G++){let H=$[G];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: ${G})`);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: ${G})`);for(let V of z)if(!Y.has(V))throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${G}, 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: ${G}, field: ${V})`);c0.assertNoUndefinedParam(H[V],`\u6279\u91CF\u63D2\u5165\u5B57\u6BB5\u503C (table: ${J.table}, rowIndex: ${G}, field: ${V})`)}}return X}}var c={QUOTE_IDENT_NEED_STRING:($)=>`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`,IDENT_EMPTY:"SQL \u6807\u8BC6\u7B26\u4E0D\u80FD\u4E3A\u7A7A",FIELD_EXPR_NOT_ALLOWED:($)=>`\u5B57\u6BB5\u5305\u542B\u51FD\u6570/\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${$})`,FROM_EMPTY:"FROM \u8868\u540D\u4E0D\u80FD\u4E3A\u7A7A",FROM_NEED_NON_EMPTY:($)=>`FROM \u8868\u540D\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32 (table: ${String($)})`,FROM_REQUIRED:"FROM \u8868\u540D\u662F\u5FC5\u9700\u7684",COUNT_NEED_FROM:"COUNT \u9700\u8981 FROM \u8868\u540D",TABLE_REF_TOO_MANY_PARTS:($)=>`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08\u5305\u542B\u8FC7\u591A\u7247\u6BB5\uFF09\u3002\u8BF7\u4F7F\u7528 fromRaw \u663E\u5F0F\u4F20\u5165\u590D\u6742\u8868\u8FBE\u5F0F (table: ${$})`,TABLE_REF_SCHEMA_TOO_DEEP:($)=>`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09\u3002\u8BF7\u4F7F\u7528 fromRaw (table: ${$})`,SCHEMA_QUOTE_NOT_PAIRED:($)=>`schema \u6807\u8BC6\u7B26\u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (schema: ${$})`,TABLE_QUOTE_NOT_PAIRED:($)=>`table \u6807\u8BC6\u7B26\u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (table: ${$})`,SELECT_FIELDS_INVALID:"SELECT \u5B57\u6BB5\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u6570\u7EC4",SELECT_RAW_NEED_NON_EMPTY:($)=>`selectRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (expr: ${String($)})`,FROM_RAW_NEED_NON_EMPTY:($)=>`fromRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (tableExpr: ${String($)})`,WHERE_RAW_NEED_NON_EMPTY:($)=>`whereRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (sql: ${String($)})`,WHERE_VALUE_REQUIRED:"where(field, value) \u4E0D\u5141\u8BB8\u7701\u7565 value\u3002\u82E5\u9700\u4F20\u5165\u539F\u59CB WHERE\uFF0C\u8BF7\u4F7F\u7528 whereRaw",JOIN_NEED_STRING:($,J)=>`JOIN \u8868\u540D\u548C\u6761\u4EF6\u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (table: ${String($)}, on: ${String(J)})`,ORDER_BY_NEED_ARRAY:'orderBy \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\uFF0C\u683C\u5F0F\u4E3A "\u5B57\u6BB5#\u65B9\u5411"',ORDER_BY_ITEM_NEED_HASH:($)=>`orderBy \u5B57\u6BB5\u5FC5\u987B\u662F "\u5B57\u6BB5#\u65B9\u5411" \u683C\u5F0F\u7684\u5B57\u7B26\u4E32\uFF08\u4F8B\u5982\uFF1A"name#ASC", "id#DESC"\uFF09 (item: ${String($)})`,ORDER_BY_FIELD_EMPTY:($)=>`orderBy \u4E2D\u5B57\u6BB5\u540D\u4E0D\u80FD\u4E3A\u7A7A (item: ${$})`,ORDER_BY_DIR_INVALID:($)=>`ORDER BY \u65B9\u5411\u5FC5\u987B\u662F ASC \u6216 DESC (direction: ${$})`,LIMIT_MUST_NON_NEGATIVE:($)=>`LIMIT \u6570\u91CF\u5FC5\u987B\u662F\u975E\u8D1F\u6570 (count: ${String($)})`,OFFSET_MUST_NON_NEGATIVE:($)=>`OFFSET \u5FC5\u987B\u662F\u975E\u8D1F\u6570 (offset: ${String($)})`,OFFSET_COUNT_MUST_NON_NEGATIVE:($)=>`OFFSET \u5FC5\u987B\u662F\u975E\u8D1F\u6570 (count: ${String($)})`,INSERT_NEED_TABLE:($)=>`INSERT \u9700\u8981\u8868\u540D (table: ${String($)})`,INSERT_NEED_DATA:($,J)=>`INSERT \u9700\u8981\u6570\u636E (table: ${String($)}, data: ${JSON.stringify(J)})`,INSERT_NEED_AT_LEAST_ONE_FIELD:($)=>`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${$})`,UPDATE_NEED_TABLE:"UPDATE \u9700\u8981\u8868\u540D",UPDATE_NEED_OBJECT:"UPDATE \u9700\u8981\u6570\u636E\u5BF9\u8C61",UPDATE_NEED_AT_LEAST_ONE_FIELD:"\u66F4\u65B0\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5",UPDATE_NEED_WHERE:"\u4E3A\u5B89\u5168\u8D77\u89C1\uFF0CUPDATE \u9700\u8981 WHERE \u6761\u4EF6",DELETE_NEED_TABLE:"DELETE \u9700\u8981\u8868\u540D",DELETE_NEED_WHERE:"\u4E3A\u5B89\u5168\u8D77\u89C1\uFF0CDELETE \u9700\u8981 WHERE \u6761\u4EF6",TO_DELETE_IN_NEED_TABLE:($)=>`toDeleteInSql \u9700\u8981\u975E\u7A7A\u8868\u540D (table: ${String($)})`,TO_DELETE_IN_NEED_ID_FIELD:($)=>`toDeleteInSql \u9700\u8981\u975E\u7A7A idField (idField: ${String($)})`,TO_DELETE_IN_NEED_IDS:"toDeleteInSql \u9700\u8981 ids \u6570\u7EC4",TO_UPDATE_CASE_NEED_TABLE:($)=>`toUpdateCaseByIdSql \u9700\u8981\u975E\u7A7A\u8868\u540D (table: ${String($)})`,TO_UPDATE_CASE_NEED_ID_FIELD:($)=>`toUpdateCaseByIdSql \u9700\u8981\u975E\u7A7A idField (idField: ${String($)})`,TO_UPDATE_CASE_NEED_ROWS:"toUpdateCaseByIdSql \u9700\u8981 rows \u6570\u7EC4",TO_UPDATE_CASE_NEED_FIELDS:"toUpdateCaseByIdSql \u9700\u8981 fields \u6570\u7EC4"};class h${_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(c.QUOTE_IDENT_NEED_STRING(J));let Z=J.trim();if(!Z)throw Error(c.IDENT_EMPTY);return`\`${Z.replace(/`/g,"``")}\``}}_isQuotedIdent($){return c0.isQuotedIdentPaired($)}_startsWithQuote($){return c0.startsWithQuote($)}reset(){return this._select=[],this._from="",this._where=[],this._joins=[],this._orderBy=[],this._groupBy=[],this._having=[],this._limit=null,this._offset=null,this._params=[],this}_escapeField($){if(typeof $!=="string")return $;if($=$.trim(),c0.assertPairedQuotedIdentIfStartsWithQuote($,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),$==="*"||this._isQuotedIdent($))return $;try{c0.assertNoExprField($)}catch{throw Error(c.FIELD_EXPR_NOT_ALLOWED($))}if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i),Z=J[0].trim(),X=J[1].trim();return c0.assertSafeAlias(X),`${this._escapeField(Z)} AS ${X}`}if($.includes("."))return $.split(".").map((Z)=>{if(Z=Z.trim(),Z==="*"||this._isQuotedIdent(Z))return Z;return c0.assertPairedQuotedIdentIfStartsWithQuote(Z,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),this._quoteIdent(Z)}).join(".");return this._quoteIdent($)}_validateIdentifierPart($,J){c0.assertSafeIdentifierPart($,J)}_escapeTable($){if(typeof $!=="string")return $;if($=$.trim(),this._startsWithQuote($)&&!this._isQuotedIdent($));if(this._isQuotedIdent($))return $;let J=$.split(/\s+/).filter((H)=>H.length>0);if(J.length===0)throw Error(c.FROM_EMPTY);if(J.length>2)throw Error(c.TABLE_REF_TOO_MANY_PARTS($));let Z=J[0].trim(),X=J.length===2?J[1].trim():null,Y=Z.split(".");if(Y.length>2)throw Error(c.TABLE_REF_SCHEMA_TOO_DEEP($));let G="";if(Y.length===2){let H=Y[0].trim(),z=Y[1].trim(),V=this._isQuotedIdent(H)?H:(()=>{if(this._startsWithQuote(H)&&!this._isQuotedIdent(H))throw Error(c.SCHEMA_QUOTE_NOT_PAIRED(H));return this._validateIdentifierPart(H,"schema"),this._quoteIdent(H)})(),O=this._isQuotedIdent(z)?z:(()=>{if(this._startsWithQuote(z)&&!this._isQuotedIdent(z))throw Error(c.TABLE_QUOTE_NOT_PAIRED(z));return this._validateIdentifierPart(z,"table"),this._quoteIdent(z)})();G=`${V}.${O}`}else{let H=Y[0].trim();if(this._isQuotedIdent(H))G=H;else{if(this._startsWithQuote(H)&&!this._isQuotedIdent(H))throw Error(c.TABLE_QUOTE_NOT_PAIRED(H));this._validateIdentifierPart(H,"table"),G=this._quoteIdent(H)}}if(X)return this._validateIdentifierPart(X,"alias"),`${G} ${X}`;return G}_validateParam($){c0.assertNoUndefinedParam($,"SQL \u53C2\u6570\u503C")}_applyOperator($,J,Z){let X=this._escapeField($);switch(J){case"$ne":case"$not":this._validateParam(Z),this._where.push(`${X} != ?`),this._params.push(Z);break;case"$in":if(!Array.isArray(Z))throw Error(`$in \u64CD\u4F5C\u7B26\u7684\u503C\u5FC5\u987B\u662F\u6570\u7EC4 (operator: ${J})`);if(Z.length===0)throw Error("$in \u64CD\u4F5C\u7B26\u7684\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A\u3002\u63D0\u793A\uFF1A\u7A7A\u6570\u7EC4\u4F1A\u5BFC\u81F4\u67E5\u8BE2\u6C38\u8FDC\u4E0D\u5339\u914D\u4EFB\u4F55\u8BB0\u5F55\uFF0C\u8FD9\u901A\u5E38\u4E0D\u662F\u9884\u671F\u884C\u4E3A\u3002\u8BF7\u68C0\u67E5\u67E5\u8BE2\u6761\u4EF6\u6216\u79FB\u9664\u8BE5\u5B57\u6BB5\u3002");let Y=Z.map(()=>"?").join(",");this._where.push(`${X} IN (${Y})`),this._params.push(...Z);break;case"$nin":case"$notIn":if(!Array.isArray(Z))throw Error(`$nin/$notIn \u64CD\u4F5C\u7B26\u7684\u503C\u5FC5\u987B\u662F\u6570\u7EC4 (operator: ${J})`);if(Z.length===0)throw Error("$nin/$notIn \u64CD\u4F5C\u7B26\u7684\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A\u3002\u63D0\u793A\uFF1A\u7A7A\u6570\u7EC4\u4F1A\u5BFC\u81F4\u67E5\u8BE2\u5339\u914D\u6240\u6709\u8BB0\u5F55\uFF0C\u8FD9\u901A\u5E38\u4E0D\u662F\u9884\u671F\u884C\u4E3A\u3002\u8BF7\u68C0\u67E5\u67E5\u8BE2\u6761\u4EF6\u6216\u79FB\u9664\u8BE5\u5B57\u6BB5\u3002");let G=Z.map(()=>"?").join(",");this._where.push(`${X} NOT IN (${G})`),this._params.push(...Z);break;case"$like":this._validateParam(Z),this._where.push(`${X} LIKE ?`),this._params.push(Z);break;case"$notLike":this._validateParam(Z),this._where.push(`${X} NOT LIKE ?`),this._params.push(Z);break;case"$gt":this._validateParam(Z),this._where.push(`${X} > ?`),this._params.push(Z);break;case"$gte":this._validateParam(Z),this._where.push(`${X} >= ?`),this._params.push(Z);break;case"$lt":this._validateParam(Z),this._where.push(`${X} < ?`),this._params.push(Z);break;case"$lte":this._validateParam(Z),this._where.push(`${X} <= ?`),this._params.push(Z);break;case"$between":if(Array.isArray(Z)&&Z.length===2)this._validateParam(Z[0]),this._validateParam(Z[1]),this._where.push(`${X} BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$notBetween":if(Array.isArray(Z)&&Z.length===2)this._validateParam(Z[0]),this._validateParam(Z[1]),this._where.push(`${X} NOT BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$null":if(Z===!0)this._where.push(`${X} IS NULL`);break;case"$notNull":if(Z===!0)this._where.push(`${X} IS NOT NULL`);break;default:this._validateParam(Z),this._where.push(`${X} = ?`),this._params.push(Z)}}_processWhereConditions($){if(!$||typeof $!=="object")return;Object.entries($).forEach(([J,Z])=>{if(Z===void 0)return;if(J==="$and"){if(Array.isArray(Z))Z.forEach((X)=>this._processWhereConditions(X))}else if(J==="$or"){if(Array.isArray(Z)){let X=[],Y=[];if(Z.forEach((G)=>{let H=new h$({quoteIdent:this._quoteIdent});if(H._processWhereConditions(G),H._where.length>0)X.push(`(${H._where.join(" AND ")})`),Y.push(...H._params)}),X.length>0)this._where.push(`(${X.join(" OR ")})`),this._params.push(...Y)}}else if(J.includes("$")){let X=J.lastIndexOf("$"),Y=J.substring(0,X),G="$"+J.substring(X+1);this._applyOperator(Y,G,Z)}else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))for(let[X,Y]of Object.entries(Z))this._applyOperator(J,X,Y);else{this._validateParam(Z);let X=this._escapeField(J);this._where.push(`${X} = ?`),this._params.push(Z)}})}getWhereConditions(){return{sql:this._where.length>0?this._where.join(" AND "):"",params:[...this._params]}}select($="*"){if(Array.isArray($))this._select=[...this._select,...$.map((J)=>this._escapeField(J))];else if(typeof $==="string")this._select.push(this._escapeField($));else throw Error(c.SELECT_FIELDS_INVALID);return this}selectRaw($){if(typeof $!=="string"||!$.trim())throw Error(c.SELECT_RAW_NEED_NON_EMPTY($));return this._select.push($),this}from($){if(typeof $!=="string"||!$.trim())throw Error(c.FROM_NEED_NON_EMPTY($));return this._from=this._escapeTable($.trim()),this}fromRaw($){if(typeof $!=="string"||!$.trim())throw Error(c.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(c.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(c.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(c.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(c.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(c.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`INNER JOIN ${Z} ON ${J}`),this}orderBy($){if(!Array.isArray($))throw Error(c.ORDER_BY_NEED_ARRAY);return $.forEach((J)=>{if(typeof J!=="string"||!J.includes("#"))throw Error(c.ORDER_BY_ITEM_NEED_HASH(J));let[Z,X]=J.split("#"),Y=Z.trim(),G=X.trim().toUpperCase();if(!Y)throw Error(c.ORDER_BY_FIELD_EMPTY(J));if(!["ASC","DESC"].includes(G))throw Error(c.ORDER_BY_DIR_INVALID(G));let H=this._escapeField(Y);this._orderBy.push(`${H} ${G}`)}),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(c.LIMIT_MUST_NON_NEGATIVE($));if(this._limit=Math.floor($),J!==void 0&&J!==null){if(typeof J!=="number"||J<0)throw Error(c.OFFSET_MUST_NON_NEGATIVE(J));this._offset=Math.floor(J)}return this}offset($){if(typeof $!=="number"||$<0)throw Error(c.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(c.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(c.INSERT_NEED_TABLE($));if(!J||typeof J!=="object")throw Error(c.INSERT_NEED_DATA($,J));let Z=this._escapeTable($);if(Array.isArray(J)){let X=c0.assertBatchInsertRowsConsistent(J,{table:$}),Y=X.map((O)=>this._escapeField(O)),G=X.map(()=>"?").join(", "),H=J.map(()=>`(${G})`).join(", "),z=`INSERT INTO ${Z} (${Y.join(", ")}) VALUES ${H}`,V=[];for(let O=0;O<J.length;O++){let F=J[O];for(let I of X)V.push(F[I])}return{sql:z,params:V}}else{let X=Object.keys(J);if(X.length===0)throw Error(c.INSERT_NEED_AT_LEAST_ONE_FIELD($));for(let V of X)this._validateParam(J[V]);let Y=X.map((V)=>this._escapeField(V)),G=X.map(()=>"?").join(", "),H=`INSERT INTO ${Z} (${Y.join(", ")}) VALUES (${G})`,z=X.map((V)=>J[V]);return{sql:H,params:z}}}toUpdateSql($,J){if(!$||typeof $!=="string")throw Error(c.UPDATE_NEED_TABLE);if(!J||typeof J!=="object"||Array.isArray(J))throw Error(c.UPDATE_NEED_OBJECT);let Z=Object.keys(J);if(Z.length===0)throw Error(c.UPDATE_NEED_AT_LEAST_ONE_FIELD);let X=this._escapeTable($),Y=Z.map((z)=>`${this._escapeField(z)} = ?`),G=[...Object.values(J),...this._params],H=`UPDATE ${X} SET ${Y.join(", ")}`;if(this._where.length>0)H+=" WHERE "+this._where.join(" AND ");else throw Error(c.UPDATE_NEED_WHERE);return{sql:H,params:G}}toDeleteSql($){if(!$||typeof $!=="string")throw Error(c.DELETE_NEED_TABLE);let Z=`DELETE FROM ${this._escapeTable($)}`;if(this._where.length>0)Z+=" WHERE "+this._where.join(" AND ");else throw Error(c.DELETE_NEED_WHERE);return{sql:Z,params:[...this._params]}}toCountSql(){let $="SELECT COUNT(*) as total";if(!this._from)throw Error(c.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(c.TO_DELETE_IN_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(c.TO_DELETE_IN_NEED_ID_FIELD($.idField));if(!Array.isArray($.ids))throw Error(c.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(c.TO_UPDATE_CASE_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(c.TO_UPDATE_CASE_NEED_ID_FIELD($.idField));if(!Array.isArray($.rows))throw Error(c.TO_UPDATE_CASE_NEED_ROWS);if($.rows.length===0)return{sql:"",params:[]};if(!Array.isArray($.fields))throw Error(c.TO_UPDATE_CASE_NEED_FIELDS);if($.fields.length===0)return{sql:"",params:[]};let J=$.rows.map((z)=>z.id),Z=J.map(()=>"?").join(","),X=[],Y=[],G=$.quoteIdent($.idField);for(let z of $.fields){let V=[];for(let F of $.rows){if(!(z in F.data))continue;V.push("WHEN ? THEN ?"),Y.push(F.id),Y.push(F.data[z])}if(V.length===0)continue;let O=$.quoteIdent(z);X.push(`${O} = CASE ${G} ${V.join(" ")} ELSE ${O} END`)}X.push(`${$.quoteIdent($.updatedAtField)} = ?`),Y.push($.updatedAtValue);for(let z of J)Y.push(z);let H=`UPDATE ${$.quoteIdent($.table)} SET ${X.join(", ")} WHERE ${G} IN (${Z})`;if($.stateGtZero&&$.stateField)H+=` AND ${$.quoteIdent($.stateField)} > 0`;return{sql:H,params:Y}}}var DQ=3600;class fJ{redis;dialect;sql=null;isTransaction=!1;constructor($){this.redis=$.redis,this.sql=$.sql||null,this.isTransaction=!!$.sql,this.dialect=$.dialect?$.dialect:new SJ}createSqlBuilder(){return new h$({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($),G=(await this.executeWithConn(X.sql,X.params)).data;if(!G||G.length===0)throw Error(`\u8868 ${$} \u4E0D\u5B58\u5728\u6216\u6CA1\u6709\u5B57\u6BB5`);let H=this.dialect.getTableColumnsFromResult(G);if(await this.redis.setObject(J,H,DQ)===null)P.warn({table:$,cacheKey:J,msg:"\u8868\u5B57\u6BB5\u7F13\u5B58\u5199\u5165 Redis \u5931\u8D25"});return H}async prepareQueryOptions($){let J=w$($.where||{},{excludeValues:[null,void 0]});if($.joins&&$.joins.length>0){let Y=($.fields||[]).map((z)=>g.processJoinField(z)),G=g.normalizeTableRef($.table),H=g.getJoinMainQualifier($.table);return{table:G,tableQualifier:H,fields:Y.length>0?Y:["*"],where:g.processJoinWhere(J),joins:$.joins,orderBy:g.processJoinOrderBy($.orderBy||[]),page:$.page||1,limit:$.limit||10}}let X=await g.fieldsToSnake(u($.table),$.fields||[],this.getTableColumns.bind(this));return{table:u($.table),tableQualifier:u($.table),fields:X,where:g.whereKeysToSnake(J),joins:void 0,orderBy:g.orderByToSnake($.orderBy||[]),page:$.page||1,limit:$.limit||10}}applyJoins($,J){if(!J||J.length===0)return;for(let Z of J){let X=g.normalizeTableRef(Z.table);switch(Z.type||"left"){case"inner":$.innerJoin(X,Z.on);break;case"right":$.rightJoin(X,Z.on);break;case"left":default:$.leftJoin(X,Z.on);break}}}async executeWithConn($,J){if(!this.sql)throw Error("\u6570\u636E\u5E93\u8FDE\u63A5\u672A\u521D\u59CB\u5316");if(typeof $!=="string")throw Error(`executeWithConn \u53EA\u63A5\u53D7\u5B57\u7B26\u4E32\u7C7B\u578B\u7684 SQL\uFF0C\u6536\u5230\u7C7B\u578B: ${typeof $}\uFF0C\u503C: ${JSON.stringify($)}`);let Z=Date.now(),X=Array.isArray(J)?J:[];try{let Y;if(X.length>0)Y=await this.sql.unsafe($,X);else Y=await this.sql.unsafe($);let G=Date.now()-Z;return{data:Y,sql:{sql:$,params:X,duration:G}}}catch(Y){let G=Date.now()-Z,H=Error(`SQL\u6267\u884C\u5931\u8D25: ${Y.message}`);throw H.originalError=Y,H.params=X,H.duration=G,H.sqlInfo={sql:$,params:X,duration:G},H}}async unsafe($,J){return await this.executeWithConn($,J)}async tableExists($){let J=u($),Z=this.dialect.tableExistsQuery(J),X=await this.executeWithConn(Z.sql,Z.params);return{data:(X.data?.[0]?.count||0)>0,sql:X.sql}}async getCount($){let{table:J,where:Z,joins:X,tableQualifier:Y}=await this.prepareQueryOptions($),G=this.createSqlBuilder().selectRaw("COUNT(*) as count").from(J).where(g.addDefaultStateFilter(Z,Y,!!X));this.applyJoins(G,X);let{sql:H,params:z}=G.toSelectSql(),V=await this.executeWithConn(H,z);return{data:V.data?.[0]?.count||0,sql:V.sql}}async getOne($){let{table:J,fields:Z,where:X,joins:Y,tableQualifier:G}=await this.prepareQueryOptions($),H=this.createSqlBuilder().select(Z).from(J).where(g.addDefaultStateFilter(X,G,!!Y));this.applyJoins(H,Y);let{sql:z,params:V}=H.toSelectSql(),O=await this.executeWithConn(z,V),I=O.data?.[0]||null;if(!I)return{data:null,sql:O.sql};let B=RZ(I),L=g.deserializeArrayFields(B);if(!L)return{data:null,sql:O.sql};return{data:xJ([L])[0],sql:O.sql}}async getList($){let J=await this.prepareQueryOptions($);if(J.page<1||J.page>1e4)throw Error(`\u9875\u7801\u5FC5\u987B\u5728 1 \u5230 10000 \u4E4B\u95F4 (table: ${$.table}, page: ${J.page}, limit: ${J.limit})`);if(J.limit<1||J.limit>1000)throw Error(`\u6BCF\u9875\u6570\u91CF\u5FC5\u987B\u5728 1 \u5230 1000 \u4E4B\u95F4 (table: ${$.table}, page: ${J.page}, limit: ${J.limit})`);let Z=g.addDefaultStateFilter(J.where,J.tableQualifier,!!J.joins),X=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(J.table).where(Z);this.applyJoins(X,J.joins);let{sql:Y,params:G}=X.toSelectSql(),H=await this.executeWithConn(Y,G),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:F,params:I}=O.toSelectSql(),B=await this.executeWithConn(F,I),L=B.data||[],w=IZ(L).map((T)=>g.deserializeArrayFields(T)).filter((T)=>T!==null);return{data:{lists:xJ(w),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=await this.prepareQueryOptions({...$,page:1,limit:10}),Y=g.addDefaultStateFilter(X.where,X.tableQualifier,!!X.joins),G=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(X.table).where(Y);this.applyJoins(G,X.joins);let{sql:H,params:z}=G.toSelectSql(),V=await this.executeWithConn(H,z),O=V.data?.[0]?.total||0;if(O===0)return{data:{lists:[],total:0},sql:{count:V.sql}};let F=this.createSqlBuilder().select(X.fields).from(X.table).where(Y).limit(1e4);if(this.applyJoins(F,X.joins),X.orderBy&&X.orderBy.length>0)F.orderBy(X.orderBy);let{sql:I,params:B}=F.toSelectSql(),L=await this.executeWithConn(I,B),C=L.data||[];if(C.length>=1000)P.warn({table:$.table,count:C.length,total:O,msg:"getAll \u8FD4\u56DE\u6570\u636E\u8FC7\u591A\uFF0C\u5EFA\u8BAE\u4F7F\u7528 getList \u5206\u9875\u67E5\u8BE2"});if(C.length>=1e4)P.warn({table:$.table,limit:1e4,total:O,msg:`getAll \u8FBE\u5230\u6700\u5927\u9650\u5236 ${1e4}\uFF0C\u5B9E\u9645\u603B\u6570 ${O}\uFF0C\u53EA\u8FD4\u56DE\u524D ${1e4} \u6761`});let T=IZ(C).map((E)=>g.deserializeArrayFields(E)).filter((E)=>E!==null);return{data:{lists:xJ(T),total:O},sql:{count:V.sql,data:L.sql}}}async insData($){let{table:J,data:Z}=$,X=u(J),Y=Date.now(),G;try{G=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=g.buildInsertRow({data:Z,id:G,now:Y});c0.assertNoUndefinedInRecord(H,`insData \u63D2\u5165\u6570\u636E (table: ${X})`);let z=this.createSqlBuilder(),{sql:V,params:O}=z.toInsertSql(X,H),F=await this.executeWithConn(V,O);return{data:H.id||F.data?.lastInsertRowid||0,sql:F.sql}}async insBatch($,J){if(J.length===0)return{data:[],sql:{sql:"",params:[],duration:0}};let Z=1000;if(J.length>Z)throw Error(`\u6279\u91CF\u63D2\u5165\u6570\u91CF ${J.length} \u8D85\u8FC7\u6700\u5927\u9650\u5236 ${Z}`);let X=u($),Y=[];for(let I=0;I<J.length;I++)Y.push(await this.redis.genTimeID());let G=Date.now(),H=J.map((I,B)=>{return g.buildInsertRow({data:I,id:Y[B],now:G})}),z=c0.assertBatchInsertRowsConsistent(H,{table:X}),V=this.createSqlBuilder(),{sql:O,params:F}=V.toInsertSql(X,H);try{let I=await this.executeWithConn(O,F);return{data:Y,sql:I.sql}}catch(I){throw P.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=u($),X=h$.toDeleteInSql({table:Z,idField:"id",ids:J,quoteIdent:this.dialect.quoteIdent.bind(this.dialect)}),Y=await this.executeWithConn(X.sql,X.params);return{data:Y.data?.changes||0,sql:Y.sql}}async updBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=u($),X=Date.now(),Y=[],G=new Set;for(let F of J){let I=g.buildPartialUpdateData({data:F.data,allowState:!0});for(let B of Object.keys(I))G.add(B);Y.push({id:F.id,data:I})}let H=Array.from(G).sort();if(H.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let z=h$.toUpdateCaseByIdSql({table:Z,idField:"id",rows:Y,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}=$,Y=w$(X,{excludeValues:[null,void 0]}),G=u(J),H=g.whereKeysToSnake(Y),z=g.buildUpdateRow({data:Z,now:Date.now(),allowState:!0}),V=g.addDefaultStateFilter(H,G,!1),O=this.createSqlBuilder().where(V),{sql:F,params:I}=O.toUpdateSql(G,z),B=await this.executeWithConn(F,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=u(J),Y=w$(Z,{excludeValues:[null,void 0]}),G=g.whereKeysToSnake(Y),H=this.createSqlBuilder().where(G),{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 fJ({redis:this.redis,sql:J,dialect:this.dialect});return await $(Z)})}async query($,J){return await this.executeWithConn($,J)}async exists($){let{table:J,where:Z,tableQualifier:X}=await this.prepareQueryOptions({...$,page:1,limit:1}),Y=this.createSqlBuilder().selectRaw("COUNT(1) as cnt").from(J).where(g.addDefaultStateFilter(Z,X,!1)).limit(1),{sql:G,params:H}=Y.toSelectSql(),z=await this.executeWithConn(G,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]}),Y=X.data;if(!Y)return{data:null,sql:X.sql};if(J in Y)return{data:Y[J],sql:X.sql};let G=J.replace(/_([a-z])/g,(z,V)=>V.toUpperCase());if(G!==J&&G in Y)return{data:Y[G],sql:X.sql};let H=J.replace(/[A-Z]/g,(z)=>`_${z.toLowerCase()}`);if(H!==J&&H in Y)return{data:Y[H],sql:X.sql};return{data:null,sql:X.sql}}async increment($,J,Z,X=1){let Y=u($),G=u(J);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(Y))throw Error(`\u65E0\u6548\u7684\u8868\u540D: ${Y}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(G))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=w$(Z,{excludeValues:[null,void 0]}),z=g.whereKeysToSnake(H),V=g.addDefaultStateFilter(z,Y,!1),O=this.createSqlBuilder().where(V),{sql:F,params:I}=O.getWhereConditions(),B=this.dialect.quoteIdent(Y),L=this.dialect.quoteIdent(G),C=F?`UPDATE ${B} SET ${L} = ${L} + ? WHERE ${F}`:`UPDATE ${B} SET ${L} = ${L} + ?`,w=await this.executeWithConn(C,[X,...I]);return{data:w.data?.changes||0,sql:w.sql}}async decrement($,J,Z,X=1){return await this.increment($,J,Z,-X)}}a();var kQ={name:"db",enable:!0,deps:["logger","redis"],async handler($){if(!$.redis)throw Error("\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25\uFF1Actx.redis \u672A\u521D\u59CB\u5316\uFF08Redis \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");try{let J=z$.getSql(),Z=$.config&&$.config.db?$.config.db.type:void 0,X=Z==="postgres"?"postgresql":Z,Y=f$(X==="postgresql"||X==="sqlite"?X:"mysql");return new fJ({redis:$.redis,sql:J,dialect:Y})}catch(J){throw P.error({err:J,msg:"\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25"}),J}}},kY=kQ;var v$=fW(jW(),1);class vX{config;constructor($={}){this.config={secret:$.secret||"befly-secret",expiresIn:$.expiresIn||"7d",algorithm:$.algorithm||"HS256"}}sign($,J={}){let Z=J.secret||this.config.secret||"befly-secret",X=J.algorithm||this.config.algorithm||"HS256";return v$.createSigner({key:Z,algorithm:X,expiresIn:J.expiresIn||this.config.expiresIn,iss:J.issuer,aud:J.audience,sub:J.subject,jti:J.jwtId,notBefore:typeof J.notBefore==="number"?J.notBefore:void 0})($)}verify($,J={}){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let Z=J.secret||this.config.secret||"befly-secret",X=this.config.algorithm||"HS256",Y=J.algorithms?J.algorithms:[X];return v$.createVerifier({key:Z,algorithms:Y,allowedIss:J.issuer,allowedAud:J.audience,allowedSub:J.subject,ignoreExpiration:J.ignoreExpiration,ignoreNotBefore:J.ignoreNotBefore,cache:!0,cacheTTL:600000})($)}decode($,J=!1){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(J){let Y=v$.createDecoder({complete:!0})($);return{header:Y.header,payload:Y.payload,signature:Y.signature}}return v$.createDecoder()($)}}var $9={name:"jwt",enable:!0,deps:[],handler:($)=>{return new vX($.config?$.config.auth:void 0)}},BW=$9;a();var J9={name:"logger",enable:!0,deps:[],async handler($){if($.config&&$.config.logger)P.configure($.config.logger);return P}},LW=J9;a();a();class NX{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,X={}){if(Z<=this.slowThresholdMs)return;P.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),Y=`${this.prefix}${$}`,G=Date.now();if(Z){let V=await this.client.setex(Y,Z,X),O=Date.now()-G;return this.logSlow("SETEX",Y,O,{ttl:Z}),V}let H=await this.client.set(Y,X),z=Date.now()-G;return this.logSlow("SET",Y,z),H}catch(X){return P.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),Y=Date.now()-Z;return this.logSlow("GET",J,Y),X?JSON.parse(X):null}catch(J){return P.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){P.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 Y=Date.now()-Z;this.logSlow("INCR",J,Y,{expireSeconds:1});let G=100+($%900+X-1)%900;return Number(`${$}${G}`)}async setString($,J,Z=null){try{let X=`${this.prefix}${$}`,Y=Date.now();if(Z){let z=await this.client.setex(X,Z,J),V=Date.now()-Y;return this.logSlow("SETEX",X,V,{ttl:Z}),z}let G=await this.client.set(X,J),H=Date.now()-Y;return this.logSlow("SET",X,H),G}catch(X){return P.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),Y=Date.now()-Z;return this.logSlow("GET",J,Y),X}catch(J){return P.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),Y=Date.now()-Z;return this.logSlow("EXISTS",J,Y),X}catch(J){return P.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),Y=Date.now()-Z;return this.logSlow("INCR",J,Y),X}catch(J){return P.error({err:J,msg:"Redis incr \u9519\u8BEF"}),0}}async incrWithExpire($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),Y=await this.client.incr(Z);if(Y===1)await this.client.expire(Z,J);let G=Date.now()-X;return this.logSlow("INCR",Z,G,{expireSeconds:J}),Y}catch(Z){return P.error({err:Z,msg:"Redis incrWithExpire \u9519\u8BEF"}),0}}async expire($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),Y=await this.client.expire(Z,J),G=Date.now()-X;return this.logSlow("EXPIRE",Z,G,{seconds:J}),Y}catch(Z){return P.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),Y=Date.now()-Z;return this.logSlow("TTL",J,Y),X}catch(J){return P.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 P.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(),Y=await this.client.sadd(Z,...J),G=Date.now()-X;return this.logSlow("SADD",Z,G,{membersCount:J.length}),Y}catch(Z){return P.error({err:Z,msg:"Redis sadd \u9519\u8BEF"}),0}}async sismember($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),Y=await this.client.sismember(Z,J),G=Date.now()-X;return this.logSlow("SISMEMBER",Z,G),Y}catch(Z){return P.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),Y=Date.now()-Z;return this.logSlow("SCARD",J,Y),X}catch(J){return P.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),Y=Date.now()-Z;return this.logSlow("SMEMBERS",J,Y),X}catch(J){return P.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 P.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 P.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),Y=Date.now()-Z;return this.logSlow("DEL",J,Y),X}catch(J){return P.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 P.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 P.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 P.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 P.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 P.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 P.error({err:$,msg:"Redis ping \u9519\u8BEF"}),$}}}var Z9={name:"redis",enable:!0,deps:["logger"],async handler($){let J=$.config&&$.config.redis?$.config.redis:{};try{return z$.getRedis(),new NX(J.prefix)}catch(Z){throw P.error({err:Z,msg:"Redis \u521D\u59CB\u5316\u5931\u8D25"}),Z}}},SW=Z9;function X9($,J={},Z={}){return{code:0,msg:$,data:J,...Z}}function Y9($,J=null,Z={}){return{code:1,msg:$,data:J,...Z}}function G9($,J,Z={}){let{status:X=200,contentType:Y,headers:G={}}=Z,H=Y,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,...G};return new Response(z,{status:X,headers:V})}var W9={name:"tool",enable:!0,deps:[],handler:()=>{return{Yes:X9,No:Y9,Raw:G9}}},CW=W9;m0();function EW($,J){let Z=J.name,X=o(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 wW(){let $=[],J=[LW,SW,kY,vY,CW,NY,BW,DY];for(let Z of J)$.push(EW("plugin",Z));return $}function TW(){let $=[],J=[KY,FY,SY,TY,CY];for(let Z of J)$.push(EW("hook",Z));return $}I$();import{existsSync as H9}from"fs";a();async function vW($,J){try{let X=(await import($))?.default;if(X===null||X===void 0)return J;return X}catch(Z){return P.warn({err:Z,file:$,msg:"importDefault \u5BFC\u5165\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C"}),J}}m0();function Q9($){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 z9($){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 V$($,J,Z,X){if(!H9($))return[];let Y=L$($),G=new Bun.Glob(X),H=[];try{let z=await G.scan({cwd:$,onlyFiles:!0,absolute:!0,followSymlinks:!0});for await(let V of z){if(V.endsWith(".d.ts"))continue;let O=L$(V),F=$J(O).name,I=xZ(Y,O),B=$J(I),L=B.dir?d(B.dir,B.name):B.name;if(F.startsWith("_"))continue;if(L.split("/").some((D)=>D.startsWith("_")))continue;let C=await vW(O,{}),w=K$(F),T="",N="";if(J==="core")T="",N=F;else if(J==="app")N=`app_${w}`;else{let D=Q9(O)||z9(O);if(!D)throw Error(`scanFiles addon moduleName \u89E3\u6790\u5931\u8D25\uFF1A\u672A\u627E\u5230 @befly-addon/<addon>/ \u6BB5\u843D\uFF1A${O}`);T=D,N=`addon_${K$(T)}_${w}`}let E={source:J,type:Z,sourceName:{core:"\u6838\u5FC3",addon:"\u7EC4\u4EF6",app:"\u9879\u76EE"}[J],filePath:O,relativePath:L,fileName:F,moduleName:N,addonName:T,fileBaseName:$J(O).base,fileDir:$,customKeys:o(C)?Object.keys(C):[]};if(Z==="table"){E.content=C,H.push(E);continue}if(Z==="api")E.auth=!0,E.rawBody=!1,E.method="POST",E.fields={},E.required=[];if(Z==="plugin"||Z==="hook")E.deps=[],E.name="",E.handler=null;if(tX(C,(D,h)=>{E[h]=D}),Z==="api")E.routePrefix=J==="app"?"/app":`/addon/${T}`,E.routePath=`/api${E.routePrefix}/${L}`;H.push(E)}}catch(z){let V=Error(`scanFiles failed: source=${J} type=${Z} dir=${Y} pattern=${X}`);throw V.cause=z,V}return H}var NW=async()=>{let $=[],J=[],Z=[],X=[],Y=await AY();X.push(...await V$(d(d0,"tables"),"app","table","*.json"));for(let G of Y)X.push(...await V$(d(G.fullPath,"tables"),"addon","table","*.json"));J.push(...wW()),J.push(...await V$(d(d0,"plugins"),"app","plugin","*.{ts,js}"));for(let G of Y)J.push(...await V$(d(G.fullPath,"plugins"),"addon","plugin","*.{ts,js}"));Z.push(...TW()),Z.push(...await V$(d(d0,"hooks"),"app","hook","*.{ts,js}"));for(let G of Y)Z.push(...await V$(d(G.fullPath,"hooks"),"addon","hook","*.{ts,js}"));$.push(...await V$(d(d0,"apis"),"app","api","**/*.{ts,js}"));for(let G of Y)$.push(...await V$(d(G.fullPath,"apis"),"addon","api","**/*.{ts,js}"));return{hooks:Z,plugins:J,apis:$,tables:X,addons:Y}};class U9{apis=new Map;plugins=[];hooks=[];context={};config=null;async start(){try{let $=Bun.nanoseconds();this.config=await Y1(),this.context.config=this.config;let{apis:J,tables:Z,plugins:X,hooks:Y,addons:G}=await NW();this.context.addons=G,await F1(J),await f1(Z),await N1(X),await R1(Y);let H=await T1(G,{disableMenus:this.config.disableMenus||[]});if(await z$.connect({db:this.config.db||{},redis:this.config.redis||{}}),this.plugins=await p1(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 EJ(this.context,Z),await s1(this.context,J),await r1(this.context,H),await l1(this.context,{devEmail:this.config.devEmail,devPassword:this.config.devPassword}),await o1(this.context),this.hooks=await c1(Y),this.apis=await b1(J);let z=m1(this.apis,this.hooks,this.context),V=d1(this.config.cors),O=Bun.serve({port:this.config.appPort,hostname:this.config.appHost,development:this.config.nodeEnv==="development",idleTimeout:30,fetch:async(C,w)=>{let T=new URL(C.url);if(T.pathname==="/")return Response.json({code:0,msg:`${this.config.appName} \u63A5\u53E3\u670D\u52A1\u5DF2\u542F\u52A8`});if(T.pathname.startsWith("/api/"))return z(C,w);return V(C)},error:(C)=>{if(P.error({err:C,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:C.message,stack:C.stack},{status:200});return Response.json({code:1,msg:"\u5185\u90E8\u670D\u52A1\u5668\u9519\u8BEF"},{status:200})}}),F=OY($),I=_Y(),B=I.role==="primary"?"\u4E3B\u8FDB\u7A0B":`\u5DE5\u4F5C\u8FDB\u7A0B #${I.instanceId}`,L=I.env==="standalone"?"":` [${I.env}]`;return P.info(`${this.config.appName} \u542F\u52A8\u6210\u529F! (${B}${L})`),P.info(`\u670D\u52A1\u5668\u542F\u52A8\u8017\u65F6: ${F}`),P.info(`\u670D\u52A1\u5668\u76D1\u542C\u5730\u5740: ${O.url}`),O}catch($){P.error({err:$,msg:"\u9879\u76EE\u542F\u52A8\u5931\u8D25"});try{await P.flush()}catch{}try{await P.shutdown()}catch{}if($ instanceof Error)throw $;throw Error(String($))}}}export{U9 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,X]=J.split("#");return`${u(Z.trim())}#${X.trim()}`})}static processJoinField($){if($.includes("(")||$==="*"||$.startsWith("`"))return $;if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i),Z=J[0].trim(),X=J[1].trim();return`${g.processJoinField(Z)} AS ${X}`}if($.includes(".")){let J=$.split("."),Z=J[0],X=J[1];return`${Z.trim()}.${u(X)}`}return u($)}static processJoinWhereKey($){if($==="$or"||$==="$and")return $;if($.includes("$")){let J=$.lastIndexOf("$"),Z=$.substring(0,J),X=$.substring(J);if(Z.includes(".")){let Y=Z.split("."),G=Y[0],H=Y[1];return`${G.trim()}.${u(H)}${X}`}return`${u(Z)}${X}`}if($.includes(".")){let J=$.split("."),Z=J[0],X=J[1];return`${Z.trim()}.${u(X)}`}return u($)}static processJoinWhere($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>g.processJoinWhere(Z));let J={};for(let[Z,X]of Object.entries($)){let Y=g.processJoinWhereKey(Z);if(Z==="$or"||Z==="$and")J[Y]=X.map((G)=>g.processJoinWhere(G));else if(typeof X==="object"&&X!==null&&!Array.isArray(X))J[Y]=g.processJoinWhere(X);else J[Y]=X}return J}static processJoinOrderBy($){if(!$||!Array.isArray($))return $;return $.map((J)=>{if(typeof J!=="string"||!J.includes("#"))return J;let[Z,X]=J.split("#");return`${g.processJoinField(Z.trim())}#${X.trim()}`})}static addDefaultStateFilter($={},J,Z=!1){if(Object.keys($).some((G)=>G.startsWith("state")||G.includes(".state")))return $;if(Z&&J){let G={};for(let[H,z]of Object.entries($))G[H]=z;return G[`${J}.state$gt`]=0,G}let Y={};for(let[G,H]of Object.entries($))Y[G]=H;return Y.state$gt=0,Y}static whereKeysToSnake($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>g.whereKeysToSnake(Z));let J={};for(let[Z,X]of Object.entries($)){if(Z==="$or"||Z==="$and"){J[Z]=X.map((G)=>g.whereKeysToSnake(G));continue}if(Z.includes("$")){let G=Z.lastIndexOf("$"),H=Z.substring(0,G),z=Z.substring(G),V=u(H)+z;J[V]=X;continue}let Y=u(Z);if(typeof X==="object"&&X!==null&&!Array.isArray(X))J[Y]=g.whereKeysToSnake(X);else J[Y]=X}return J}static serializeArrayFields($){let J={};for(let[Z,X]of Object.entries($)){if(X===null||X===void 0){J[Z]=X;continue}if(Array.isArray(X)){J[Z]=JSON.stringify(X);continue}J[Z]=X}return J}static deserializeArrayFields($){if(!$)return null;let J={};for(let[Z,X]of Object.entries($))J[Z]=X;for(let[Z,X]of Object.entries(J)){if(typeof X!=="string")continue;if(X.startsWith("[")&&X.endsWith("]"))try{let Y=JSON.parse(X);if(Array.isArray(Y))J[Z]=Y}catch{}}return J}static cleanAndSnakeAndSerializeWriteData($,J=[null,void 0]){let Z=w$($,{excludeValues:J}),X=aX(Z);return g.serializeArrayFields(X)}static stripSystemFieldsForWrite($,J){let Z={};for(let[X,Y]of Object.entries($)){if(X==="id")continue;if(X==="created_at")continue;if(X==="updated_at")continue;if(X==="deleted_at")continue;if(!J.allowState&&X==="state")continue;Z[X]=Y}return Z}static buildInsertRow($){let J=g.cleanAndSnakeAndSerializeWriteData($.data),Z=g.stripSystemFieldsForWrite(J,{allowState:!1}),X={};for(let[Y,G]of Object.entries(Z))X[Y]=G;return X.id=$.id,X.created_at=$.now,X.updated_at=$.now,X.state=1,X}static buildUpdateRow($){let J=g.cleanAndSnakeAndSerializeWriteData($.data),Z=g.stripSystemFieldsForWrite(J,{allowState:$.allowState}),X={};for(let[Y,G]of Object.entries(Z))X[Y]=G;return X.updated_at=$.now,X}static buildPartialUpdateData($){let J=g.cleanAndSnakeAndSerializeWriteData($.data);return g.stripSystemFieldsForWrite(J,{allowState:$.allowState})}}a();class c0{static SAFE_IDENTIFIER_RE=/^[a-zA-Z_][a-zA-Z0-9_]*$/;static assertNonEmptyString($,J){if(typeof $!=="string")throw Error(`${J} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (value: ${String($)})`);if(!$.trim())throw Error(`${J} \u4E0D\u80FD\u4E3A\u7A7A`)}static assertNoUndefinedParam($,J){if($===void 0)throw Error(`${J} \u4E0D\u80FD\u4E3A undefined`)}static startsWithQuote($){let J=$.trim();return J.startsWith("`")||J.startsWith('"')}static isQuotedIdentPaired($){let J=$.trim();if(J.length<2)return!1;let Z=J[0],X=J[J.length-1];if(Z==="`"&&X==="`")return!0;if(Z==='"'&&X==='"')return!0;return!1}static assertPairedQuotedIdentIfStartsWithQuote($,J){if(c0.startsWithQuote($)&&!c0.isQuotedIdentPaired($))throw Error(`${J} \u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (value: ${$})`)}static assertSafeIdentifierPart($,J){if(!c0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684 ${J} \u6807\u8BC6\u7B26: ${$}`)}static assertSafeAlias($){if(c0.isQuotedIdentPaired($))return;if(!c0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u522B\u540D: ${$}`)}static assertNoExprField($){if(typeof $!=="string")return;let J=$.trim();if(!J)return;if(J.includes("(")||J.includes(")"))throw Error(`\u5B57\u6BB5\u5305\u542B\u51FD\u6570/\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${J})`)}static assertNoUndefinedInRecord($,J){for(let[Z,X]of Object.entries($))if(X===void 0)throw Error(`${J} \u5B58\u5728 undefined \u5B57\u6BB5\u503C (field: ${Z})`)}static assertBatchInsertRowsConsistent($,J){if(!Array.isArray($))throw Error("\u6279\u91CF\u63D2\u5165 rows \u5FC5\u987B\u662F\u6570\u7EC4");if($.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A (table: ${J.table})`);let Z=$[0];if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`\u6279\u91CF\u63D2\u5165\u7684\u6BCF\u4E00\u884C\u5FC5\u987B\u662F\u5BF9\u8C61 (table: ${J.table}, rowIndex: 0)`);let X=Object.keys(Z);if(X.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${J.table})`);let Y=new Set(X);for(let G=0;G<$.length;G++){let H=$[G];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: ${G})`);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: ${G})`);for(let V of z)if(!Y.has(V))throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${G}, 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: ${G}, field: ${V})`);c0.assertNoUndefinedParam(H[V],`\u6279\u91CF\u63D2\u5165\u5B57\u6BB5\u503C (table: ${J.table}, rowIndex: ${G}, field: ${V})`)}}return X}}var c={QUOTE_IDENT_NEED_STRING:($)=>`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`,IDENT_EMPTY:"SQL \u6807\u8BC6\u7B26\u4E0D\u80FD\u4E3A\u7A7A",FIELD_EXPR_NOT_ALLOWED:($)=>`\u5B57\u6BB5\u5305\u542B\u51FD\u6570/\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${$})`,FROM_EMPTY:"FROM \u8868\u540D\u4E0D\u80FD\u4E3A\u7A7A",FROM_NEED_NON_EMPTY:($)=>`FROM \u8868\u540D\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32 (table: ${String($)})`,FROM_REQUIRED:"FROM \u8868\u540D\u662F\u5FC5\u9700\u7684",COUNT_NEED_FROM:"COUNT \u9700\u8981 FROM \u8868\u540D",TABLE_REF_TOO_MANY_PARTS:($)=>`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08\u5305\u542B\u8FC7\u591A\u7247\u6BB5\uFF09\u3002\u8BF7\u4F7F\u7528 fromRaw \u663E\u5F0F\u4F20\u5165\u590D\u6742\u8868\u8FBE\u5F0F (table: ${$})`,TABLE_REF_SCHEMA_TOO_DEEP:($)=>`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09\u3002\u8BF7\u4F7F\u7528 fromRaw (table: ${$})`,SCHEMA_QUOTE_NOT_PAIRED:($)=>`schema \u6807\u8BC6\u7B26\u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (schema: ${$})`,TABLE_QUOTE_NOT_PAIRED:($)=>`table \u6807\u8BC6\u7B26\u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (table: ${$})`,SELECT_FIELDS_INVALID:"SELECT \u5B57\u6BB5\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u6570\u7EC4",SELECT_RAW_NEED_NON_EMPTY:($)=>`selectRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (expr: ${String($)})`,FROM_RAW_NEED_NON_EMPTY:($)=>`fromRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (tableExpr: ${String($)})`,WHERE_RAW_NEED_NON_EMPTY:($)=>`whereRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (sql: ${String($)})`,WHERE_VALUE_REQUIRED:"where(field, value) \u4E0D\u5141\u8BB8\u7701\u7565 value\u3002\u82E5\u9700\u4F20\u5165\u539F\u59CB WHERE\uFF0C\u8BF7\u4F7F\u7528 whereRaw",JOIN_NEED_STRING:($,J)=>`JOIN \u8868\u540D\u548C\u6761\u4EF6\u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (table: ${String($)}, on: ${String(J)})`,ORDER_BY_NEED_ARRAY:'orderBy \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\uFF0C\u683C\u5F0F\u4E3A "\u5B57\u6BB5#\u65B9\u5411"',ORDER_BY_ITEM_NEED_HASH:($)=>`orderBy \u5B57\u6BB5\u5FC5\u987B\u662F "\u5B57\u6BB5#\u65B9\u5411" \u683C\u5F0F\u7684\u5B57\u7B26\u4E32\uFF08\u4F8B\u5982\uFF1A"name#ASC", "id#DESC"\uFF09 (item: ${String($)})`,ORDER_BY_FIELD_EMPTY:($)=>`orderBy \u4E2D\u5B57\u6BB5\u540D\u4E0D\u80FD\u4E3A\u7A7A (item: ${$})`,ORDER_BY_DIR_INVALID:($)=>`ORDER BY \u65B9\u5411\u5FC5\u987B\u662F ASC \u6216 DESC (direction: ${$})`,LIMIT_MUST_NON_NEGATIVE:($)=>`LIMIT \u6570\u91CF\u5FC5\u987B\u662F\u975E\u8D1F\u6570 (count: ${String($)})`,OFFSET_MUST_NON_NEGATIVE:($)=>`OFFSET \u5FC5\u987B\u662F\u975E\u8D1F\u6570 (offset: ${String($)})`,OFFSET_COUNT_MUST_NON_NEGATIVE:($)=>`OFFSET \u5FC5\u987B\u662F\u975E\u8D1F\u6570 (count: ${String($)})`,INSERT_NEED_TABLE:($)=>`INSERT \u9700\u8981\u8868\u540D (table: ${String($)})`,INSERT_NEED_DATA:($,J)=>`INSERT \u9700\u8981\u6570\u636E (table: ${String($)}, data: ${JSON.stringify(J)})`,INSERT_NEED_AT_LEAST_ONE_FIELD:($)=>`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${$})`,UPDATE_NEED_TABLE:"UPDATE \u9700\u8981\u8868\u540D",UPDATE_NEED_OBJECT:"UPDATE \u9700\u8981\u6570\u636E\u5BF9\u8C61",UPDATE_NEED_AT_LEAST_ONE_FIELD:"\u66F4\u65B0\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5",UPDATE_NEED_WHERE:"\u4E3A\u5B89\u5168\u8D77\u89C1\uFF0CUPDATE \u9700\u8981 WHERE \u6761\u4EF6",DELETE_NEED_TABLE:"DELETE \u9700\u8981\u8868\u540D",DELETE_NEED_WHERE:"\u4E3A\u5B89\u5168\u8D77\u89C1\uFF0CDELETE \u9700\u8981 WHERE \u6761\u4EF6",TO_DELETE_IN_NEED_TABLE:($)=>`toDeleteInSql \u9700\u8981\u975E\u7A7A\u8868\u540D (table: ${String($)})`,TO_DELETE_IN_NEED_ID_FIELD:($)=>`toDeleteInSql \u9700\u8981\u975E\u7A7A idField (idField: ${String($)})`,TO_DELETE_IN_NEED_IDS:"toDeleteInSql \u9700\u8981 ids \u6570\u7EC4",TO_UPDATE_CASE_NEED_TABLE:($)=>`toUpdateCaseByIdSql \u9700\u8981\u975E\u7A7A\u8868\u540D (table: ${String($)})`,TO_UPDATE_CASE_NEED_ID_FIELD:($)=>`toUpdateCaseByIdSql \u9700\u8981\u975E\u7A7A idField (idField: ${String($)})`,TO_UPDATE_CASE_NEED_ROWS:"toUpdateCaseByIdSql \u9700\u8981 rows \u6570\u7EC4",TO_UPDATE_CASE_NEED_FIELDS:"toUpdateCaseByIdSql \u9700\u8981 fields \u6570\u7EC4"};class h${_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(c.QUOTE_IDENT_NEED_STRING(J));let Z=J.trim();if(!Z)throw Error(c.IDENT_EMPTY);return`\`${Z.replace(/`/g,"``")}\``}}_isQuotedIdent($){return c0.isQuotedIdentPaired($)}_startsWithQuote($){return c0.startsWithQuote($)}reset(){return this._select=[],this._from="",this._where=[],this._joins=[],this._orderBy=[],this._groupBy=[],this._having=[],this._limit=null,this._offset=null,this._params=[],this}_escapeField($){if(typeof $!=="string")return $;if($=$.trim(),c0.assertPairedQuotedIdentIfStartsWithQuote($,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),$==="*"||this._isQuotedIdent($))return $;try{c0.assertNoExprField($)}catch{throw Error(c.FIELD_EXPR_NOT_ALLOWED($))}if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i),Z=J[0].trim(),X=J[1].trim();return c0.assertSafeAlias(X),`${this._escapeField(Z)} AS ${X}`}if($.includes("."))return $.split(".").map((Z)=>{if(Z=Z.trim(),Z==="*"||this._isQuotedIdent(Z))return Z;return c0.assertPairedQuotedIdentIfStartsWithQuote(Z,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),this._quoteIdent(Z)}).join(".");return this._quoteIdent($)}_validateIdentifierPart($,J){c0.assertSafeIdentifierPart($,J)}_escapeTable($){if(typeof $!=="string")return $;if($=$.trim(),this._startsWithQuote($)&&!this._isQuotedIdent($));if(this._isQuotedIdent($))return $;let J=$.split(/\s+/).filter((H)=>H.length>0);if(J.length===0)throw Error(c.FROM_EMPTY);if(J.length>2)throw Error(c.TABLE_REF_TOO_MANY_PARTS($));let Z=J[0].trim(),X=J.length===2?J[1].trim():null,Y=Z.split(".");if(Y.length>2)throw Error(c.TABLE_REF_SCHEMA_TOO_DEEP($));let G="";if(Y.length===2){let H=Y[0].trim(),z=Y[1].trim(),V=this._isQuotedIdent(H)?H:(()=>{if(this._startsWithQuote(H)&&!this._isQuotedIdent(H))throw Error(c.SCHEMA_QUOTE_NOT_PAIRED(H));return this._validateIdentifierPart(H,"schema"),this._quoteIdent(H)})(),O=this._isQuotedIdent(z)?z:(()=>{if(this._startsWithQuote(z)&&!this._isQuotedIdent(z))throw Error(c.TABLE_QUOTE_NOT_PAIRED(z));return this._validateIdentifierPart(z,"table"),this._quoteIdent(z)})();G=`${V}.${O}`}else{let H=Y[0].trim();if(this._isQuotedIdent(H))G=H;else{if(this._startsWithQuote(H)&&!this._isQuotedIdent(H))throw Error(c.TABLE_QUOTE_NOT_PAIRED(H));this._validateIdentifierPart(H,"table"),G=this._quoteIdent(H)}}if(X)return this._validateIdentifierPart(X,"alias"),`${G} ${X}`;return G}_validateParam($){c0.assertNoUndefinedParam($,"SQL \u53C2\u6570\u503C")}_applyOperator($,J,Z){let X=this._escapeField($);switch(J){case"$ne":case"$not":this._validateParam(Z),this._where.push(`${X} != ?`),this._params.push(Z);break;case"$in":if(!Array.isArray(Z))throw Error(`$in \u64CD\u4F5C\u7B26\u7684\u503C\u5FC5\u987B\u662F\u6570\u7EC4 (operator: ${J})`);if(Z.length===0)throw Error("$in \u64CD\u4F5C\u7B26\u7684\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A\u3002\u63D0\u793A\uFF1A\u7A7A\u6570\u7EC4\u4F1A\u5BFC\u81F4\u67E5\u8BE2\u6C38\u8FDC\u4E0D\u5339\u914D\u4EFB\u4F55\u8BB0\u5F55\uFF0C\u8FD9\u901A\u5E38\u4E0D\u662F\u9884\u671F\u884C\u4E3A\u3002\u8BF7\u68C0\u67E5\u67E5\u8BE2\u6761\u4EF6\u6216\u79FB\u9664\u8BE5\u5B57\u6BB5\u3002");let Y=Z.map(()=>"?").join(",");this._where.push(`${X} IN (${Y})`),this._params.push(...Z);break;case"$nin":case"$notIn":if(!Array.isArray(Z))throw Error(`$nin/$notIn \u64CD\u4F5C\u7B26\u7684\u503C\u5FC5\u987B\u662F\u6570\u7EC4 (operator: ${J})`);if(Z.length===0)throw Error("$nin/$notIn \u64CD\u4F5C\u7B26\u7684\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A\u3002\u63D0\u793A\uFF1A\u7A7A\u6570\u7EC4\u4F1A\u5BFC\u81F4\u67E5\u8BE2\u5339\u914D\u6240\u6709\u8BB0\u5F55\uFF0C\u8FD9\u901A\u5E38\u4E0D\u662F\u9884\u671F\u884C\u4E3A\u3002\u8BF7\u68C0\u67E5\u67E5\u8BE2\u6761\u4EF6\u6216\u79FB\u9664\u8BE5\u5B57\u6BB5\u3002");let G=Z.map(()=>"?").join(",");this._where.push(`${X} NOT IN (${G})`),this._params.push(...Z);break;case"$like":this._validateParam(Z),this._where.push(`${X} LIKE ?`),this._params.push(Z);break;case"$notLike":this._validateParam(Z),this._where.push(`${X} NOT LIKE ?`),this._params.push(Z);break;case"$gt":this._validateParam(Z),this._where.push(`${X} > ?`),this._params.push(Z);break;case"$gte":this._validateParam(Z),this._where.push(`${X} >= ?`),this._params.push(Z);break;case"$lt":this._validateParam(Z),this._where.push(`${X} < ?`),this._params.push(Z);break;case"$lte":this._validateParam(Z),this._where.push(`${X} <= ?`),this._params.push(Z);break;case"$between":if(Array.isArray(Z)&&Z.length===2)this._validateParam(Z[0]),this._validateParam(Z[1]),this._where.push(`${X} BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$notBetween":if(Array.isArray(Z)&&Z.length===2)this._validateParam(Z[0]),this._validateParam(Z[1]),this._where.push(`${X} NOT BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$null":if(Z===!0)this._where.push(`${X} IS NULL`);break;case"$notNull":if(Z===!0)this._where.push(`${X} IS NOT NULL`);break;default:this._validateParam(Z),this._where.push(`${X} = ?`),this._params.push(Z)}}_processWhereConditions($){if(!$||typeof $!=="object")return;Object.entries($).forEach(([J,Z])=>{if(Z===void 0)return;if(J==="$and"){if(Array.isArray(Z))Z.forEach((X)=>this._processWhereConditions(X))}else if(J==="$or"){if(Array.isArray(Z)){let X=[],Y=[];if(Z.forEach((G)=>{let H=new h$({quoteIdent:this._quoteIdent});if(H._processWhereConditions(G),H._where.length>0)X.push(`(${H._where.join(" AND ")})`),Y.push(...H._params)}),X.length>0)this._where.push(`(${X.join(" OR ")})`),this._params.push(...Y)}}else if(J.includes("$")){let X=J.lastIndexOf("$"),Y=J.substring(0,X),G="$"+J.substring(X+1);this._applyOperator(Y,G,Z)}else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))for(let[X,Y]of Object.entries(Z))this._applyOperator(J,X,Y);else{this._validateParam(Z);let X=this._escapeField(J);this._where.push(`${X} = ?`),this._params.push(Z)}})}getWhereConditions(){return{sql:this._where.length>0?this._where.join(" AND "):"",params:[...this._params]}}select($="*"){if(Array.isArray($))this._select=[...this._select,...$.map((J)=>this._escapeField(J))];else if(typeof $==="string")this._select.push(this._escapeField($));else throw Error(c.SELECT_FIELDS_INVALID);return this}selectRaw($){if(typeof $!=="string"||!$.trim())throw Error(c.SELECT_RAW_NEED_NON_EMPTY($));return this._select.push($),this}from($){if(typeof $!=="string"||!$.trim())throw Error(c.FROM_NEED_NON_EMPTY($));return this._from=this._escapeTable($.trim()),this}fromRaw($){if(typeof $!=="string"||!$.trim())throw Error(c.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(c.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(c.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(c.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(c.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(c.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`INNER JOIN ${Z} ON ${J}`),this}orderBy($){if(!Array.isArray($))throw Error(c.ORDER_BY_NEED_ARRAY);return $.forEach((J)=>{if(typeof J!=="string"||!J.includes("#"))throw Error(c.ORDER_BY_ITEM_NEED_HASH(J));let[Z,X]=J.split("#"),Y=Z.trim(),G=X.trim().toUpperCase();if(!Y)throw Error(c.ORDER_BY_FIELD_EMPTY(J));if(!["ASC","DESC"].includes(G))throw Error(c.ORDER_BY_DIR_INVALID(G));let H=this._escapeField(Y);this._orderBy.push(`${H} ${G}`)}),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(c.LIMIT_MUST_NON_NEGATIVE($));if(this._limit=Math.floor($),J!==void 0&&J!==null){if(typeof J!=="number"||J<0)throw Error(c.OFFSET_MUST_NON_NEGATIVE(J));this._offset=Math.floor(J)}return this}offset($){if(typeof $!=="number"||$<0)throw Error(c.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(c.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(c.INSERT_NEED_TABLE($));if(!J||typeof J!=="object")throw Error(c.INSERT_NEED_DATA($,J));let Z=this._escapeTable($);if(Array.isArray(J)){let X=c0.assertBatchInsertRowsConsistent(J,{table:$}),Y=X.map((O)=>this._escapeField(O)),G=X.map(()=>"?").join(", "),H=J.map(()=>`(${G})`).join(", "),z=`INSERT INTO ${Z} (${Y.join(", ")}) VALUES ${H}`,V=[];for(let O=0;O<J.length;O++){let F=J[O];for(let I of X)V.push(F[I])}return{sql:z,params:V}}else{let X=Object.keys(J);if(X.length===0)throw Error(c.INSERT_NEED_AT_LEAST_ONE_FIELD($));for(let V of X)this._validateParam(J[V]);let Y=X.map((V)=>this._escapeField(V)),G=X.map(()=>"?").join(", "),H=`INSERT INTO ${Z} (${Y.join(", ")}) VALUES (${G})`,z=X.map((V)=>J[V]);return{sql:H,params:z}}}toUpdateSql($,J){if(!$||typeof $!=="string")throw Error(c.UPDATE_NEED_TABLE);if(!J||typeof J!=="object"||Array.isArray(J))throw Error(c.UPDATE_NEED_OBJECT);let Z=Object.keys(J);if(Z.length===0)throw Error(c.UPDATE_NEED_AT_LEAST_ONE_FIELD);let X=this._escapeTable($),Y=Z.map((z)=>`${this._escapeField(z)} = ?`),G=[...Object.values(J),...this._params],H=`UPDATE ${X} SET ${Y.join(", ")}`;if(this._where.length>0)H+=" WHERE "+this._where.join(" AND ");else throw Error(c.UPDATE_NEED_WHERE);return{sql:H,params:G}}toDeleteSql($){if(!$||typeof $!=="string")throw Error(c.DELETE_NEED_TABLE);let Z=`DELETE FROM ${this._escapeTable($)}`;if(this._where.length>0)Z+=" WHERE "+this._where.join(" AND ");else throw Error(c.DELETE_NEED_WHERE);return{sql:Z,params:[...this._params]}}toCountSql(){let $="SELECT COUNT(*) as total";if(!this._from)throw Error(c.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(c.TO_DELETE_IN_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(c.TO_DELETE_IN_NEED_ID_FIELD($.idField));if(!Array.isArray($.ids))throw Error(c.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(c.TO_UPDATE_CASE_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(c.TO_UPDATE_CASE_NEED_ID_FIELD($.idField));if(!Array.isArray($.rows))throw Error(c.TO_UPDATE_CASE_NEED_ROWS);if($.rows.length===0)return{sql:"",params:[]};if(!Array.isArray($.fields))throw Error(c.TO_UPDATE_CASE_NEED_FIELDS);if($.fields.length===0)return{sql:"",params:[]};let J=$.rows.map((z)=>z.id),Z=J.map(()=>"?").join(","),X=[],Y=[],G=$.quoteIdent($.idField);for(let z of $.fields){let V=[];for(let F of $.rows){if(!(z in F.data))continue;V.push("WHEN ? THEN ?"),Y.push(F.id),Y.push(F.data[z])}if(V.length===0)continue;let O=$.quoteIdent(z);X.push(`${O} = CASE ${G} ${V.join(" ")} ELSE ${O} END`)}X.push(`${$.quoteIdent($.updatedAtField)} = ?`),Y.push($.updatedAtValue);for(let z of J)Y.push(z);let H=`UPDATE ${$.quoteIdent($.table)} SET ${X.join(", ")} WHERE ${G} IN (${Z})`;if($.stateGtZero&&$.stateField)H+=` AND ${$.quoteIdent($.stateField)} > 0`;return{sql:H,params:Y}}}var DQ=3600;class fJ{redis;dialect;sql=null;isTransaction=!1;constructor($){this.redis=$.redis,this.sql=$.sql||null,this.isTransaction=!!$.sql,this.dialect=$.dialect?$.dialect:new SJ}createSqlBuilder(){return new h$({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($),G=(await this.executeWithConn(X.sql,X.params)).data;if(!G||G.length===0)throw Error(`\u8868 ${$} \u4E0D\u5B58\u5728\u6216\u6CA1\u6709\u5B57\u6BB5`);let H=this.dialect.getTableColumnsFromResult(G);if(await this.redis.setObject(J,H,DQ)===null)P.warn({table:$,cacheKey:J,msg:"\u8868\u5B57\u6BB5\u7F13\u5B58\u5199\u5165 Redis \u5931\u8D25"});return H}async prepareQueryOptions($){let J=w$($.where||{},{excludeValues:[null,void 0]});if($.joins&&$.joins.length>0){let Y=($.fields||[]).map((z)=>g.processJoinField(z)),G=g.normalizeTableRef($.table),H=g.getJoinMainQualifier($.table);return{table:G,tableQualifier:H,fields:Y.length>0?Y:["*"],where:g.processJoinWhere(J),joins:$.joins,orderBy:g.processJoinOrderBy($.orderBy||[]),page:$.page||1,limit:$.limit||10}}let X=await g.fieldsToSnake(u($.table),$.fields||[],this.getTableColumns.bind(this));return{table:u($.table),tableQualifier:u($.table),fields:X,where:g.whereKeysToSnake(J),joins:void 0,orderBy:g.orderByToSnake($.orderBy||[]),page:$.page||1,limit:$.limit||10}}applyJoins($,J){if(!J||J.length===0)return;for(let Z of J){let X=g.normalizeTableRef(Z.table);switch(Z.type||"left"){case"inner":$.innerJoin(X,Z.on);break;case"right":$.rightJoin(X,Z.on);break;case"left":default:$.leftJoin(X,Z.on);break}}}async executeWithConn($,J){if(!this.sql)throw Error("\u6570\u636E\u5E93\u8FDE\u63A5\u672A\u521D\u59CB\u5316");if(typeof $!=="string")throw Error(`executeWithConn \u53EA\u63A5\u53D7\u5B57\u7B26\u4E32\u7C7B\u578B\u7684 SQL\uFF0C\u6536\u5230\u7C7B\u578B: ${typeof $}\uFF0C\u503C: ${JSON.stringify($)}`);let Z=Date.now(),X=Array.isArray(J)?J:[];try{let Y;if(X.length>0)Y=await this.sql.unsafe($,X);else Y=await this.sql.unsafe($);let G=Date.now()-Z;return{data:Y,sql:{sql:$,params:X,duration:G}}}catch(Y){let G=Date.now()-Z,H=Error(`SQL\u6267\u884C\u5931\u8D25: ${Y.message}`);throw H.originalError=Y,H.params=X,H.duration=G,H.sqlInfo={sql:$,params:X,duration:G},H}}async unsafe($,J){return await this.executeWithConn($,J)}async tableExists($){let J=u($),Z=this.dialect.tableExistsQuery(J),X=await this.executeWithConn(Z.sql,Z.params);return{data:(X.data?.[0]?.count||0)>0,sql:X.sql}}async getCount($){let{table:J,where:Z,joins:X,tableQualifier:Y}=await this.prepareQueryOptions($),G=this.createSqlBuilder().selectRaw("COUNT(*) as count").from(J).where(g.addDefaultStateFilter(Z,Y,!!X));this.applyJoins(G,X);let{sql:H,params:z}=G.toSelectSql(),V=await this.executeWithConn(H,z);return{data:V.data?.[0]?.count||0,sql:V.sql}}async getOne($){let{table:J,fields:Z,where:X,joins:Y,tableQualifier:G}=await this.prepareQueryOptions($),H=this.createSqlBuilder().select(Z).from(J).where(g.addDefaultStateFilter(X,G,!!Y));this.applyJoins(H,Y);let{sql:z,params:V}=H.toSelectSql(),O=await this.executeWithConn(z,V),I=O.data?.[0]||null;if(!I)return{data:null,sql:O.sql};let B=RZ(I),L=g.deserializeArrayFields(B);if(!L)return{data:null,sql:O.sql};return{data:xJ([L])[0],sql:O.sql}}async getList($){let J=await this.prepareQueryOptions($);if(J.page<1||J.page>1e4)throw Error(`\u9875\u7801\u5FC5\u987B\u5728 1 \u5230 10000 \u4E4B\u95F4 (table: ${$.table}, page: ${J.page}, limit: ${J.limit})`);if(J.limit<1||J.limit>1000)throw Error(`\u6BCF\u9875\u6570\u91CF\u5FC5\u987B\u5728 1 \u5230 1000 \u4E4B\u95F4 (table: ${$.table}, page: ${J.page}, limit: ${J.limit})`);let Z=g.addDefaultStateFilter(J.where,J.tableQualifier,!!J.joins),X=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(J.table).where(Z);this.applyJoins(X,J.joins);let{sql:Y,params:G}=X.toSelectSql(),H=await this.executeWithConn(Y,G),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:F,params:I}=O.toSelectSql(),B=await this.executeWithConn(F,I),L=B.data||[],w=IZ(L).map((T)=>g.deserializeArrayFields(T)).filter((T)=>T!==null);return{data:{lists:xJ(w),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=await this.prepareQueryOptions({...$,page:1,limit:10}),Y=g.addDefaultStateFilter(X.where,X.tableQualifier,!!X.joins),G=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(X.table).where(Y);this.applyJoins(G,X.joins);let{sql:H,params:z}=G.toSelectSql(),V=await this.executeWithConn(H,z),O=V.data?.[0]?.total||0;if(O===0)return{data:{lists:[],total:0},sql:{count:V.sql}};let F=this.createSqlBuilder().select(X.fields).from(X.table).where(Y).limit(1e4);if(this.applyJoins(F,X.joins),X.orderBy&&X.orderBy.length>0)F.orderBy(X.orderBy);let{sql:I,params:B}=F.toSelectSql(),L=await this.executeWithConn(I,B),C=L.data||[];if(C.length>=1000)P.warn({table:$.table,count:C.length,total:O,msg:"getAll \u8FD4\u56DE\u6570\u636E\u8FC7\u591A\uFF0C\u5EFA\u8BAE\u4F7F\u7528 getList \u5206\u9875\u67E5\u8BE2"});if(C.length>=1e4)P.warn({table:$.table,limit:1e4,total:O,msg:`getAll \u8FBE\u5230\u6700\u5927\u9650\u5236 ${1e4}\uFF0C\u5B9E\u9645\u603B\u6570 ${O}\uFF0C\u53EA\u8FD4\u56DE\u524D ${1e4} \u6761`});let T=IZ(C).map((E)=>g.deserializeArrayFields(E)).filter((E)=>E!==null);return{data:{lists:xJ(T),total:O},sql:{count:V.sql,data:L.sql}}}async insData($){let{table:J,data:Z}=$,X=u(J),Y=Date.now(),G;try{G=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=g.buildInsertRow({data:Z,id:G,now:Y});c0.assertNoUndefinedInRecord(H,`insData \u63D2\u5165\u6570\u636E (table: ${X})`);let z=this.createSqlBuilder(),{sql:V,params:O}=z.toInsertSql(X,H),F=await this.executeWithConn(V,O);return{data:H.id||F.data?.lastInsertRowid||0,sql:F.sql}}async insBatch($,J){if(J.length===0)return{data:[],sql:{sql:"",params:[],duration:0}};let Z=1000;if(J.length>Z)throw Error(`\u6279\u91CF\u63D2\u5165\u6570\u91CF ${J.length} \u8D85\u8FC7\u6700\u5927\u9650\u5236 ${Z}`);let X=u($),Y=[];for(let I=0;I<J.length;I++)Y.push(await this.redis.genTimeID());let G=Date.now(),H=J.map((I,B)=>{return g.buildInsertRow({data:I,id:Y[B],now:G})}),z=c0.assertBatchInsertRowsConsistent(H,{table:X}),V=this.createSqlBuilder(),{sql:O,params:F}=V.toInsertSql(X,H);try{let I=await this.executeWithConn(O,F);return{data:Y,sql:I.sql}}catch(I){throw P.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=u($),X=h$.toDeleteInSql({table:Z,idField:"id",ids:J,quoteIdent:this.dialect.quoteIdent.bind(this.dialect)}),Y=await this.executeWithConn(X.sql,X.params);return{data:Y.data?.changes||0,sql:Y.sql}}async updBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=u($),X=Date.now(),Y=[],G=new Set;for(let F of J){let I=g.buildPartialUpdateData({data:F.data,allowState:!0});for(let B of Object.keys(I))G.add(B);Y.push({id:F.id,data:I})}let H=Array.from(G).sort();if(H.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let z=h$.toUpdateCaseByIdSql({table:Z,idField:"id",rows:Y,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}=$,Y=w$(X,{excludeValues:[null,void 0]}),G=u(J),H=g.whereKeysToSnake(Y),z=g.buildUpdateRow({data:Z,now:Date.now(),allowState:!0}),V=g.addDefaultStateFilter(H,G,!1),O=this.createSqlBuilder().where(V),{sql:F,params:I}=O.toUpdateSql(G,z),B=await this.executeWithConn(F,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=u(J),Y=w$(Z,{excludeValues:[null,void 0]}),G=g.whereKeysToSnake(Y),H=this.createSqlBuilder().where(G),{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 fJ({redis:this.redis,sql:J,dialect:this.dialect});return await $(Z)})}async query($,J){return await this.executeWithConn($,J)}async exists($){let{table:J,where:Z,tableQualifier:X}=await this.prepareQueryOptions({...$,page:1,limit:1}),Y=this.createSqlBuilder().selectRaw("COUNT(1) as cnt").from(J).where(g.addDefaultStateFilter(Z,X,!1)).limit(1),{sql:G,params:H}=Y.toSelectSql(),z=await this.executeWithConn(G,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]}),Y=X.data;if(!Y)return{data:null,sql:X.sql};if(J in Y)return{data:Y[J],sql:X.sql};let G=J.replace(/_([a-z])/g,(z,V)=>V.toUpperCase());if(G!==J&&G in Y)return{data:Y[G],sql:X.sql};let H=J.replace(/[A-Z]/g,(z)=>`_${z.toLowerCase()}`);if(H!==J&&H in Y)return{data:Y[H],sql:X.sql};return{data:null,sql:X.sql}}async increment($,J,Z,X=1){let Y=u($),G=u(J);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(Y))throw Error(`\u65E0\u6548\u7684\u8868\u540D: ${Y}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(G))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=w$(Z,{excludeValues:[null,void 0]}),z=g.whereKeysToSnake(H),V=g.addDefaultStateFilter(z,Y,!1),O=this.createSqlBuilder().where(V),{sql:F,params:I}=O.getWhereConditions(),B=this.dialect.quoteIdent(Y),L=this.dialect.quoteIdent(G),C=F?`UPDATE ${B} SET ${L} = ${L} + ? WHERE ${F}`:`UPDATE ${B} SET ${L} = ${L} + ?`,w=await this.executeWithConn(C,[X,...I]);return{data:w.data?.changes||0,sql:w.sql}}async decrement($,J,Z,X=1){return await this.increment($,J,Z,-X)}}a();var kQ={name:"db",enable:!0,deps:["logger","redis"],async handler($){let J=$.config?$.config.nodeEnv:void 0;if(!$.redis)throw Error("\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25\uFF1Actx.redis \u672A\u521D\u59CB\u5316");try{let Z=z$.getSql(),X=$.config&&$.config.db?$.config.db.type:void 0,Y=X==="postgres"?"postgresql":X,G=f$(Y==="postgresql"||Y==="sqlite"?Y:"mysql");return new fJ({redis:$.redis,sql:Z,dialect:G})}catch(Z){throw P.error({env:J,err:Z,msg:"\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25"}),Z}}},kY=kQ;var v$=fW(jW(),1);class vX{config;constructor($={}){this.config={secret:$.secret||"befly-secret",expiresIn:$.expiresIn||"7d",algorithm:$.algorithm||"HS256"}}sign($,J={}){let Z=J.secret||this.config.secret||"befly-secret",X=J.algorithm||this.config.algorithm||"HS256";return v$.createSigner({key:Z,algorithm:X,expiresIn:J.expiresIn||this.config.expiresIn,iss:J.issuer,aud:J.audience,sub:J.subject,jti:J.jwtId,notBefore:typeof J.notBefore==="number"?J.notBefore:void 0})($)}verify($,J={}){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let Z=J.secret||this.config.secret||"befly-secret",X=this.config.algorithm||"HS256",Y=J.algorithms?J.algorithms:[X];return v$.createVerifier({key:Z,algorithms:Y,allowedIss:J.issuer,allowedAud:J.audience,allowedSub:J.subject,ignoreExpiration:J.ignoreExpiration,ignoreNotBefore:J.ignoreNotBefore,cache:!0,cacheTTL:600000})($)}decode($,J=!1){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(J){let Y=v$.createDecoder({complete:!0})($);return{header:Y.header,payload:Y.payload,signature:Y.signature}}return v$.createDecoder()($)}}var $9={name:"jwt",enable:!0,deps:[],handler:($)=>{return new vX($.config?$.config.auth:void 0)}},BW=$9;a();var J9={name:"logger",enable:!0,deps:[],async handler($){if($.config&&$.config.logger)P.configure($.config.logger);return P}},LW=J9;a();a();class NX{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,X={}){if(Z<=this.slowThresholdMs)return;P.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),Y=`${this.prefix}${$}`,G=Date.now();if(Z){let V=await this.client.setex(Y,Z,X),O=Date.now()-G;return this.logSlow("SETEX",Y,O,{ttl:Z}),V}let H=await this.client.set(Y,X),z=Date.now()-G;return this.logSlow("SET",Y,z),H}catch(X){return P.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),Y=Date.now()-Z;return this.logSlow("GET",J,Y),X?JSON.parse(X):null}catch(J){return P.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){P.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 Y=Date.now()-Z;this.logSlow("INCR",J,Y,{expireSeconds:1});let G=100+($%900+X-1)%900;return Number(`${$}${G}`)}async setString($,J,Z=null){try{let X=`${this.prefix}${$}`,Y=Date.now();if(Z){let z=await this.client.setex(X,Z,J),V=Date.now()-Y;return this.logSlow("SETEX",X,V,{ttl:Z}),z}let G=await this.client.set(X,J),H=Date.now()-Y;return this.logSlow("SET",X,H),G}catch(X){return P.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),Y=Date.now()-Z;return this.logSlow("GET",J,Y),X}catch(J){return P.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),Y=Date.now()-Z;return this.logSlow("EXISTS",J,Y),X}catch(J){return P.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),Y=Date.now()-Z;return this.logSlow("INCR",J,Y),X}catch(J){return P.error({err:J,msg:"Redis incr \u9519\u8BEF"}),0}}async incrWithExpire($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),Y=await this.client.incr(Z);if(Y===1)await this.client.expire(Z,J);let G=Date.now()-X;return this.logSlow("INCR",Z,G,{expireSeconds:J}),Y}catch(Z){return P.error({err:Z,msg:"Redis incrWithExpire \u9519\u8BEF"}),0}}async expire($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),Y=await this.client.expire(Z,J),G=Date.now()-X;return this.logSlow("EXPIRE",Z,G,{seconds:J}),Y}catch(Z){return P.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),Y=Date.now()-Z;return this.logSlow("TTL",J,Y),X}catch(J){return P.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 P.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(),Y=await this.client.sadd(Z,...J),G=Date.now()-X;return this.logSlow("SADD",Z,G,{membersCount:J.length}),Y}catch(Z){return P.error({err:Z,msg:"Redis sadd \u9519\u8BEF"}),0}}async sismember($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),Y=await this.client.sismember(Z,J),G=Date.now()-X;return this.logSlow("SISMEMBER",Z,G),Y}catch(Z){return P.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),Y=Date.now()-Z;return this.logSlow("SCARD",J,Y),X}catch(J){return P.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),Y=Date.now()-Z;return this.logSlow("SMEMBERS",J,Y),X}catch(J){return P.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 P.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 P.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),Y=Date.now()-Z;return this.logSlow("DEL",J,Y),X}catch(J){return P.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 P.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 P.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 P.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 P.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 P.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 P.error({err:$,msg:"Redis ping \u9519\u8BEF"}),$}}}var Z9={name:"redis",enable:!0,deps:["logger"],async handler($){let J=$.config?$.config.nodeEnv:void 0,Z=$.config&&$.config.redis?$.config.redis:{};try{return z$.getRedis(),new NX(Z.prefix)}catch(X){throw P.error({env:J,err:X,msg:"Redis \u521D\u59CB\u5316\u5931\u8D25"}),X}}},SW=Z9;function X9($,J={},Z={}){return{code:0,msg:$,data:J,...Z}}function Y9($,J=null,Z={}){return{code:1,msg:$,data:J,...Z}}function G9($,J,Z={}){let{status:X=200,contentType:Y,headers:G={}}=Z,H=Y,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,...G};return new Response(z,{status:X,headers:V})}var W9={name:"tool",enable:!0,deps:[],handler:()=>{return{Yes:X9,No:Y9,Raw:G9}}},CW=W9;m0();function EW($,J){let Z=J.name,X=o(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 wW(){let $=[],J=[LW,SW,kY,vY,CW,NY,BW,DY];for(let Z of J)$.push(EW("plugin",Z));return $}function TW(){let $=[],J=[KY,FY,SY,TY,CY];for(let Z of J)$.push(EW("hook",Z));return $}I$();import{existsSync as H9}from"fs";a();async function vW($,J){try{let X=(await import($))?.default;if(X===null||X===void 0)return J;return X}catch(Z){return P.warn({err:Z,file:$,msg:"importDefault \u5BFC\u5165\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C"}),J}}m0();function Q9($){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 z9($){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 V$($,J,Z,X){if(!H9($))return[];let Y=L$($),G=new Bun.Glob(X),H=[];try{let z=await G.scan({cwd:$,onlyFiles:!0,absolute:!0,followSymlinks:!0});for await(let V of z){if(V.endsWith(".d.ts"))continue;let O=L$(V),F=$J(O).name,I=xZ(Y,O),B=$J(I),L=B.dir?n(B.dir,B.name):B.name;if(F.startsWith("_"))continue;if(L.split("/").some((D)=>D.startsWith("_")))continue;let C=await vW(O,{}),w=K$(F),T="",N="";if(J==="core")T="",N=F;else if(J==="app")N=`app_${w}`;else{let D=Q9(O)||z9(O);if(!D)throw Error(`scanFiles addon moduleName \u89E3\u6790\u5931\u8D25\uFF1A\u672A\u627E\u5230 @befly-addon/<addon>/ \u6BB5\u843D\uFF1A${O}`);T=D,N=`addon_${K$(T)}_${w}`}let E={source:J,type:Z,sourceName:{core:"\u6838\u5FC3",addon:"\u7EC4\u4EF6",app:"\u9879\u76EE"}[J],filePath:O,relativePath:L,fileName:F,moduleName:N,addonName:T,fileBaseName:$J(O).base,fileDir:$,customKeys:o(C)?Object.keys(C):[]};if(Z==="table"){E.content=C,H.push(E);continue}if(Z==="api")E.auth=!0,E.rawBody=!1,E.method="POST",E.fields={},E.required=[];if(Z==="plugin"||Z==="hook")E.deps=[],E.name="",E.handler=null;if(tX(C,(D,h)=>{E[h]=D}),Z==="api")E.routePrefix=J==="app"?"/app":`/addon/${T}`,E.routePath=`/api${E.routePrefix}/${L}`;H.push(E)}}catch(z){let V=Error(`scanFiles failed: source=${J} type=${Z} dir=${Y} pattern=${X}`);throw V.cause=z,V}return H}var NW=async()=>{let $=[],J=[],Z=[],X=[],Y=await AY();X.push(...await V$(n(n0,"tables"),"app","table","*.json"));for(let G of Y)X.push(...await V$(n(G.fullPath,"tables"),"addon","table","*.json"));J.push(...wW()),J.push(...await V$(n(n0,"plugins"),"app","plugin","*.{ts,js}"));for(let G of Y)J.push(...await V$(n(G.fullPath,"plugins"),"addon","plugin","*.{ts,js}"));Z.push(...TW()),Z.push(...await V$(n(n0,"hooks"),"app","hook","*.{ts,js}"));for(let G of Y)Z.push(...await V$(n(G.fullPath,"hooks"),"addon","hook","*.{ts,js}"));$.push(...await V$(n(n0,"apis"),"app","api","**/*.{ts,js}"));for(let G of Y)$.push(...await V$(n(G.fullPath,"apis"),"addon","api","**/*.{ts,js}"));return{hooks:Z,plugins:J,apis:$,tables:X,addons:Y}};class U9{apis=new Map;plugins=[];hooks=[];context={};config=null;async start(){try{let $=Bun.nanoseconds();this.config=await Y1(),this.context.config=this.config;let{apis:J,tables:Z,plugins:X,hooks:Y,addons:G}=await NW();this.context.addons=G,await F1(J),await f1(Z),await N1(X),await R1(Y);let H=await T1(G,{disableMenus:this.config.disableMenus||[]});if(await z$.connect({db:this.config.db||{},redis:this.config.redis||{}}),this.plugins=await p1(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 EJ(this.context,Z),await s1(this.context,J),await r1(this.context,H),await l1(this.context,{devEmail:this.config.devEmail,devPassword:this.config.devPassword}),await o1(this.context),this.hooks=await c1(Y),this.apis=await b1(J);let z=m1(this.apis,this.hooks,this.context),V=n1(this.config.cors),O=Bun.serve({port:this.config.appPort,hostname:this.config.appHost,development:this.config.nodeEnv==="development",idleTimeout:30,fetch:async(C,w)=>{let T=new URL(C.url);if(T.pathname==="/")return Response.json({code:0,msg:`${this.config.appName} \u63A5\u53E3\u670D\u52A1\u5DF2\u542F\u52A8`});if(T.pathname.startsWith("/api/"))return z(C,w);return V(C)},error:(C)=>{if(P.error({err:C,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:C.message,stack:C.stack},{status:200});return Response.json({code:1,msg:"\u5185\u90E8\u670D\u52A1\u5668\u9519\u8BEF"},{status:200})}}),F=OY($),I=_Y(),B=I.role==="primary"?"\u4E3B\u8FDB\u7A0B":`\u5DE5\u4F5C\u8FDB\u7A0B #${I.instanceId}`,L=I.env==="standalone"?"":` [${I.env}]`;return P.info(`${this.config.appName} \u542F\u52A8\u6210\u529F! (${B}${L})`),P.info(`\u670D\u52A1\u5668\u542F\u52A8\u8017\u65F6: ${F}`),P.info(`\u670D\u52A1\u5668\u76D1\u542C\u5730\u5740: ${O.url}`),O}catch($){P.error({err:$,msg:"\u9879\u76EE\u542F\u52A8\u5931\u8D25"});try{await P.flush()}catch{}try{await P.shutdown()}catch{}if($ instanceof Error)throw $;throw Error(String($))}}}export{U9 as Befly};
|