bknd
Version:
Lightweight Firebase/Supabase alternative built to run anywhere — incl. Next.js, React Router, Astro, Cloudflare, Bun, Node, AWS Lambda & more.
245 lines • 905 kB
JavaScript
#!/usr/bin/env node
import{createRequire as Vd}from"node:module";var Ud=Object.create;var{getPrototypeOf:Rd,defineProperty:AK,getOwnPropertyNames:Md}=Object;var qd=Object.prototype.hasOwnProperty;var q1=($,f,W)=>{W=$!=null?Ud(Rd($)):{};let J=f||!$||!$.__esModule?AK(W,"default",{value:$,enumerable:!0}):W;for(let Z of Md($))if(!qd.call(J,Z))AK(J,Z,{get:()=>$[Z],enumerable:!0});return J};var d=($,f)=>()=>(f||$((f={exports:{}}).exports,f),f.exports);var V1=($,f)=>{for(var W in f)AK($,W,{get:f[W],enumerable:!0,configurable:!0,set:(J)=>f[W]=()=>J})};var K=($,f)=>()=>($&&(f=$($=0)),f);var u=Vd(import.meta.url);var FJ=d((Qd)=>{class xK extends Error{constructor($,f,W){super(W);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=f,this.exitCode=$,this.nestedError=void 0}}class jx extends xK{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Qd.CommanderError=xK;Qd.InvalidArgumentError=jx});var aX=d((_d)=>{var{InvalidArgumentError:Ad}=FJ();class gx{constructor($,f){switch(this.description=f||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue($,f){if(f===this.defaultValue||!Array.isArray(f))return[$];return f.concat($)}default($,f){return this.defaultValue=$,this.defaultValueDescription=f,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(f,W)=>{if(!this.argChoices.includes(f))throw new Ad(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(f,W);return f},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function xd($){let f=$.name()+($.variadic===!0?"...":"");return $.required?"<"+f+">":"["+f+"]"}_d.Argument=gx;_d.humanReadableArgName=xd});var _K=d((Bd)=>{var{humanReadableArgName:Fd}=aX();class bx{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands($){let f=$.commands.filter((W)=>!W._hidden);if($._hasImplicitHelpCommand()){let[,W,J]=$._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/),Z=$.createCommand(W).helpOption(!1);if(Z.description($._helpCommandDescription),J)Z.arguments(J);f.push(Z)}if(this.sortSubcommands)f.sort((W,J)=>{return W.name().localeCompare(J.name())});return f}compareOptions($,f){let W=(J)=>{return J.short?J.short.replace(/^-/,""):J.long.replace(/^--/,"")};return W($).localeCompare(W(f))}visibleOptions($){let f=$.options.filter((Z)=>!Z.hidden),W=$._hasHelpOption&&$._helpShortFlag&&!$._findOption($._helpShortFlag),J=$._hasHelpOption&&!$._findOption($._helpLongFlag);if(W||J){let Z;if(!W)Z=$.createOption($._helpLongFlag,$._helpDescription);else if(!J)Z=$.createOption($._helpShortFlag,$._helpDescription);else Z=$.createOption($._helpFlags,$._helpDescription);f.push(Z)}if(this.sortOptions)f.sort(this.compareOptions);return f}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let f=[];for(let W=$.parent;W;W=W.parent){let J=W.options.filter((Z)=>!Z.hidden);f.push(...J)}if(this.sortOptions)f.sort(this.compareOptions);return f}visibleArguments($){if($._argsDescription)$._args.forEach((f)=>{f.description=f.description||$._argsDescription[f.name()]||""});if($._args.find((f)=>f.description))return $._args;return[]}subcommandTerm($){let f=$._args.map((W)=>Fd(W)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(f?" "+f:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,f){return f.visibleCommands($).reduce((W,J)=>{return Math.max(W,f.subcommandTerm(J).length)},0)}longestOptionTermLength($,f){return f.visibleOptions($).reduce((W,J)=>{return Math.max(W,f.optionTerm(J).length)},0)}longestGlobalOptionTermLength($,f){return f.visibleGlobalOptions($).reduce((W,J)=>{return Math.max(W,f.optionTerm(J).length)},0)}longestArgumentTermLength($,f){return f.visibleArguments($).reduce((W,J)=>{return Math.max(W,f.argumentTerm(J).length)},0)}commandUsage($){let f=$._name;if($._aliases[0])f=f+"|"+$._aliases[0];let W="";for(let J=$.parent;J;J=J.parent)W=J.name()+" "+W;return W+f+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let f=[];if($.argChoices)f.push(`choices: ${$.argChoices.map((W)=>JSON.stringify(W)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")f.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)f.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)f.push(`env: ${$.envVar}`);if(f.length>0)return`${$.description} (${f.join(", ")})`;return $.description}argumentDescription($){let f=[];if($.argChoices)f.push(`choices: ${$.argChoices.map((W)=>JSON.stringify(W)).join(", ")}`);if($.defaultValue!==void 0)f.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(f.length>0){let W=`(${f.join(", ")})`;if($.description)return`${$.description} ${W}`;return W}return $.description}formatHelp($,f){let W=f.padWidth($,f),J=f.helpWidth||80,Z=2,X=2;function z(q,V){if(V){let Q=`${q.padEnd(W+2)}${V}`;return f.wrap(Q,J-2,W+2)}return q}function w(q){return q.join(`
`).replace(/^/gm," ".repeat(2))}let G=[`Usage: ${f.commandUsage($)}`,""],Y=f.commandDescription($);if(Y.length>0)G=G.concat([Y,""]);let L=f.visibleArguments($).map((q)=>{return z(f.argumentTerm(q),f.argumentDescription(q))});if(L.length>0)G=G.concat(["Arguments:",w(L),""]);let U=f.visibleOptions($).map((q)=>{return z(f.optionTerm(q),f.optionDescription(q))});if(U.length>0)G=G.concat(["Options:",w(U),""]);if(this.showGlobalOptions){let q=f.visibleGlobalOptions($).map((V)=>{return z(f.optionTerm(V),f.optionDescription(V))});if(q.length>0)G=G.concat(["Global Options:",w(q),""])}let M=f.visibleCommands($).map((q)=>{return z(f.subcommandTerm(q),f.subcommandDescription(q))});if(M.length>0)G=G.concat(["Commands:",w(M),""]);return G.join(`
`)}padWidth($,f){return Math.max(f.longestOptionTermLength($,f),f.longestGlobalOptionTermLength($,f),f.longestSubcommandTermLength($,f),f.longestArgumentTermLength($,f))}wrap($,f,W,J=40){if($.match(/[\n]\s+/))return $;let Z=f-W;if(Z<J)return $;let X=$.slice(0,W),z=$.slice(W),w=" ".repeat(W),G=new RegExp(".{1,"+(Z-1)+"}([\\s]|$)|[^\\s]+?([\\s]|$)","g"),Y=z.match(G)||[];return X+Y.map((L,U)=>{if(L.slice(-1)===`
`)L=L.slice(0,L.length-1);return(U>0?w:"")+L.trimRight()}).join(`
`)}}Bd.Help=bx});var NK=d((Ed)=>{var{InvalidArgumentError:Pd}=FJ();class ux{constructor($,f){this.flags=$,this.description=f||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let W=dx($);if(this.short=W.shortFlag,this.long=W.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default($,f){return this.defaultValue=$,this.defaultValueDescription=f,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){return this.implied=Object.assign(this.implied||{},$),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_concatValue($,f){if(f===this.defaultValue||!Array.isArray(f))return[$];return f.concat($)}choices($){return this.argChoices=$.slice(),this.parseArg=(f,W)=>{if(!this.argChoices.includes(f))throw new Pd(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(f,W);return f},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){return Cd(this.name().replace(/^no-/,""))}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class cx{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((f)=>{if(f.negate)this.negativeOptions.set(f.attributeName(),f);else this.positiveOptions.set(f.attributeName(),f)}),this.negativeOptions.forEach((f,W)=>{if(this.positiveOptions.has(W))this.dualOptions.add(W)})}valueFromOption($,f){let W=f.attributeName();if(!this.dualOptions.has(W))return!0;let J=this.negativeOptions.get(W).presetArg,Z=J!==void 0?J:!1;return f.negate===(Z===$)}}function Cd($){return $.split("-").reduce((f,W)=>{return f+W[0].toUpperCase()+W.slice(1)})}function dx($){let f,W,J=$.split(/[ |,]+/);if(J.length>1&&!/^[[<]/.test(J[1]))f=J.shift();if(W=J.shift(),!f&&/^-[^-]$/.test(W))f=W,W=void 0;return{shortFlag:f,longFlag:W}}Ed.Option=ux;Ed.splitOptionFlags=dx;Ed.DualOptions=cx});var ix=d((yd)=>{function md($,f){if(Math.abs($.length-f.length)>3)return Math.max($.length,f.length);let W=[];for(let J=0;J<=$.length;J++)W[J]=[J];for(let J=0;J<=f.length;J++)W[0][J]=J;for(let J=1;J<=f.length;J++)for(let Z=1;Z<=$.length;Z++){let X=1;if($[Z-1]===f[J-1])X=0;else X=1;if(W[Z][J]=Math.min(W[Z-1][J]+1,W[Z][J-1]+1,W[Z-1][J-1]+X),Z>1&&J>1&&$[Z-1]===f[J-2]&&$[Z-2]===f[J-1])W[Z][J]=Math.min(W[Z][J],W[Z-2][J-2]+1)}return W[$.length][f.length]}function kd($,f){if(!f||f.length===0)return"";f=Array.from(new Set(f));let W=$.startsWith("--");if(W)$=$.slice(2),f=f.map((z)=>z.slice(2));let J=[],Z=3,X=0.4;if(f.forEach((z)=>{if(z.length<=1)return;let w=md($,z),G=Math.max($.length,z.length);if((G-w)/G>X){if(w<Z)Z=w,J=[z];else if(w===Z)J.push(z)}}),J.sort((z,w)=>z.localeCompare(w)),W)J=J.map((z)=>`--${z}`);if(J.length>1)return`
(Did you mean one of ${J.join(", ")}?)`;if(J.length===1)return`
(Did you mean ${J[0]}?)`;return""}yd.suggestSimilar=kd});var sx=d((rd)=>{var gd=u("events").EventEmitter,SK=u("child_process"),f9=u("path"),FK=u("fs"),n0=u("process"),{Argument:bd,humanReadableArgName:ud}=aX(),{CommanderError:BK}=FJ(),{Help:cd}=_K(),{Option:rx,splitOptionFlags:dd,DualOptions:id}=NK(),{suggestSimilar:lx}=ix();class TK extends gd{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this._args=[],this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:(f)=>n0.stdout.write(f),writeErr:(f)=>n0.stderr.write(f),getOutHelpWidth:()=>n0.stdout.isTTY?n0.stdout.columns:void 0,getErrHelpWidth:()=>n0.stderr.isTTY?n0.stderr.columns:void 0,outputError:(f,W)=>W(f)},this._hidden=!1,this._hasHelpOption=!0,this._helpFlags="-h, --help",this._helpDescription="display help for command",this._helpShortFlag="-h",this._helpLongFlag="--help",this._addImplicitHelpCommand=void 0,this._helpCommandName="help",this._helpCommandnameAndArgs="help [command]",this._helpCommandDescription="display help for command",this._helpConfiguration={}}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._hasHelpOption=$._hasHelpOption,this._helpFlags=$._helpFlags,this._helpDescription=$._helpDescription,this._helpShortFlag=$._helpShortFlag,this._helpLongFlag=$._helpLongFlag,this._helpCommandName=$._helpCommandName,this._helpCommandnameAndArgs=$._helpCommandnameAndArgs,this._helpCommandDescription=$._helpCommandDescription,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}command($,f,W){let J=f,Z=W;if(typeof J==="object"&&J!==null)Z=J,J=null;Z=Z||{};let[,X,z]=$.match(/([^ ]+) *(.*)/),w=this.createCommand(X);if(J)w.description(J),w._executableHandler=!0;if(Z.isDefault)this._defaultCommandName=w._name;if(w._hidden=!!(Z.noHelp||Z.hidden),w._executableFile=Z.executableFile||null,z)w.arguments(z);if(this.commands.push(w),w.parent=this,w.copyInheritedSettings(this),J)return this;return w}createCommand($){return new TK($)}createHelp(){return Object.assign(new cd,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,$),this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,f){if(!$._name)throw new Error(`Command passed to .addCommand() must have a name
- specify the name in Command constructor or using .name()`);if(f=f||{},f.isDefault)this._defaultCommandName=$._name;if(f.noHelp||f.hidden)$._hidden=!0;return this.commands.push($),$.parent=this,this}createArgument($,f){return new bd($,f)}argument($,f,W,J){let Z=this.createArgument($,f);if(typeof W==="function")Z.default(J).argParser(W);else Z.default(W);return this.addArgument(Z),this}arguments($){return $.split(/ +/).forEach((f)=>{this.argument(f)}),this}addArgument($){let f=this._args.slice(-1)[0];if(f&&f.variadic)throw new Error(`only the last argument can be variadic '${f.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${$.name()}'`);return this._args.push($),this}addHelpCommand($,f){if($===!1)this._addImplicitHelpCommand=!1;else{if(this._addImplicitHelpCommand=!0,typeof $==="string")this._helpCommandName=$.split(" ")[0],this._helpCommandnameAndArgs=$;this._helpCommandDescription=f||this._helpCommandDescription}return this}_hasImplicitHelpCommand(){if(this._addImplicitHelpCommand===void 0)return this.commands.length&&!this._actionHandler&&!this._findCommand("help");return this._addImplicitHelpCommand}hook($,f){let W=["preSubcommand","preAction","postAction"];if(!W.includes($))throw new Error(`Unexpected value for event passed to hook : '${$}'.
Expecting one of '${W.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(f);else this._lifeCycleHooks[$]=[f];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(f)=>{if(f.code!=="commander.executeSubCommandAsync")throw f};return this}_exit($,f,W){if(this._exitCallback)this._exitCallback(new BK($,f,W));n0.exit($)}action($){let f=(W)=>{let J=this._args.length,Z=W.slice(0,J);if(this._storeOptionsAsProperties)Z[J]=this;else Z[J]=this.opts();return Z.push(this),$.apply(this,Z)};return this._actionHandler=f,this}createOption($,f){return new rx($,f)}addOption($){let f=$.name(),W=$.attributeName();if($.negate){let Z=$.long.replace(/^--no-/,"--");if(!this._findOption(Z))this.setOptionValueWithSource(W,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(W,$.defaultValue,"default");this.options.push($);let J=(Z,X,z)=>{if(Z==null&&$.presetArg!==void 0)Z=$.presetArg;let w=this.getOptionValue(W);if(Z!==null&&$.parseArg)try{Z=$.parseArg(Z,w)}catch(G){if(G.code==="commander.invalidArgument"){let Y=`${X} ${G.message}`;this.error(Y,{exitCode:G.exitCode,code:G.code})}throw G}else if(Z!==null&&$.variadic)Z=$._concatValue(Z,w);if(Z==null)if($.negate)Z=!1;else if($.isBoolean()||$.optional)Z=!0;else Z="";this.setOptionValueWithSource(W,Z,z)};if(this.on("option:"+f,(Z)=>{let X=`error: option '${$.flags}' argument '${Z}' is invalid.`;J(Z,X,"cli")}),$.envVar)this.on("optionEnv:"+f,(Z)=>{let X=`error: option '${$.flags}' value '${Z}' from env '${$.envVar}' is invalid.`;J(Z,X,"env")});return this}_optionEx($,f,W,J,Z){if(typeof f==="object"&&f instanceof rx)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let X=this.createOption(f,W);if(X.makeOptionMandatory(!!$.mandatory),typeof J==="function")X.default(Z).argParser(J);else if(J instanceof RegExp){let z=J;J=(w,G)=>{let Y=z.exec(w);return Y?Y[0]:G},X.default(Z).argParser(J)}else X.default(J);return this.addOption(X)}option($,f,W,J){return this._optionEx({},$,f,W,J)}requiredOption($,f,W,J){return this._optionEx({mandatory:!0},$,f,W,J)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){if(this._passThroughOptions=!!$,!!this.parent&&$&&!this.parent._enablePositionalOptions)throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");return this}storeOptionsAsProperties($=!0){if(this._storeOptionsAsProperties=!!$,this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");return this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,f){return this.setOptionValueWithSource($,f,void 0)}setOptionValueWithSource($,f,W){if(this._storeOptionsAsProperties)this[$]=f;else this._optionValues[$]=f;return this._optionValueSources[$]=W,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let f;return BJ(this).forEach((W)=>{if(W.getOptionValueSource($)!==void 0)f=W.getOptionValueSource($)}),f}_prepareUserArgs($,f){if($!==void 0&&!Array.isArray($))throw new Error("first parameter to parse must be array or undefined");if(f=f||{},$===void 0){if($=n0.argv,n0.versions&&n0.versions.electron)f.from="electron"}this.rawArgs=$.slice();let W;switch(f.from){case void 0:case"node":this._scriptPath=$[1],W=$.slice(2);break;case"electron":if(n0.defaultApp)this._scriptPath=$[1],W=$.slice(2);else W=$.slice(1);break;case"user":W=$.slice(0);break;default:throw new Error(`unexpected parse option { from: '${f.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",W}parse($,f){let W=this._prepareUserArgs($,f);return this._parseCommand([],W),this}async parseAsync($,f){let W=this._prepareUserArgs($,f);return await this._parseCommand([],W),this}_executeSubCommand($,f){f=f.slice();let W=!1,J=[".js",".ts",".tsx",".mjs",".cjs"];function Z(Y,L){let U=f9.resolve(Y,L);if(FK.existsSync(U))return U;if(J.includes(f9.extname(L)))return;let M=J.find((q)=>FK.existsSync(`${U}${q}`));if(M)return`${U}${M}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let X=$._executableFile||`${this._name}-${$._name}`,z=this._executableDir||"";if(this._scriptPath){let Y;try{Y=FK.realpathSync(this._scriptPath)}catch(L){Y=this._scriptPath}z=f9.resolve(f9.dirname(Y),z)}if(z){let Y=Z(z,X);if(!Y&&!$._executableFile&&this._scriptPath){let L=f9.basename(this._scriptPath,f9.extname(this._scriptPath));if(L!==this._name)Y=Z(z,`${L}-${$._name}`)}X=Y||X}W=J.includes(f9.extname(X));let w;if(n0.platform!=="win32")if(W)f.unshift(X),f=nx(n0.execArgv).concat(f),w=SK.spawn(n0.argv[0],f,{stdio:"inherit"});else w=SK.spawn(X,f,{stdio:"inherit"});else f.unshift(X),f=nx(n0.execArgv).concat(f),w=SK.spawn(n0.execPath,f,{stdio:"inherit"});if(!w.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((L)=>{n0.on(L,()=>{if(w.killed===!1&&w.exitCode===null)w.kill(L)})});let G=this._exitCallback;if(!G)w.on("close",n0.exit.bind(n0));else w.on("close",()=>{G(new BK(n0.exitCode||0,"commander.executeSubCommandAsync","(close)"))});w.on("error",(Y)=>{if(Y.code==="ENOENT"){let L=z?`searched for local subcommand relative to directory '${z}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",U=`'${X}' does not exist
- if '${$._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
- ${L}`;throw new Error(U)}else if(Y.code==="EACCES")throw new Error(`'${X}' not executable`);if(!G)n0.exit(1);else{let L=new BK(1,"commander.executeSubCommandAsync","(error)");L.nestedError=Y,G(L)}}),this.runningCommand=w}_dispatchSubcommand($,f,W){let J=this._findCommand($);if(!J)this.help({error:!0});let Z;return Z=this._chainOrCallSubCommandHook(Z,J,"preSubcommand"),Z=this._chainOrCall(Z,()=>{if(J._executableHandler)this._executeSubCommand(J,f.concat(W));else return J._parseCommand(f,W)}),Z}_checkNumberOfArguments(){if(this._args.forEach(($,f)=>{if($.required&&this.args[f]==null)this.missingArgument($.name())}),this._args.length>0&&this._args[this._args.length-1].variadic)return;if(this.args.length>this._args.length)this._excessArguments(this.args)}_processArguments(){let $=(W,J,Z)=>{let X=J;if(J!==null&&W.parseArg)try{X=W.parseArg(J,Z)}catch(z){if(z.code==="commander.invalidArgument"){let w=`error: command-argument value '${J}' is invalid for argument '${W.name()}'. ${z.message}`;this.error(w,{exitCode:z.exitCode,code:z.code})}throw z}return X};this._checkNumberOfArguments();let f=[];this._args.forEach((W,J)=>{let Z=W.defaultValue;if(W.variadic){if(J<this.args.length){if(Z=this.args.slice(J),W.parseArg)Z=Z.reduce((X,z)=>{return $(W,z,X)},W.defaultValue)}else if(Z===void 0)Z=[]}else if(J<this.args.length){if(Z=this.args[J],W.parseArg)Z=$(W,Z,W.defaultValue)}f[J]=Z}),this.processedArgs=f}_chainOrCall($,f){if($&&$.then&&typeof $.then==="function")return $.then(()=>f());return f()}_chainOrCallHooks($,f){let W=$,J=[];if(BJ(this).reverse().filter((Z)=>Z._lifeCycleHooks[f]!==void 0).forEach((Z)=>{Z._lifeCycleHooks[f].forEach((X)=>{J.push({hookedCommand:Z,callback:X})})}),f==="postAction")J.reverse();return J.forEach((Z)=>{W=this._chainOrCall(W,()=>{return Z.callback(Z.hookedCommand,this)})}),W}_chainOrCallSubCommandHook($,f,W){let J=$;if(this._lifeCycleHooks[W]!==void 0)this._lifeCycleHooks[W].forEach((Z)=>{J=this._chainOrCall(J,()=>{return Z(this,f)})});return J}_parseCommand($,f){let W=this.parseOptions(f);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(W.operands),f=W.unknown,this.args=$.concat(f),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),f);if(this._hasImplicitHelpCommand()&&$[0]===this._helpCommandName){if($.length===1)this.help();return this._dispatchSubcommand($[1],[],[this._helpLongFlag])}if(this._defaultCommandName)return px(this,f),this._dispatchSubcommand(this._defaultCommandName,$,f);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});px(this,W.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let J=()=>{if(W.unknown.length>0)this.unknownOption(W.unknown[0])},Z=`command:${this.name()}`;if(this._actionHandler){J(),this._processArguments();let X;if(X=this._chainOrCallHooks(X,"preAction"),X=this._chainOrCall(X,()=>this._actionHandler(this.processedArgs)),this.parent)X=this._chainOrCall(X,()=>{this.parent.emit(Z,$,f)});return X=this._chainOrCallHooks(X,"postAction"),X}if(this.parent&&this.parent.listenerCount(Z))J(),this._processArguments(),this.parent.emit(Z,$,f);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,f);if(this.listenerCount("command:*"))this.emit("command:*",$,f);else if(this.commands.length)this.unknownCommand();else J(),this._processArguments()}else if(this.commands.length)J(),this.help({error:!0});else J(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((f)=>f._name===$||f._aliases.includes($))}_findOption($){return this.options.find((f)=>f.is($))}_checkForMissingMandatoryOptions(){for(let $=this;$;$=$.parent)$.options.forEach((f)=>{if(f.mandatory&&$.getOptionValue(f.attributeName())===void 0)$.missingMandatoryOptionValue(f)})}_checkForConflictingLocalOptions(){let $=this.options.filter((W)=>{let J=W.attributeName();if(this.getOptionValue(J)===void 0)return!1;return this.getOptionValueSource(J)!=="default"});$.filter((W)=>W.conflictsWith.length>0).forEach((W)=>{let J=$.find((Z)=>W.conflictsWith.includes(Z.attributeName()));if(J)this._conflictingOption(W,J)})}_checkForConflictingOptions(){for(let $=this;$;$=$.parent)$._checkForConflictingLocalOptions()}parseOptions($){let f=[],W=[],J=f,Z=$.slice();function X(w){return w.length>1&&w[0]==="-"}let z=null;while(Z.length){let w=Z.shift();if(w==="--"){if(J===W)J.push(w);J.push(...Z);break}if(z&&!X(w)){this.emit(`option:${z.name()}`,w);continue}if(z=null,X(w)){let G=this._findOption(w);if(G){if(G.required){let Y=Z.shift();if(Y===void 0)this.optionMissingArgument(G);this.emit(`option:${G.name()}`,Y)}else if(G.optional){let Y=null;if(Z.length>0&&!X(Z[0]))Y=Z.shift();this.emit(`option:${G.name()}`,Y)}else this.emit(`option:${G.name()}`);z=G.variadic?G:null;continue}}if(w.length>2&&w[0]==="-"&&w[1]!=="-"){let G=this._findOption(`-${w[1]}`);if(G){if(G.required||G.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${G.name()}`,w.slice(2));else this.emit(`option:${G.name()}`),Z.unshift(`-${w.slice(2)}`);continue}}if(/^--[^=]+=/.test(w)){let G=w.indexOf("="),Y=this._findOption(w.slice(0,G));if(Y&&(Y.required||Y.optional)){this.emit(`option:${Y.name()}`,w.slice(G+1));continue}}if(X(w))J=W;if((this._enablePositionalOptions||this._passThroughOptions)&&f.length===0&&W.length===0){if(this._findCommand(w)){if(f.push(w),Z.length>0)W.push(...Z);break}else if(w===this._helpCommandName&&this._hasImplicitHelpCommand()){if(f.push(w),Z.length>0)f.push(...Z);break}else if(this._defaultCommandName){if(W.push(w),Z.length>0)W.push(...Z);break}}if(this._passThroughOptions){if(J.push(w),Z.length>0)J.push(...Z);break}J.push(w)}return{operands:f,unknown:W}}opts(){if(this._storeOptionsAsProperties){let $={},f=this.options.length;for(let W=0;W<f;W++){let J=this.options[W].attributeName();$[J]=J===this._versionOptionName?this._version:this[J]}return $}return this._optionValues}optsWithGlobals(){return BJ(this).reduce(($,f)=>Object.assign($,f.opts()),{})}error($,f){if(this._outputConfiguration.outputError(`${$}
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
`),this.outputHelp({error:!0});let W=f||{},J=W.exitCode||1,Z=W.code||"commander.error";this._exit(J,Z,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in n0.env){let f=$.attributeName();if(this.getOptionValue(f)===void 0||["default","config","env"].includes(this.getOptionValueSource(f)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,n0.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new id(this.options),f=(W)=>{return this.getOptionValue(W)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(W))};this.options.filter((W)=>W.implied!==void 0&&f(W.attributeName())&&$.valueFromOption(this.getOptionValue(W.attributeName()),W)).forEach((W)=>{Object.keys(W.implied).filter((J)=>!f(J)).forEach((J)=>{this.setOptionValueWithSource(J,W.implied[J],"implied")})})}missingArgument($){let f=`error: missing required argument '${$}'`;this.error(f,{code:"commander.missingArgument"})}optionMissingArgument($){let f=`error: option '${$.flags}' argument missing`;this.error(f,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let f=`error: required option '${$.flags}' not specified`;this.error(f,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,f){let W=(X)=>{let z=X.attributeName(),w=this.getOptionValue(z),G=this.options.find((L)=>L.negate&&z===L.attributeName()),Y=this.options.find((L)=>!L.negate&&z===L.attributeName());if(G&&(G.presetArg===void 0&&w===!1||G.presetArg!==void 0&&w===G.presetArg))return G;return Y||X},J=(X)=>{let z=W(X),w=z.attributeName();if(this.getOptionValueSource(w)==="env")return`environment variable '${z.envVar}'`;return`option '${z.flags}'`},Z=`error: ${J($)} cannot be used with ${J(f)}`;this.error(Z,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let f="";if($.startsWith("--")&&this._showSuggestionAfterError){let J=[],Z=this;do{let X=Z.createHelp().visibleOptions(Z).filter((z)=>z.long).map((z)=>z.long);J=J.concat(X),Z=Z.parent}while(Z&&!Z._enablePositionalOptions);f=lx($,J)}let W=`error: unknown option '${$}'${f}`;this.error(W,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let f=this._args.length,W=f===1?"":"s",Z=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${f} argument${W} but got ${$.length}.`;this.error(Z,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],f="";if(this._showSuggestionAfterError){let J=[];this.createHelp().visibleCommands(this).forEach((Z)=>{if(J.push(Z.name()),Z.alias())J.push(Z.alias())}),f=lx($,J)}let W=`error: unknown command '${$}'${f}`;this.error(W,{code:"commander.unknownCommand"})}version($,f,W){if($===void 0)return this._version;this._version=$,f=f||"-V, --version",W=W||"output the version number";let J=this.createOption(f,W);return this._versionOptionName=J.attributeName(),this.options.push(J),this.on("option:"+J.name(),()=>{this._outputConfiguration.writeOut(`${$}
`),this._exit(0,"commander.version",$)}),this}description($,f){if($===void 0&&f===void 0)return this._description;if(this._description=$,f)this._argsDescription=f;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let f=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)f=this.commands[this.commands.length-1];if($===f._name)throw new Error("Command alias can't be the same as its name");return f._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((f)=>this.alias(f)),this}usage($){if($===void 0){if(this._usage)return this._usage;let f=this._args.map((W)=>{return ud(W)});return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this._args.length?f:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}nameFromFilename($){return this._name=f9.basename($,f9.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let f=this.createHelp();if(f.helpWidth===void 0)f.helpWidth=$&&$.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return f.formatHelp(this,f)}_getHelpContext($){$=$||{};let f={error:!!$.error},W;if(f.error)W=(J)=>this._outputConfiguration.writeErr(J);else W=(J)=>this._outputConfiguration.writeOut(J);return f.write=$.write||W,f.command=this,f}outputHelp($){let f;if(typeof $==="function")f=$,$=void 0;let W=this._getHelpContext($);BJ(this).reverse().forEach((Z)=>Z.emit("beforeAllHelp",W)),this.emit("beforeHelp",W);let J=this.helpInformation(W);if(f){if(J=f(J),typeof J!=="string"&&!Buffer.isBuffer(J))throw new Error("outputHelp callback must return a string or a Buffer")}W.write(J),this.emit(this._helpLongFlag),this.emit("afterHelp",W),BJ(this).forEach((Z)=>Z.emit("afterAllHelp",W))}helpOption($,f){if(typeof $==="boolean")return this._hasHelpOption=$,this;this._helpFlags=$||this._helpFlags,this._helpDescription=f||this._helpDescription;let W=dd(this._helpFlags);return this._helpShortFlag=W.shortFlag,this._helpLongFlag=W.longFlag,this}help($){this.outputHelp($);let f=n0.exitCode||0;if(f===0&&$&&typeof $!=="function"&&$.error)f=1;this._exit(f,"commander.help","(outputHelp)")}addHelpText($,f){let W=["beforeAll","before","after","afterAll"];if(!W.includes($))throw new Error(`Unexpected value for position to addHelpText.
Expecting one of '${W.join("', '")}'`);let J=`${$}Help`;return this.on(J,(Z)=>{let X;if(typeof f==="function")X=f({error:Z.error,command:Z.command});else X=f;if(X)Z.write(`${X}
`)}),this}}function px($,f){if($._hasHelpOption&&f.find((J)=>J===$._helpLongFlag||J===$._helpShortFlag))$.outputHelp(),$._exit(0,"commander.helpDisplayed","(outputHelp)")}function nx($){return $.map((f)=>{if(!f.startsWith("--inspect"))return f;let W,J="127.0.0.1",Z="9229",X;if((X=f.match(/^(--inspect(-brk)?)$/))!==null)W=X[1];else if((X=f.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(W=X[1],/^\d+$/.test(X[3]))Z=X[3];else J=X[3];else if((X=f.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)W=X[1],J=X[3],Z=X[4];if(W&&Z!=="0")return`${W}=${J}:${parseInt(Z)+1}`;return f})}function BJ($){let f=[];for(let W=$;W;W=W.parent)f.push(W);return f}rd.Command=TK});var ex=d((Cf,ox)=>{var{Argument:pd}=aX(),{Command:tx}=sx(),{CommanderError:nd,InvalidArgumentError:ax}=FJ(),{Help:sd}=_K(),{Option:td}=NK();Cf=ox.exports=new tx;Cf.program=Cf;Cf.Argument=pd;Cf.Command=tx;Cf.CommanderError=nd;Cf.Help=sd;Cf.InvalidArgumentError=ax;Cf.InvalidOptionArgumentError=ax;Cf.Option=td});var Ef=d((TW0,PK)=>{var $z=process||{},W_=$z.argv||[],eX=$z.env||{},ad=!(!!eX.NO_COLOR||W_.includes("--no-color"))&&(!!eX.FORCE_COLOR||W_.includes("--color")||$z.platform==="win32"||($z.stdout||{}).isTTY&&eX.TERM!=="dumb"||!!eX.CI),od=($,f,W=$)=>(J)=>{let Z=""+J,X=Z.indexOf(f,$.length);return~X?$+ed(Z,f,W,X)+f:$+Z+f},ed=($,f,W,J)=>{let Z="",X=0;do Z+=$.substring(X,J)+W,X=J+f.length,J=$.indexOf(f,X);while(~J);return Z+$.substring(X)},J_=($=ad)=>{let f=$?od:()=>String;return{isColorSupported:$,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}};PK.exports=J_();PK.exports.createColors=J_});var Z_=d((CK,EK)=>{(function($,f){typeof CK=="object"&&typeof EK!="undefined"?EK.exports=f():typeof define=="function"&&define.amd?define(f):($=typeof globalThis!="undefined"?globalThis:$||self).dayjs=f()})(CK,function(){var $=1000,f=60000,W=3600000,J="millisecond",Z="second",X="minute",z="hour",w="day",G="week",Y="month",L="quarter",U="year",M="date",q="Invalid Date",V=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,Q=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,O={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(n){var D=["th","st","nd","rd"],P=n%100;return"["+n+(D[(P-20)%10]||D[P]||D[0])+"]"}},x=function(n,D,P){var c=String(n);return!c||c.length>=D?n:""+Array(D+1-c.length).join(P)+n},y={s:x,z:function(n){var D=-n.utcOffset(),P=Math.abs(D),c=Math.floor(P/60),h=P%60;return(D<=0?"+":"-")+x(c,2,"0")+":"+x(h,2,"0")},m:function n(D,P){if(D.date()<P.date())return-n(P,D);var c=12*(P.year()-D.year())+(P.month()-D.month()),h=D.clone().add(c,Y),e=P-h<0,$0=D.clone().add(c+(e?-1:1),Y);return+(-(c+(P-h)/(e?h-$0:$0-h))||0)},a:function(n){return n<0?Math.ceil(n)||0:Math.floor(n)},p:function(n){return{M:Y,y:U,w:G,d:w,D:M,h:z,m:X,s:Z,ms:J,Q:L}[n]||String(n||"").toLowerCase().replace(/s$/,"")},u:function(n){return n===void 0}},F="en",B={};B[F]=O;var i="$isDayjsObject",w0=function(n){return n instanceof y1||!(!n||!n[i])},L0=function n(D,P,c){var h;if(!D)return F;if(typeof D=="string"){var e=D.toLowerCase();B[e]&&(h=e),P&&(B[e]=P,h=e);var $0=D.split("-");if(!h&&$0.length>1)return n($0[0])}else{var x0=D.name;B[x0]=D,h=x0}return!c&&h&&(F=h),h||!c&&F},K0=function(n,D){if(w0(n))return n.clone();var P=typeof D=="object"?D:{};return P.date=n,P.args=arguments,new y1(P)},j=y;j.l=L0,j.i=w0,j.w=function(n,D){return K0(n,{locale:D.$L,utc:D.$u,x:D.$x,$offset:D.$offset})};var y1=function(){function n(P){this.$L=L0(P.locale,null,!0),this.parse(P),this.$x=this.$x||P.x||{},this[i]=!0}var D=n.prototype;return D.parse=function(P){this.$d=function(c){var{date:h,utc:e}=c;if(h===null)return new Date(NaN);if(j.u(h))return new Date;if(h instanceof Date)return new Date(h);if(typeof h=="string"&&!/Z$/i.test(h)){var $0=h.match(V);if($0){var x0=$0[2]-1||0,d0=($0[7]||"0").substring(0,3);return e?new Date(Date.UTC($0[1],x0,$0[3]||1,$0[4]||0,$0[5]||0,$0[6]||0,d0)):new Date($0[1],x0,$0[3]||1,$0[4]||0,$0[5]||0,$0[6]||0,d0)}}return new Date(h)}(P),this.init()},D.init=function(){var P=this.$d;this.$y=P.getFullYear(),this.$M=P.getMonth(),this.$D=P.getDate(),this.$W=P.getDay(),this.$H=P.getHours(),this.$m=P.getMinutes(),this.$s=P.getSeconds(),this.$ms=P.getMilliseconds()},D.$utils=function(){return j},D.isValid=function(){return this.$d.toString()!==q},D.isSame=function(P,c){var h=K0(P);return this.startOf(c)<=h&&h<=this.endOf(c)},D.isAfter=function(P,c){return K0(P)<this.startOf(c)},D.isBefore=function(P,c){return this.endOf(c)<K0(P)},D.$g=function(P,c,h){return j.u(P)?this[c]:this.set(h,P)},D.unix=function(){return Math.floor(this.valueOf()/1000)},D.valueOf=function(){return this.$d.getTime()},D.startOf=function(P,c){var h=this,e=!!j.u(c)||c,$0=j.p(P),x0=function(Pf,B1){var H2=j.w(h.$u?Date.UTC(h.$y,B1,Pf):new Date(h.$y,B1,Pf),h);return e?H2:H2.endOf(w)},d0=function(Pf,B1){return j.w(h.toDate()[Pf].apply(h.toDate("s"),(e?[0,0,0,0]:[23,59,59,999]).slice(B1)),h)},p0=this.$W,M1=this.$M,G$=this.$D,$9="set"+(this.$u?"UTC":"");switch($0){case U:return e?x0(1,0):x0(31,11);case Y:return e?x0(1,M1):x0(0,M1+1);case G:var j1=this.$locale().weekStart||0,K2=(p0<j1?p0+7:p0)-j1;return x0(e?G$-K2:G$+(6-K2),M1);case w:case M:return d0($9+"Hours",0);case z:return d0($9+"Minutes",1);case X:return d0($9+"Seconds",2);case Z:return d0($9+"Milliseconds",3);default:return this.clone()}},D.endOf=function(P){return this.startOf(P,!1)},D.$set=function(P,c){var h,e=j.p(P),$0="set"+(this.$u?"UTC":""),x0=(h={},h[w]=$0+"Date",h[M]=$0+"Date",h[Y]=$0+"Month",h[U]=$0+"FullYear",h[z]=$0+"Hours",h[X]=$0+"Minutes",h[Z]=$0+"Seconds",h[J]=$0+"Milliseconds",h)[e],d0=e===w?this.$D+(c-this.$W):c;if(e===Y||e===U){var p0=this.clone().set(M,1);p0.$d[x0](d0),p0.init(),this.$d=p0.set(M,Math.min(this.$D,p0.daysInMonth())).$d}else x0&&this.$d[x0](d0);return this.init(),this},D.set=function(P,c){return this.clone().$set(P,c)},D.get=function(P){return this[j.p(P)]()},D.add=function(P,c){var h,e=this;P=Number(P);var $0=j.p(c),x0=function(M1){var G$=K0(e);return j.w(G$.date(G$.date()+Math.round(M1*P)),e)};if($0===Y)return this.set(Y,this.$M+P);if($0===U)return this.set(U,this.$y+P);if($0===w)return x0(1);if($0===G)return x0(7);var d0=(h={},h[X]=f,h[z]=W,h[Z]=$,h)[$0]||1,p0=this.$d.getTime()+P*d0;return j.w(p0,this)},D.subtract=function(P,c){return this.add(-1*P,c)},D.format=function(P){var c=this,h=this.$locale();if(!this.isValid())return h.invalidDate||q;var e=P||"YYYY-MM-DDTHH:mm:ssZ",$0=j.z(this),x0=this.$H,d0=this.$m,p0=this.$M,M1=h.weekdays,G$=h.months,$9=h.meridiem,j1=function(B1,H2,k$,Zf){return B1&&(B1[H2]||B1(c,e))||k$[H2].slice(0,Zf)},K2=function(B1){return j.s(x0%12||12,B1,"0")},Pf=$9||function(B1,H2,k$){var Zf=B1<12?"AM":"PM";return k$?Zf.toLowerCase():Zf};return e.replace(Q,function(B1,H2){return H2||function(k$){switch(k$){case"YY":return String(c.$y).slice(-2);case"YYYY":return j.s(c.$y,4,"0");case"M":return p0+1;case"MM":return j.s(p0+1,2,"0");case"MMM":return j1(h.monthsShort,p0,G$,3);case"MMMM":return j1(G$,p0);case"D":return c.$D;case"DD":return j.s(c.$D,2,"0");case"d":return String(c.$W);case"dd":return j1(h.weekdaysMin,c.$W,M1,2);case"ddd":return j1(h.weekdaysShort,c.$W,M1,3);case"dddd":return M1[c.$W];case"H":return String(x0);case"HH":return j.s(x0,2,"0");case"h":return K2(1);case"hh":return K2(2);case"a":return Pf(x0,d0,!0);case"A":return Pf(x0,d0,!1);case"m":return String(d0);case"mm":return j.s(d0,2,"0");case"s":return String(c.$s);case"ss":return j.s(c.$s,2,"0");case"SSS":return j.s(c.$ms,3,"0");case"Z":return $0}return null}(B1)||$0.replace(":","")})},D.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},D.diff=function(P,c,h){var e,$0=this,x0=j.p(c),d0=K0(P),p0=(d0.utcOffset()-this.utcOffset())*f,M1=this-d0,G$=function(){return j.m($0,d0)};switch(x0){case U:e=G$()/12;break;case Y:e=G$();break;case L:e=G$()/3;break;case G:e=(M1-p0)/604800000;break;case w:e=(M1-p0)/86400000;break;case z:e=M1/W;break;case X:e=M1/f;break;case Z:e=M1/$;break;default:e=M1}return h?e:j.a(e)},D.daysInMonth=function(){return this.endOf(Y).$D},D.$locale=function(){return B[this.$L]},D.locale=function(P,c){if(!P)return this.$L;var h=this.clone(),e=L0(P,c,!0);return e&&(h.$L=e),h},D.clone=function(){return j.w(this.$d,this)},D.toDate=function(){return new Date(this.valueOf())},D.toJSON=function(){return this.isValid()?this.toISOString():null},D.toISOString=function(){return this.$d.toISOString()},D.toString=function(){return this.$d.toUTCString()},n}(),L2=y1.prototype;return K0.prototype=L2,[["$ms",J],["$s",Z],["$m",X],["$H",z],["$W",w],["$M",Y],["$y",U],["$D",M]].forEach(function(n){L2[n[1]]=function(D){return this.$g(D,n[0],n[1])}}),K0.extend=function(n,D){return n.$i||(n(D,y1,K0),n.$i=!0),K0},K0.locale=L0,K0.isDayjs=w0,K0.unix=function(n){return K0(1000*n)},K0.en=B[F],K0.Ls=B,K0.p={},K0})});var X_=d((hK,DK)=>{(function($,f){typeof hK=="object"&&typeof DK!="undefined"?DK.exports=f():typeof define=="function"&&define.amd?define(f):($=typeof globalThis!="undefined"?globalThis:$||self).dayjs_plugin_weekOfYear=f()})(hK,function(){var $="week",f="year";return function(W,J,Z){var X=J.prototype;X.week=function(z){if(z===void 0&&(z=null),z!==null)return this.add(7*(z-this.week()),"day");var w=this.$locale().yearStart||1;if(this.month()===11&&this.date()>25){var G=Z(this).startOf(f).add(1,f).date(w),Y=Z(this).endOf($);if(G.isBefore(Y))return 1}var L=Z(this).startOf(f).date(w).startOf($).subtract(1,"millisecond"),U=this.diff(L,$,!0);return U<0?Z(this).startOf("week").week():Math.ceil(U)},X.weeks=function(z){return z===void 0&&(z=null),this.week(z)}}})});function fz($){return s5.default($).format("YYYY-MM-DD HH:mm:ss")}function w_($){return($?new Date($):new Date).toISOString().replace("T"," ").split(".")[0]}function G_(){return new Date().getTimezoneOffset()}function Y_(){return Intl.DateTimeFormat().resolvedOptions().timeZone}var s5,z_;var vK=K(()=>{s5=q1(Z_(),1),z_=q1(X_(),1);s5.default.extend(z_.default)});function Z1(){try{return mK(0)}catch($){return!1}}function L_(){try{return"0.16.0"}catch($){return"0.0.0"}}var mK=($,f)=>{return typeof $==="string"?[1,"1","true"].includes($):Boolean($||f)},$i,W9=($,f,W)=>{try{let J=W?.source??process.env,Z=$i[$],X=J[Z.key],z=Z.validate(X);if(typeof z!=="undefined")return W?.onValid?.(z),z;W?.onFallback?.(X)}catch(J){W?.onFallback?.(void 0)}return f};var V$=K(()=>{$i={cli_log_level:{key:"BKND_CLI_LOG_LEVEL",validate:($)=>{if(typeof $==="string"&&["log","info","warn","error","debug"].includes($.toLowerCase()))return $.toLowerCase();return}},cli_create_ref:{key:"BKND_CLI_CREATE_REF",validate:($)=>{return typeof $==="string"?$:void 0}},cli_telemetry:{key:"BKND_CLI_TELEMETRY",validate:($)=>{if(typeof $==="undefined")return;return mK($,!0)}},modules_debug:{key:"BKND_MODULES_DEBUG",validate:mK}}});function fi(){try{let $=process||{},f=$.argv||[],W=$.env||{};return!(!!W.NO_COLOR||f.includes("--no-color"))&&(!!W.FORCE_COLOR||f.includes("--color")||$.platform==="win32"||($.stdout||{}).isTTY&&W.TERM!=="dumb"||!!W.CI)}catch($){return!1}}function Wi($,f){let W=fi(),J=Jz[$],Z=J.color(`[${J.prefix}]`),X=f.map((z)=>("args_color"in J)&&W&&typeof z==="string"?J.args_color(z):z);return J.original(Z,y$.default.gray(fz()),...X)}function U_($){for(let[f]of Object.entries(Jz))$[f]=A[f]}var y$,Jz,H_,Wz,K_,A;var kK=K(()=>{vK();y$=q1(Ef(),1);V$();Jz={critical:{prefix:"CRT",color:y$.default.red,args_color:y$.default.red,original:console.error},error:{prefix:"ERR",color:y$.default.red,args_color:y$.default.red,original:console.error},warn:{prefix:"WRN",color:y$.default.yellow,args_color:y$.default.yellow,original:console.warn},info:{prefix:"INF",color:y$.default.cyan,original:console.info},log:{prefix:"LOG",color:y$.default.dim,args_color:y$.default.dim,original:console.log},debug:{prefix:"DBG",color:y$.default.yellow,args_color:y$.default.dim,original:console.debug}};H_=W9("cli_log_level","log"),Wz=globalThis.__consoleConfig??={level:H_},K_=Object.keys(Jz),A=new Proxy(Wz,{get:($,f)=>{switch(f){case"original":return console;case"setLevel":return(Z)=>{Wz.level=Z};case"resetLevel":return()=>{Wz.level=H_}}let W=K_.indexOf(Wz.level),J=K_.indexOf(f);if(f in Jz&&J<=W)return(...Z)=>Wi(f,Z);return()=>null}})});function jK($){if(!$||$.length===0)return $;return $.charAt(0).toUpperCase()+$.slice(1)}function Xz($,f=!1){let Z="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+(f?"!@#$%^&*()_+{}:\"<>?|[];',./`~":""),X="";for(let z=0;z<$;z++)X+=Z[Math.floor(Math.random()*Z.length)];return X}function G4($){if(!$||$.length===0)return $;return $.split("_").map((f)=>f.charAt(0).toUpperCase()+f.slice(1).toLowerCase()).join(" ")}function Zz($){return $.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function Ji($){if(/^[a-z]+(_[a-z]+)*$/.test($))return"snake_case";else if(/^[A-Z][a-zA-Z]*$/.test($))return"PascalCase";else if(/^[a-z][a-zA-Z]*$/.test($))return"camelCase";else if(/^[a-z]+(-[a-z]+)*$/.test($))return"kebab-case";else if(/^[A-Z]+(_[A-Z]+)*$/.test($))return"SCREAMING_SNAKE_CASE";else return"unknown"}function Zi($){switch(Ji($)){case"snake_case":return G4($);case"PascalCase":return yK(Zz($));case"camelCase":return jK(yK(Zz($)));case"kebab-case":return yK($);case"SCREAMING_SNAKE_CASE":return G4($.toLowerCase());case"unknown":return jK($)}}function R_($){return Zi($)}function yK($){return $.split("-").map(jK).join(" ")}function M_($,f){if(f instanceof RegExp)return f.test($);else if(typeof f==="string"&&f.startsWith("/"))return new RegExp(f).test($);else if(typeof f==="string")return $.startsWith(f);return!1}function q_($,f=50,W="..."){if($.length<=f)return $;return $.substring(0,f)+W}function gK($){return Object.prototype.toString.call($)==="[object Object]"}function U6($){return $!==null&&typeof $==="object"}function s1($,f){let W=new Set(f),J={};for(let[Z,X]of Object.entries($))if(!W.has(Z))J[Z]=X;return J}function zz($,f=[]){if($===null||typeof $!=="object")return $;if(Array.isArray($))return $.map((W)=>zz(W,f));return Object.keys($).reduce((W,J)=>{let Z=f.includes(J)?J:Zz(J);return W[Z]=zz($[J],f),W},{})}function bK($,f){let W={};for(let J in $)if(!f.some((X)=>J.includes(X)))if(typeof $[J]==="object"&&$[J]!==null&&!Array.isArray($[J]))W[J]=bK($[J],f);else W[J]=$[J];return W}function M0($,f){let W={};for(let[J,Z]of Object.entries($)){let X=f(Z,J);if(typeof X!=="undefined")W[J]=X}return W}function uK($,f){Object.entries($).forEach(([W,J])=>{f(J,W)},{})}function cK($,f=""){let W=[];for(let J in $){let Z=f?`${f}.${J}`:J;if(W.push(Z),typeof $[J]==="object"&&$[J]!==null)W=W.concat(cK($[J],Z))}return W}function wz($){if(!$)return $;return Object.entries($).reduce((f,[W,J])=>{if(J&&Array.isArray(J)&&J.some((Z)=>typeof Z==="object")){let Z=J.map(wz);if(Z.length>0)f[W]=Z}else if(J&&typeof J==="object"&&!Array.isArray(J)){let Z=wz(J);if(Object.keys(Z).length>0)f[W]=Z}else if(J!==""&&J!==null&&J!==void 0)f[W]=J;return f},{})}function dK($,f,W){for(let[J,Z]of Object.entries(f)){let X=W($[J],Z,J,$,f);if(X!==void 0){$[J]=X;continue}if(Z===void 0)continue;if(!gK(Z)&&!Array.isArray(Z))$[J]=Z;else if(Array.isArray(Z)&&!Array.isArray($[J]))$[J]=Z;else if(!U6($[J]))$[J]=Z;else dK($[J],Z,W)}return $}function Gz($,f=0,W=0){let J=f?`
`:"",Z=(G)=>f?" ".repeat(f*G):"",X=Z(W+1),z=Z(W);if($===null)return"null";if($===void 0)return"undefined";let w=typeof $;if(w==="string")return JSON.stringify($);if(w==="number"||w==="boolean")return String($);if(Array.isArray($)){let G=$.map((Y)=>Gz(Y,f,W+1)).join(", "+(f?J+X:""));return"["+(f&&$.length?J+X:"")+G+(f&&$.length?J+z:"")+"]"}if(w==="object"){let G=Object.entries($).map(([L,U])=>{return(/^[A-Za-z_$][\w$]*$/.test(L)?L:JSON.stringify(L))+": "+Gz(U,f,W+1)}),Y=G.join(", "+(f?J+X:""));return"{"+(f&&G.length?J+X:"")+Y+(f&&G.length?J+z:"")+"}"}throw new TypeError(`Unsupported data type: ${w}`)}function V_($,f){return f.reduce((W,J)=>{if(J in $)W[J]=$[J];return W},{})}function R6($){if(Object.isFrozen($))return $;let f=Reflect.ownKeys($);for(let W of f){let J=$[W];if(J&&typeof J==="object"||typeof J==="function")R6(J)}return Object.freeze($)}var Y4;var iK=K(()=>{Y4=M0});function M6($){try{let f=$.split(".").pop();if(!f)return X0.a();for(let[W,J]of Object.entries(rK))if(J.includes(f))return`${W}/${f}`;return lK.get(f)}catch(f){return X0.a()}}function Yz($,f=[]){let W=$.toLowerCase();if(f.includes(W))return!1;if(Object.entries(rK).flatMap(([J,Z])=>Z.map((X)=>`${J}/${X}`)).includes(W))return!0;for(let[J,Z]of lK.entries())if(Z===W&&!f.includes(J))return!0;return!1}function Lz($){let f=$.toLowerCase();for(let[W,J]of Object.entries(rK))for(let Z of J)if(f===`${W}/${Z}`)return Z;for(let[W,J]of lK.entries())if(J===f)return W;return""}var rK,X0,lK;var TJ=K(()=>{rK={video:["mp4","webm"],audio:["ogg"],image:["jpeg","png","gif","webp","bmp","tiff","avif","heic","heif"],text:["html","css","mdx","yaml","vcard","csv","vtt"],application:["zip","xml","toml","json","json5"],font:["woff","woff2","ttf","otf"]},X0={vnd:"vnd.openxmlformats-officedocument",z:"application/x-7z-compressed",t:($="plain")=>`text/${$}`,a:($="octet-stream")=>`application/${$}`,i:($)=>`image/${$}`,v:($)=>`video/${$}`},lK=new Map([["7z",X0.z],["7zip",X0.z],["ai",X0.a("pdf")],["apk",X0.a("vnd.android.package-archive")],["doc",X0.a("msword")],["docx",`${X0.vnd}.wordprocessingml.document`],["eps",X0.a("postscript")],["epub",X0.a("epub+zip")],["ini",X0.t()],["ico",X0.i("vnd.microsoft.icon")],["jar",X0.a("java-archive")],["jsonld",X0.a("ld+json")],["jpg",X0.i("jpeg")],["js",X0.t("javascript")],["log",X0.t()],["m3u",X0.t()],["m3u8",X0.a("vnd.apple.mpegurl")],["manifest",X0.t("cache-manifest")],["md",X0.t("markdown")],["mkv",X0.v("x-matroska")],["mp3",X0.a("mpeg")],["mobi",X0.a("x-mobipocket-ebook")],["ppt",X0.a("powerpoint")],["pptx",`${X0.vnd}.presentationml.presentation`],["qt",X0.v("quicktime")],["svg",X0.i("svg+xml")],["tif",X0.i("tiff")],["tsv",X0.t("tab-separated-values")],["tgz",X0.a("x-tar")],["txt",X0.t()],["text",X0.t()],["vcd",X0.a("x-cdlink")],["vcs",X0.t("x-vcalendar")],["wav",X0.a("x-wav")],["webmanifest",X0.a("manifest+json")],["xls",X0.a("vnd.ms-excel")],["xlsx",`${X0.vnd}.spreadsheetml.sheet`],["yml",X0.t("yaml")]])});var Xi,Kz=()=>{let $=globalThis;if(typeof navigator!=="undefined"&&typeof navigator.userAgent==="string"){for(let[W,J]of Object.entries(Xi))if(zi(J))return W}if(typeof $?.EdgeRuntime==="string")return"edge-light";if($?.fastly!==void 0)return"fastly";if($?.process?.release?.name==="node")return"node";return"other"},zi=($)=>{return navigator.userAgent.startsWith($)};var pK=K(()=>{Xi={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"}});function nK(){let $=globalThis;if($?.process?.env?.NEXT_RUNTIME==="nodejs")return"nextjs";if($?.process?.env?.NEXT_RUNTIME==="edge")return"nextjs-edge";if(typeof window!=="undefined"&&window.__NEXT_DATA__)return"nextjs-client";return Kz()}function I_($){if(nK().startsWith("nextjs"))Q_.redirects_non_fq=!1;return Q_[$]}function Hz(){try{return typeof Bun!=="undefined"}catch($){return!1}}function sK($,f){if(!$)throw new Error(f)}var Q_;var tK=K(()=>{pK();Q_={redirects_non_fq:!0}});function wi($){let f="";if(typeof $==="string")f=$;else if($ instanceof Headers)f=$.get("Content-Disposition")||"";else if($ instanceof Request)f=$.headers.get("Content-Disposition")||"";let W=f.match(/filename\*?=(?:UTF-8'')?("?)([^";]+)\1/);return W?W[2]:void 0}function Gi($){return typeof $==="object"&&$!==null&&typeof $.getReader==="function"}function Uz($){return typeof $==="object"&&$!==null&&typeof $.arrayBuffer==="function"&&typeof $.type==="string"}function j$($){return Uz($)&&typeof $.name==="string"&&typeof $.lastModified==="number"}function Yi($){return typeof $==="object"&&$!==null&&Object.prototype.toString.call($)==="[object ArrayBuffer]"}function Li($){return typeof $==="object"&&$!==null&&ArrayBuffer.isView($)}async function Hi($){if(!$)return;let f;if(Gi($)){let J=$.getReader(),{value:Z}=await J.read();if(!Z)return;f=new Uint8Array(Z)}else if(Uz($)||j$($))f=new Uint8Array(await $.slice(0,12).arrayBuffer());else if(Yi($))f=new Uint8Array($);else if(Li($))f=new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(typeof $==="string")f=new TextEncoder().encode($);else return;let W=Array.from(f.slice(0,12)).map((J)=>J.toString(16).padStart(2,"0").toUpperCase()).join("");for(let[J,Z]of Object.entries(Ki))if(new RegExp("^"+J.replace(/\?\?/g,"..")).test(W))return Z;return}async function Rz($){let f=$.req.header("Content-Type")??"application/octet-stream";if(f?.startsWith("multipart/form-data")||f?.startsWith("application/x-www-form-urlencoded"))try{let W=await $.req.formData();if([...W.values()].length>0){let J=[...W.values()][0];return await O_(J)}}catch(W){A.warn("Error parsing form data",W)}else try{let W=await $.req.blob();if(j$(W))return W;else if(Uz(W))return await O_(W,{name:wi($.req.raw),type:f})}catch(W){A.warn("Error parsing blob",W)}throw new Error("No file found in request")}async function A_($,f){let W=j$($),J=W?$.type:f;sK(J&&typeof J==="string"&&J.startsWith("image/"),"type must be image/*");let Z=W?await $.arrayBuffer():$;sK(Z.byteLength>=128,"Buffer must be at least 128 bytes");let X=new DataView(Z);if(J==="image/jpeg"){let z=2;while(z<X.byteLength){let w=X.getUint16(z);if(z+=2,w===65472||w===65474)return{width:X.getUint16(z+5),height:X.getUint16(z+3)};z+=X.getUint16(z)}}else if(J==="image/png")return{width:X.getUint32(16),height:X.getUint32(20)};else if(J==="image/gif")return{width:X.getUint16(6),height:X.getUint16(8)};else if(J==="image/tiff"){let z=X.getUint16(0)===18761,w=X.getUint32(4,z),G=X.getUint32(w+18,z),Y=X.getUint32(w+10,z);return{width:G,height:Y}}throw new Error("Unsupported image format")}async function O_($,f={}){if(j$($))return $;if(!Uz($))throw new Error("Not a Blob");let W=Yz(f.type,["application/octet-stream"])?f.type:await Hi($),J=W?Lz(W):"",Z=f.name||[Xz(16),J].filter(Boolean).join(".");return new File([$],Z,{type:W||M6(Z),lastModified:Date.now()})}var Ki;var x_=K(()=>{TJ();tK();kK();Ki={"89504E47":"image/png",FFD8FF:"image/jpeg","47494638":"image/gif","49492A00":"image/tiff","4D4D002A":"image/tiff","52494646????57454250":"image/webp","504B0304":"application/zip","25504446":"application/pdf","00000020667479706D70":"video/mp4","000001BA":"video/mpeg","000001B3":"video/mpeg","1A45DFA3":"video/webm","4F676753":"audio/ogg","494433":"audio/mpeg",FFF1:"audio/aac",FFF9:"audio/aac","52494646????41564920":"audio/wav","52494646????57415645":"audio/wave","52494646????415550":"audio/aiff"}});function Ui($){if(!$)return{};return{...Object.fromEntries($.entries())}}function __($,f){let W=Ui($),J={};for(let Z of f)if(W[Z])J[Z]=W[Z];return J}function N_($,f){let W=new Headers;for(let J of f)if($.has(J))W.set(J,$.get(J));return W}function S_($,f){let W="";function J(Z){return f?.encode?encodeURIComponent(Z):Z}for(let Z in $){let X=$[Z];if(X!==void 0)if(Array.isArray(X))for(let z=0;z<X.length;z++){if(W.length>0)W+="&";W+=`${J(Z)}=${J(X[z])}`}else{if(typeof X==="object")X=JSON.stringify(X);if(W.length>0)W+="&";W+=`${J(Z)}=${J(X)}`}}return(f?.prefix||"")+W}var F_=()=>{};function Mz($,f){let W=[],J=f.exec($);while(J){let Z=[];Z.startIndex=f.lastIndex-J[0].length;let X=J.length;for(let z=0;z<X;z++)Z.push(J[z]);W.push(Z),J=f.exec($)}return W}function B_($){return typeof $!=="undefined"}var Ri=":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",Mi,qi,PJ=function($){let f=qi.exec($);return!(f===null||typeof f==="undefined")};var qz=K(()=>{Mi="[: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]["+Ri+"]*",qi=new RegExp("^"+Mi+"$")});function aK($,f){f=Object.assign({},Vi,f);let W=[],J=!1,Z=!1;if($[0]==="\uFEFF")$=$.substr(1);for(let X=0;X<$.length;X++)if($[X]==="<"&&$[X+1]==="?"){if(X+=2,X=P_($,X),X.err)return X}else if($[X]==="<"){let z=X;if(X++,$[X]==="!"){X=C_($,X);continue}else{let w=!1;if($[X]==="/")w=!0,X++;let G="";for(;X<$.length&&$[X]!==">"&&$[X]!==" "&&$[X]!=="\t"&&$[X]!==`
`&&$[X]!=="\r";X++)G+=$[X];if(G=G.trim(),G[G.length-1]==="/")G=G.substring(0,G.length-1),X--;if(!Si(G)){let U;if(G.trim().length===0)U="Invalid space after '<'.";else U="Tag '"+G+"' is an invalid name.";return z1("InvalidTag",U,Y$($,X))}let Y=Oi($,X);if(Y===!1)return z1("InvalidAttr","Attributes for '"+G+"' have open quote.",Y$($,X));let L=Y.value;if(X=Y.index,L[L.length-1]==="/"){let U=X-L.length;L=L.substring(0,L.length-1);let M=E_(L,f);if(M===!0)J=!0;else return z1(M.err.code,M.err.msg,Y$($,U+M.err.line))}else if(w)if(!Y.tagClosed)return z1("InvalidTag","Closing tag '"+G+"' doesn't have proper closing.",Y$($,X));else if(L.trim().length>0)return z1("InvalidTag","Closing tag '"+G+"' can't have attributes or invalid starting.",Y$($,z));else if(W.length===0)return z1("InvalidTag","Closing tag '"+G+"' has not been opened.",Y$($,z));else{let U=W.pop();if(G!==U.tagName){let M=Y$($,U.tagStartPos);return z1("InvalidTag","Expected closing tag '"+U.tagName+"' (opened in line "+M.line+", col "+M.col+") instead of closing tag '"+G+"'.",Y$($,z))}if(W.length==0)Z=!0}else{let U=E_(L,f);if(U!==!0)return z1(U.err.code,U.err.msg,Y$($,X-L.length+U.err.line));if(Z===!0)return z1("InvalidXml","Multiple possible root nodes found.",Y$($,X));else if(f.unpairedTags.indexOf(G)!==-1);else W.push({tagName:G,tagStartPos:z});J=!0}for(X++;X<$.length;X++)if($[X]==="<")if($[X+1]==="!"){X++,X=C_($,X);continue}else if($[X+1]==="?"){if(X=P_($,++X),X.err)return X}else break;else if($[X]==="&"){let U=_i($,X);if(U==-1)return z1("InvalidChar","char '&' is not expected.",Y$($,X));X=U}else if(Z===!0&&!T_($[X]))return z1("InvalidXml","Extra text at the end",Y$($,X));if($[X]==="<")X--}}else{if(T_($[X]))continue;return z1("InvalidChar","char '"+$[X]+"' is not expected.",Y$($,X))}if(!J)return z1("InvalidXml","Start tag expected.",1);else if(W.length==1)return z1("InvalidTag","Unclosed tag '"+W[0].tagName+"'.",Y$($,W[0].tagStartPos));else if(W.length>0)return z1("InvalidXml","Invalid '"+JSON.stringify(W.map((X)=>X.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function T_($){return $===" "||$==="\t"||$===`
`||$==="\r"}function P_($,f){let W=f;for(;f<$.length;f++)if($[f]=="?"||$[f]==" "){let J=$.substr(W,f-W);if(f>5&&J==="xml")return z1("InvalidXml","XML declaration allowed only at the start of the document.",Y$($,f));else if($[f]=="?"&&$[f+1]==">"){f++;break}else continue}return f}function C_($,f){if($.length>f+5&&$[f+1]==="-"&&$[f+2]==="-"){for(f+=3;f<$.length;f++)if($[f]==="-"&&$[f+1]==="-"&&$[f+2]===">"){f+=2;break}}else if($.length>f+8&&$[f+1]==="D"&&$[f+2]==="O"&&$[f+3]==="C"&&$[f+4]==="T"&&$[f+5]==="Y"&&$[f+6]==="P"&&$[f+7]==="E"){let W=1;for(f+=8;f<$.length;f++)if($[f]==="<")W++;else if($[f]===">"){if(W--,W===0)break}}else if($.length>f+9&&$[f+1]==="["&&$[f+2]==="C"&&$[f+3]==="D"&&$[f+4]==="A"&&$[f+5]==="T"&&$[f+6]==="A"&&$[f+7]==="["){for(f+=8;f<$.length;f++)if($[f]==="]"&&$[f+1]==="]"&&$[f+2]===">"){f+=2;break}}return f}function Oi($,f){let W="",J="",Z=!1;for(;f<$.length;f++){if($[f]===Qi||$[f]===Ii)if(J==="")J=$[f];else if(J!==$[f]);else J="";else if($[f]===">"){if(J===""){Z=!0;break}}W+=$[f]}if(J!=="")return!1;return{value:W,index:f,tagClosed:Z}}function E_($,f){let W=Mz($,Ai),J={};for(let Z=0;Z<W.length;Z++){if(W[Z][1].length===0)return z1("InvalidAttr","Attribute '"+W[Z][2]+"' has no space in starting.",CJ(W[Z]));else if(W[Z][3]!==void 0&&W[Z][4]===void 0)return z1("InvalidAttr","Attribute '"+W[Z][2]+"' is without value.",CJ(W[Z]));else if(W[Z][3]===void 0&&!f.allowBooleanAttributes)return z1("InvalidAttr","boolean attribute '"+W[Z][2]+"' is not allowed.",CJ(W[Z]));let X=W[Z][2];if(!Ni(X))return z1("InvalidAttr","Attribute '"+X+"' is an invalid name.",CJ(W[Z]));if(!J.hasOwnProperty(X))J[X]=1;else return z1("InvalidAttr","Attribute '"+X+"' is repeated.",CJ(W[Z]))}return!0}function xi($,f){let W=/\d/;if($[f]==="x")f++,W=/[\da-fA-F]/;for(;f<$.length;f++){if($[f]===";")return f;if(!$[f].match(W))break}return-1}function _i($,f){if(f++,$[f]===";")return-1;if($[f]==="#")return f++,xi($,f);let W=0;for(;f<$.length;f++,W++){if($[f].match(/\w/)&&W<20)continue;if($[f]===";")break;return-1}return f}function z1($,f,W){return{err:{code:$,msg:f,line:W.line||W,col:W.col}}}function Ni($){return PJ($)}function Si($){return PJ($)}function Y$($,f){let W=$.substring(0,f).split(/\r?\n/);return{line:W.length,col:W[W.length-1].length+1}}function CJ($){return $.startIndex+$[1].length}var Vi,Qi='"',Ii="'",Ai;var oK=K(()=>{qz();Vi={allowBooleanAttributes:!1,unpairedTags:[]};Ai=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g")});var Fi,h_=function($){return Object.assign({},Fi,$)};var D_=K(()=>{Fi={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($,f){return f},attributeValueProcessor:function($,f){return f},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function($,f,W){return $}}});class L4{constructor($){this.tagname=$,this.child=[],this[":@"]={}}add($,f){if($==="__proto__")$="#__proto__";this.child.push({[$]:f})}addChild($){if($.tagname==="__proto__")$.tagname="#__proto__";if($[":@"]&&Object.keys($[":@"]).length>0)this.child.push({[$.tagname]:$.child,[":@"]:$[":@"]});else this.child.push({[$.tagname]:$.child})}}function eK($,f){let W={};if($[f+3]==="O"&&$[f+4]==="C"&&$[f+5]==="T"&&$[f+6]==="Y"&&$[f+7]==="P"&&$[f+8]==="E"){f=f+9;let J=1,Z=!1,X=!1,z="";for(;f<$.length;f++)if($[f]==="<"&&!X){if(Z&&Pi($,f)){f+=7;let w,G;if([w,G,f]=Bi($,f+1),G.indexOf("&")===-1)W[Di(w)]={regx:RegExp(`&${w};`,"g"),val:G}}else if(Z&&Ci($,f))f+=8;else if(Z&&Ei($,f))f+=8;else if(Z&&hi($,f))f+=9;else if(Ti)X=!0;else throw new Error("Invalid DOCTYPE");J++,z=""}else if($[f]===">"){if(X){if($[f-1]==="-"&&$[f-2]==="-")X=!1,J--}else J--;if(J===0)break}else if($[f]==="[")Z=!0;else z+=$[f];if(J!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:W,i:f}}function Bi($,f){let W="";for(;f<$.length&&($[f]!=="'"&&$[f]!=='"');f++)W+=$[f];if(W=W.trim(),W.indexOf(" ")!==-1)throw new Error("External entites are not supported");let J=$[f++],Z="";for(;f<$.length&&$[f]!==J;f++)Z+=$[f];return[W,Z,f]}function Ti($,f){if($[f+1]==="!"&&$[f+2]==="-"&&$[f+3]==="-")return!0;return!1}function Pi($,f){if($[f+1]==="!"&&$[f+2]==="E"&&$[f+3]==="N"&&$[f+4]==="T"&&$[f+5]==="I"&&$[f+6]==="T"&&$[f+7]==="Y")return!0;return!1}function Ci($,f){if($[f+1]==="!"&&$[f+2]==="E"&&$[f+3]==="L"&&$[f+4]==="E"&&$[f+5]==="M"&&$[f+6]==="E"&&$[f+7]==="N"&&$[f+8]==="T")return!0;return!1}function Ei($,f){if($[f+1]==="!"&&$[f+2]==="A"&&$[f+3]==="T"&&$[f+4]==="T"&&$[f+5]==="L"&&$[f+6]==="I"&&$[f+7]==="S"&&$[f+8]==="T")return!0;return!1}function hi($,f){if($[f+1]==="!"&&$[f+2]==="N"&&$[f+3]==="O"&&$[f+4]==="T"&&$[f+5]==="A"&&$[f+6]==="T"&&$[f+7]==="I"&&$[f+8]==="O"&&$[f+9]==="N")return!0;return!1}function Di($){if(PJ($))return $;else throw new Error(`Invalid entity name ${$}`)}var v_=K(()=>{qz()});function $H($,f={}){if(f=Object.assign({},ki,f),!$||typeof $!=="string")return $;let W=$.trim();if(f.skipLike!==void 0&&f.skipLike.test(W))return $;else if($==="0")return 0;else if(f.hex&&vi.test(W))return ji(W,16);else if(W.search(/[eE]/)!==-1){let J=W.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(J){if(f.leadingZeros)W=(J[1]||"")+J[3];else if(J[2]==="0"&&J[3][0]===".");else return $;return f.eNotation?Number(W):$}else return $}else{let J=mi.exec(W);if(J){let Z=J[1],X=J[2],z=yi(J[3]);if(!f.leadingZeros&&X.length>0&&Z&&W[2]!==".")return $;else if(!f.leadingZeros&&X.length>0&&!Z&&W[1]!==".")return $;else if(f.leadingZeros&&X===$)return 0;else{let w=Number(W),G=""+w;if(G.search(/[eE]/)!==-1)if(f.eNotation)return w;else return $;else if(W.indexOf(".")!==-1)if(G==="0"&&z==="")return w;else if(G===z)return w;else if(Z&&G==="-"+z)return w;else return $;if(X)return z===G||Z+z===G?w:$;else return W===G||W===Z+G?w:$}}else return $}}function yi($){if($&&$.indexOf(".")!==-1){if($=$.replace(/0+$/,""),$===".")$="0";else if($[0]===".")$="0"+$;else if($[$.length-1]===".")$=$.substr(0,$.length-1);return $}return $}function ji($,f){if(parseInt)return parseInt($,f);else if(Number.parseInt)return Number.parseInt($,f);else if(window&&window.parseInt)return window.parseInt($,f);else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}var vi,mi,ki;var m_=K(()=>{vi=/^[-+]?0x[a-fA-F0-9]+$/,mi=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,ki={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0}});function EJ($){if(typeof $==="function")return $;if(Array.isArray($))return(f)=>{for(let W of $){if(typeof W==="string"&&f===W)return!0;if(W instanceof RegExp&&W.test(f))return!0}};return()=>!1}class Vz{constructor($){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:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(f,W)=>String.fromCharCode(Number.parseInt(W,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(f,W)=>String.fromCharCode(Number.parseInt(W,16))}},this.addExternalEntities=gi,this.parseXml=ii,this.parseTextData=bi,this.resolveNameSpace=ui,this.buildAttributesMap=di,this.isItStopNode=ni,this.replaceEntitiesValue=li,this.readStopNodeData=ti,this.saveTextToParentTag=pi,this.addChild=ri,this.ignoreAttributesFn=EJ(this.options.ignoreAttributes)}}function gi($){let f=Object.keys($);for(let W=0;W<f.length;W++){let J=f[W];this.lastEntities[J]={regex:new RegExp("&"+J+";","g"),val:$[J]}}}function bi($,f,W,J,Z,X,z){if($!==void 0){if(this.options.trimValues&&!J)$=$.trim();if($.length>0){if(!z)$=this.replaceEntitiesValue($);let w=this.options.tagValueProcessor(f,$,W,Z,X);if(w===null||w===void 0)return $;else if(typeof w!==typeof $||w!==$)return w;else if(this.options.trimValues)return WH($,this.options.parseTagValue,this.options.numberParseOptions);else if($.trim()===$)return WH($,this.options.parseTagValue,this.options.numberParseOptions);else return $}}}function ui($){if(this.options.removeNSPrefix){let f=$.split(":"),W=$.charAt(0)==="/"?"/":"";if(f[0]==="xmlns")return"";if(f.length===2)$=W+f[1]}return $}function di($,f,W){if(this.options.ignoreAttributes!==!0&&typeof $==="string"){let J=Mz($,ci),Z=J.length,X={};for(let z=0;z<Z;z++){let w=this.resolveNameSpace(J[z][1]);if(this.ignoreAttributesFn(w,f))continue;let G=J[z][4],Y=this.options.attributeNamePrefix+w;if(w.length){if(this.options.transformAttributeName)Y=this.options.transformAttributeName(Y);if(Y==="__proto__")Y="#__proto__";if(G!==void 0){if(this.options.trimValues)G=G.trim();G=this.replaceEntitiesValue(G);let L=this.options.attributeValueProcessor(w,G,f);if(L===null||L===void 0)X[Y]=G;else if(typeof L!==typeof G||L!==G)X[Y]=L;else X[Y]=WH(G,this.options.parseAttributeValue,this.options.numberParseOptions)}else if(this.options.allowBooleanAttributes)X[Y]=!0}}if(!Object.keys(X).length)return;if(this.options.attributesGroupName){let z={};return z[this.options.attributesGroupName]=X,z}return X}}function ri($,f,W){let J=this.options.updateTag(f.tagname,W,f[":@"]);if(J===!1);else if(typeof J==="string")f.tagname=J,$.addChild(f);else $.addChild(f)}function pi($,f,W,J){if($){if(J===void 0)J=f.child.length===0;if($=this.parseTextData($,f.tagname,W,!1,f[":@"]?Object.keys(f[":@"]).length!==0:!1,J),$!==void 0&&$!=="")f.add(this.options.textNodeName,$);$=""}return $}function ni($,f,W){let J="*."+W;for(let Z in $){let X=$[Z];if(J===X||f===X)return!0}return!1}function si($,f,W=">"){let J,Z="";for(let X=f;X<$.length;X++){let z=$[X];if(J){if(z===J)J=""}else if(z==='"'||z==="'")J=z;else if(z===W[0])if(W[1]){if($[X+1]===W[1])return{data:Z,index:X}}else return{data:Z,index:X};else if(z==="\t")z=" ";Z+=z}}function q6($,f,W,J){let Z=$.indexOf(f,W);if(Z===-1)throw new Error(J);else return Z+f.length-1}function fH($,f,W,J=">"){let Z=si($,f+1,J);if(!Z)return;let{data:X,index:z}=Z,w=X.search(/\s/),G=X,Y=!0;if(w!==-1)G=X.substring(0,w),X=X.substring(w+1).trimStart();let L=G;if(W){let U=G.indexOf(":");if(U!==-1)G=G.substr(U+1),Y=G!==Z.data.substr(U+1)}return{tagName:G,tagExp:X,closeIndex:z,attrExpPresent:Y,rawTagName:L}}function ti($,f,W){let J=W,Z=1;for(;W<$.length;W++)if($[W]==="<")if($[W+1]==="/"){let X=q6($,">",W,`${f} is not closed`);if($.substring(W+2,X).trim()===f){if(Z--,Z===0)return{tagContent:$.substring(J,W),i:X}}W=X}else if($[W+1]==="?")W=q6($,"?>",W+1,"StopNode is not closed.");else if($.substr(W+1,3)==="!--")W=q6($,"-->",W+3,"StopNode is not closed.");else if($.substr(W+1,2)==="![")W=q6($,"]]>",W,"StopNode is not closed.")-2;else{let X=fH($,W,">");if(X){if((X&&X.tagName)===f&&X.tagExp[X.tagExp.length-1]!=="/")Z++;W=X.closeIndex}}}function WH($,f,W){if(f&&typeof $==="string"){let J=$.trim();if(J==="true")return!0;else if(J==="false")return!1;else return $H($,W)}else if(B_($))return $;else return""}var ci,ii=function($){$=$.replace(/\r\n?/g,`
`);let f=new L4("!xml"),W=f,J="",Z="";for(let X=0;X<$.length;X++)if($[X]==="<")if($[X+1]==="/"){let w=q6($,">",X,"Closing Tag is not closed."),G=$.substring(X+2,w).trim();if(this.options.removeNSPrefix){let U=G.indexOf(":");if(U!==-1)G=G.substr(U+1)}if(this.options.transformTagName)G=this.options.transformTagName(G);if(W)J=this.saveTextToParentTag(J,W,Z);let Y=Z.substring(Z.lastIndexOf(".")+1);if(G&&this.options.unpairedTags.indexOf(G)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${G}>`);let L=0;if(Y&&this.options.unpairedTags.indexOf(Y)!==-1)L=Z.lastIndexOf(".",Z.lastIndexOf(".")-1),this.tagsNodeStack.pop();else L=Z.lastIndexOf(".");Z=Z.substring(0,L),W=this.tagsNodeStack.pop(),J="",X=w}else if($[X+1]==="?"){let w=fH($,X,!1,"?>");if(!w)throw new Error("Pi Tag is not closed.");if(J=this.saveTextToParentTag(J,W,Z),this.options.ignoreDeclaration&&w.tagName==="?xml"||this.options.ignorePiTags);else{let G=new L4(w.tagName);if(G.add(this.options.textNodeName,""),w.tagName!==w.tagExp&&w.attrExpPresent)G[":@"]=this.buildAttributesMap(w.tagExp,Z,w.tagName);this.addChild(W,G,Z)}X=w.closeIndex+1}else if($.substr(X+1,3)==="!--"){let w=q6($,"-->",X+4,"Comment is not closed.");if(this.options.commentPropName){let G=$.substring(X+4,w-2);J=this.saveTextToParentTag(J,W,Z),W.add(this.options.commentPropName,[{[this.options.textNodeName]:G}])}X=w}else if($.substr(X+1,2)==="!D"){let w=eK($,X);this.docTypeEntities=w.entities,X=w.i}else if($.substr(X+1,2)==="!["){let w=q6($,"]]>",X,"CDATA is not closed.")-2,G=$.substring(X+9,w);J=this.saveTextToParentTag(J,W,Z);let Y=this.parseTextData(G,W.tagname,Z,!0,!1,!0,!0);if(Y==null)Y="";if(this.options.cdataPropName)W.add(this.options.cdataPropName,[{[this.options.textNodeName]:G}]);else W.add(this.options.textNodeName,Y);X=w+2}else{let w=fH($,X,this.options.removeNSPrefix),G=w.tagName,Y=w.rawTagName,L=w.tagExp,U=w.attrExpPresent,M=w.closeIndex;if(this.options.transformTagName)G=this.options.transformTagName(G);if(W&&J){if(W.tagname!=="!xml")J=this.saveTextToParentTag(J,W,Z,!1)}let q=W;if(q&&this.options.unpairedTags.indexOf(q.tagname)!==-1)W=this.tagsNodeStack.pop(),Z=Z.substring(0,Z.lastIndexOf("."));if(G!==f.tagname)Z+=Z?"."+G:G;if(this.isItStopNode(this.options.stopNodes,Z,G)){let V="";if(L.length>0&&L.lastIndexOf("/")===L.length-1){if(G[G.length-1]==="/")G=G.substr(0,G.length-1),Z=Z.substr(0,Z.length-1),L=G;else L=L.substr(0,L.length-1);X=w.closeIndex}else if(this.options.unpairedTags.indexOf(G)!==-1)X=w.closeIndex;else{let O=this.readStopNodeData($,Y,M+1);if(!O)throw new Error(`Unexpected end of ${Y}`);X=O.i,V=O.tagContent}let Q=new L4(G);if(G!==L&&U)Q[":@"]=this.buildAttributesMap(L,Z,G);if(V)V=this.parseTextData(V,G,Z,!0,U,!0,!0);Z=Z.substr(0,Z.lastIndexOf(".")),Q.add(this.options.textNodeName,V),this.addChild(W,Q,Z)}else{if(L.length>0&&L.lastIndexOf("/")===L.length-1){if(G[G.length-1]==="/")G=G.substr(0,G.length-1),Z=Z.substr(0,Z.length-1),L=G;else L=L.substr(0,L.length-1);if(this.options.transformTagName)G=this.options.transformTagName(G);let V=new L4(G);if(G!==L&&U)V[":@"]=this.buildAttributesMap(L,Z,G);this.addChild(W,V,Z),Z=Z.substr(0,Z.lastIndexOf("."))}else{let V=new L4(G);if(this.tagsNodeStack.push(W),G!==L&&U)V[":@"]=this.buildAttributesMap(L,Z,G);this.addChild(W,V,Z),W=V}J="",X=M}}else J+=$[X];return f.child},li=function($){if(this.options.processEntities){for(let f in this.docTypeEntities){let W=this.docTypeEntities[f];$=$.replace(W.regx,W.val)}for(let f in this.lastEntities){let W=this.lastEntities[f];$=$.replace(W.regex,W.val)}if(this.options.htmlEntities)for(let f in this.htmlEntities){let W=this.htmlEntities[f];$=$.replace(W.regex,W.val)}$=$.replace(this.ampEntity.regex,this.ampEntity.val)}return $};var k_=K(()=>{qz();v_();m_();ci=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm")});function JH($,f){return y_($,f)}function y_($,f,W){let J,Z={};for(let X=0;X<$.length;X++){let z=$[X],w=ai(z),G="";if(W===void 0)G=w;else G=W+"."+w;if(w===f.textNodeName)if(J===void 0)J=z[w];else J+=""+z[w];else if(w===void 0)continue;else if(z[w]){let Y=y_(z[w],f,G),L=ei(Y,f);if(z[":@"])oi(Y,z[":@"],G,f);else if(Object.keys(Y).length===1&&Y[f.textNodeName]!==void 0&&!f.alwaysCreateTextNode)Y=Y[f.textNodeName];else if(Object.keys(Y).length===0)if(f.alwaysCreateTextNode)Y[f.textNodeName]="";else Y="";if(Z[w]!==void 0&&Z.hasOwnProperty(w)){if(!Array.isArray(Z[w]))Z[w]=[Z[w]];Z[w].push(Y)}else if(f.isArray(w,G,L))Z[w]=[Y];else Z[w]=Y}}if(typeof J==="string"){if(J.length>0)Z[f.textNodeName]=J}else if(J!==void 0)Z[f.textNodeName]=J;return Z}function ai($){let f=Object.keys($);for(let W=0;W<f.length;W++){let J=f[W];if(J!==":@")return J}}function oi($,f,W,J){if(f){let Z=Object.keys(f),X=Z.length;for(let z=0;z<X;z++){let w=Z[z];if(J.isArray(w,W+"."+w,!0,!0))$[w]=[f[w]];else $[w]=f[w]}}}function ei($,f){let{textNodeName:W}=f,J=Object.keys($).length;if(J===0)return!0;if(J===1&&($[W]||typeof $[W]==="boolean"||$[W]===0))return!0;return!1}class hJ{constructor($){this.externalEntities={},this.options=h_($)}parse($,f){if(typeof $==="string");else if($.toString)$=$.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(f){if(f===!0)f={};let Z=aK($,f);if(Z!==!0)throw Error(`${Z.err.msg}:${Z.err.line}:${Z.err.col}`)}let W=new Vz(this.options);W.addExternalEntities(this.externalEntities);let J=W.parseXml($);if(this.options.preserveOrder||J===void 0)return J;else return JH(J,this.options)}addEntity($,f){if(f.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");else if($.indexOf("&")!==-1||$.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");else if(f==="&")throw new Error("An entity with value '&' is not permitted");else this.externalEntities[$]=f}}var j_=K(()=>{D_();k_();oK()});function ZH($,f){let W="";if(f.format&&f.indentBy.length>0)W=`
`;return b_($,f,"",W)}function b_($,f,W,J){let Z="",X=!1;for(let z=0;z<$.length;z++){let w=$[z],G=$r(w);if(G===void 0)continue;let Y="";if(W.length===0)Y=G;else Y=`${W}.${G}`;if(G===f.textNodeName){let V=w[G];if(!fr(Y,f))V=f.tagValueProcessor(G,V),V=u_(V,f);if(X)Z+=J;Z+=V,X=!1;continue}else if(G===f.cdataPropName){if(X)Z+=J;Z+=`<![CDATA[${w[G][0][f.textNodeName]}]]>`,X=!1;continue}else if(G===f.commentPropName){Z+=J+`<!--${w[G][0][f.textNodeName]}-->`,X=!0;continue}else if(G[0]==="?"){let V=g_(w[":@"],f),Q=G==="?xml"?"":J,O=w[G][0][f.textNodeName];O=O.length!==0?" "+O:"",Z+=Q+`<${G}${O}${V}?>`,X=!0;continue}let L=J;if(L!=="")L+=f.indentBy;let U=g_(w[":@"],f),M=J+`<${G}${U}`,q=b_(w[G],f,Y,L);if(f.unpairedTags.indexOf(G)!==-1)if(f.suppressUnpairedNode)Z+=M+">";else Z+=M+"/>";else if((!q||q.length===0)&&f.suppressEmptyNode)Z+=M+"/>";else if(q&&q.endsWith(">"))Z+=M+`>${q}${J}</${G}>`;else{if(Z+=M+">",q&&J!==""&&(q.includes("/>")||q.includes("</")))Z+=J+f.indentBy+q+J;else Z+=q;Z+=`</${G}>`}X=!0}return Z}function $r($){let f=Object.keys($);for(let W=0;W<f.length;W++){let J=f[W];if(!$.hasOwnProperty(J))continue;if(J!==":@")return J}}function g_($,f){let W="";if($&&!f.ignoreAttributes)for(let J in $){if(!$.hasOwnProperty(J))continue;let Z=f.attributeValueProcessor(J,$[J]);if(Z=u_(Z,f),Z===!0&&f.suppressBooleanAttributes)W+=` ${J.substr(f.attributeNamePrefix.length)}`;else W+=` ${J.substr(f.attributeNamePrefix.length)}="${Z}"`}return W}function fr($,f){$=$.substr(0,$.length-f.textNodeName.length-1);let W=$.substr($.lastIndexOf(".")+1);for(let J in f.stopNodes)if(f.stopNodes[J]===$||f.stopNodes[J]==="*."+W)return!0;return!1}function u_($,f){if($&&$.length>0&&f.processEntities)for(let W=0;W<f.entities.length;W++){let J=f.entities[W];$=$.replace(J.regex,J.val)}return $}function J9($){if(this.options=Object.assign({},Wr,$),this.options.ignoreAttributes===!0||this.options.attributesGroupName)this.isAttribute=function(){return!1};else this.ignoreAttributesFn=EJ(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Xr;if(this.processTextOrObjNode=Jr,this.options.format)this.indentate=Zr,this.tagEndChar=`>
`,this.newLine=`
`;else this.indentate=function(){return""},this.tagEndChar=">",this.newLine=""}function Jr($,f,W,J){let Z=this.j2x($,W+1,J.concat(f));if($[this.options.textNodeName]!==void 0&&Object.keys($).length===1)return this.buildTextValNode($[this.options.textNodeName],f,Z.attrStr,W);else return this.buildObjectNode(Z.val,f,Z.attrStr,W)}function Zr($){return this.options.indentBy.repeat($)}function Xr($){if($.startsWith(this.options.attributeNamePrefix)&&$!==this.options.textNodeName)return $.substr(this.attrPrefixLen);else return!1}var Wr;var c_=K(()=>{Wr={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function($,f){return f},attributeValueProcessor:function($,f){return f},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};J9.prototype.build=function($){if(this.options.preserveOrder)return ZH($,this.options);else{if(Array.isArray($)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1)$={[this.options.arrayNodeName]:$};return this.j2x($,0,[]).val}};J9.prototype.j2x=function($,f,W){let J="",Z="",X=W.join(".");for(let z in $){if(!Object.prototype.hasOwnProperty.call($,z))continue;if(typeof $[z]==="undefined"){if(this.isAttribute(z))Z+=""}else if($[z]===null)if(this.isAttribute(z))Z+="";else if(z===this.options.cdataPropName)Z+="";else if(z[0]==="?")Z+=this.indentate(f)+"<"+z+"?"+this.tagEndChar;else Z+=this.indentate(f)+"<"+z+"/"+this.tagEndChar;else if($[z]instanceof Date)Z+=this.buildTextValNode($[z],z,"",f);else if(typeof $[z]!=="object"){let w=this.isAttribute(z);if(w&&!this.ignoreAttributesFn(w,X))J+=this.buildAttrPairStr(w,""+$[z]);else if(!w)if(z===this.options.textNodeName){let G=this.options.tagValueProcessor(z,""+$[z]);Z+=this.replaceEntitiesValue(G)}else Z+=this.buildTextValNode($[z],z,"",f)}else if(Array.isArray($[z])){let w=$[z].length,G="",Y="";for(let L=0;L<w;L++){let U=$[z][L];if(typeof U==="undefined");else if(U===null)if(z[0]==="?")Z+=this.indentate(f)+"<"+z+"?"+this.tagEndChar;else Z+=this.indentate(f)+"<"+z+"/"+this.tagEndChar;else if(typeof U==="object")if(this.options.oneListGroup){let M=this.j2x(U,f+1,W.concat(z));if(G+=M.val,this.options.attributesGroupName&&U.hasOwnProperty(this.options.attributesGroupName))Y+=M.attrStr}else G+=this.processTextOrObjNode(U,z,f,W);else if(this.options.oneListGroup){let M=this.options.tagValueProcessor(z,U);M=this.replaceEntitiesValue(M),G+=M}else G+=this.buildTextValNode(U,z,"",f)}if(this.options.oneListGroup)G=this.buildObjectNode(G,z,Y,f);Z+=G}else if(this.options.attributesGroupName&&z===this.options.attributesGroupName){let w=Object.keys($[z]),G=w.length;for(let Y=0;Y<G;Y++)J+=this.buildAttrPairStr(w[Y],""+$[z][w[Y]])}else Z+=this.processTextOrObjNode($[z],z,f,W)}return{attrStr:J,val:Z}};J9.prototype.buildAttrPairStr=function($,f){if(f=this.options.attributeValueProcessor($,""+f),f=this.replaceEntitiesValue(f),this.options.suppressBooleanAttributes&&f==="true")return" "+$;else return" "+$+'="'+f+'"'};J9.prototype.buildObjectNode=function($,f,W,J){if($==="")if(f[0]==="?")return this.indentate(J)+"<"+f+W+"?"+this.tagEndChar;else return this.indentate(J)+"<"+f+W+this.closeTag(f)+this.tagEndChar;else{let Z="</"+f+this.tagEndChar,X="";if(f[0]==="?")X="?",Z="";if((W||W==="")&&$.indexOf("<")===-1)return this.indentate(J)+"<"+f+W+X+">"+$+Z;else if(this.options.commentPropName!==!1&&f===this.options.commentPropName&&X.length===0)return this.indentate(J)+`<!--${$}-->`+this.newLine;else return this.indentate(J)+"<"+f+W+X+this.tagEndChar+$+this.indentate(J)+Z}};J9.prototype.closeTag=function($){let f="";if(this.options.unpairedTags.indexOf($)!==-1){if(!this.options.suppressUnpairedNode)f="/"}else if(this.options.suppressEmptyNode)f="/";else f=`></${$}`;return f};J9.prototype.buildTextValNode=function($,f,W,J){if(this.options.cdataPropName!==!1&&f===this.options.cdataPropName)return this.indentate(J)+`<![CDATA[${$}]]>`+this.newLine;else if(this.options.commentPropName!==!1&&f===this.options.commentPropName)return this.indentate(J)+`<!--${$}-->`+this.newLine;else if(f[0]==="?")return this.indentate(J)+"<"+f+W+"?"+this.tagEndChar;else{let Z=this.options.tagValueProcessor(f,$);if(Z=this.replaceEntitiesValue(Z),Z==="")return this.indentate(J)+"<"+f+W+this.closeTag(f)+this.tagEndChar;else return this.indentate(J)+"<"+f+W+">"+Z+"</"+f+this.tagEndChar}};J9.prototype.replaceEntitiesValue=function($){if($&&$.length>0&&this.options.processEntities)for(let f=0;f<this.options.entities.length;f++){let W=this.options.entities[f];$=$.replace(W.regex,W.val)}return $}});var d_=K(()=>{oK();j_();c_()});function i_($){return new hJ().parse($)}var XH=K(()=>{d_()});async function r_($,f,W,J){if(!zr.includes($))throw new Error(`Invalid hash algorithm: ${$}`);let Z=new TextEncoder().encode((W??"")+f+(J??"")),X=await crypto.subtle.digest($,Z);return Array.from(new Uint8Array(X)).map((w)=>w.toString(16).padStart(2,"0")).join("")}function l_($){let f=new Uint8Array($);return crypto.getRandomValues(f),Array.from(f,(W)=>String.fromCharCode(33+W%94)).join("")}var zr,Qz;var p_=K(()=>{zr=["SHA-1","SHA-256","SHA-384","SHA-512"];Qz={sha256:async($,f,W)=>r_("SHA-256",$,f,W),sha1:async($,f,W)=>r_("SHA-1",$,f,W)}});function Iz($,f=0){return(g1[$[f+0]]+g1[$[f+1]]+g1[$[f+2]]+g1[$[f+3]]+"-"+g1[$[f+4]]+g1[$[f+5]]+"-"+g1[$[f+6]]+g1[$[f+7]]+"-"+g1[$[f+8]]+g1[$[f+9]]+"-"+g1[$[f+10]]+g1[$[f+11]]+g1[$[f+12]]+g1[$[f+13]]+g1[$[f+14]]+g1[$[f+15]]).toLowerCase()}var g1;var zH=K(()=>{g1=[];for(let $=0;$<256;++$)g1.push(($+256).toString(16).slice(1))});import{randomFillSync as wr}from"crypto";function t5(){if(Oz>Az.length-16)wr(Az),Oz=0;return Az.slice(Oz,Oz+=16)}var Az,Oz;var wH=K(()=>{Az=new Uint8Array(256),Oz=Az.length});import{randomUUID as Gr}from"crypto";var GH;var n_=K(()=>{GH={randomUUID:Gr}});function Yr($,f,W){if(GH.randomUUID&&!f&&!$)return GH.randomUUID();$=$||{};let J=$.random??$.rng?.()??t5();if(J.length<16)throw new Error("Random bytes length must be >= 16");if(J[6]=J[6]&15|64,J[8]=J[8]&63|128,f){if(W=W||0,W<0||W+16>f.length)throw new RangeError(`UUID byte range ${W}:${W+15} is out of buffer bounds`);for(let Z=0;Z<16;++Z)f[W+Z]=J[Z];return f}return Iz(J)}var YH;var s_=K(()=>{n_();wH();zH();YH=Yr});function Lr($,f,W){let J;if($)J=t_($.random??$.rng?.()??t5(),$.msecs,$.seq,f,W);else{let Z=Date.now(),X=t5();Kr(LH,Z,X),J=t_(X,LH.msecs,LH.seq,f,W)}return f??Iz(J)}function Kr($,f,W){if($.msecs??=-1/0,$.seq??=0,f>$.msecs)$.seq=W[6]<<23|W[7]<<16|W[8]<<8|W[9],$.msecs=f;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function t_($,f,W,J,Z=0){if($.length<16)throw new Error("Random bytes length must be >= 16");if(!J)J=new Uint8Array(16),Z=0;else if(Z<0||Z+16>J.length)throw new RangeError(`UUID byte range ${Z}:${Z+15} is out of buffer bounds`);return f??=Date.now(),W??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],J[Z++]=f/1099511627776&255,J[Z++]=f/4294967296&255,J[Z++]=f/16777216&255,J[Z++]=f/65536&255,J[Z++]=f/256&255,J[Z++]=f&255,J[Z++]=112|W>>>28&15,J[Z++]=W>>>20&255,J[Z++]=128|W>>>14&63,J[Z++]=W>>>6&255,J[Z++]=W<<2&255|$[10]&3,J[Z++]=$[11],J[Z++]=$[12],J[Z++]=$[13],J[Z++]=$[14],J[Z++]=$[15],J}var LH,KH;var a_=K(()=>{wH();zH();LH={};KH=Lr});var o_=K(()=>{s_();a_()});function e_(){return YH()}function $N(){return KH()}var fN=K(()=>{o_()});var WN=()=>{};function HH($){if($===void 0||$===null)return 0;return typeof $==="number"?$:Number.parseInt($,10)}var JN=()=>{};var R={};V1(R,{valid:()=>b,string:()=>mJ,strictObject:()=>LN,s:()=>Ll,refId:()=>AN,ref:()=>ON,recursive:()=>xN,record:()=>UN,partialObject:()=>KN,oneOf:()=>QN,object:()=>vJ,number:()=>IH,makeOpts:()=>Q6,literal:()=>GN,integer:()=>OH,fromSchema:()=>Z9,error:()=>C0,booleanSchema:()=>VH,boolean:()=>xH,array:()=>AH,anyOf:()=>VN,any:()=>QH,allOf:()=>IN,StringSchema:()=>Tz,Schema:()=>hf,RefType:()=>_H,RecordSchema:()=>HN,ObjectSchema:()=>YN,ArraySchema:()=>MN});function Hr($,f,W=void 0){let J=typeof f=="string"?wN(f):RH(f);return Sz($,J,W)}function Sz($,f,W=void 0){let J=typeof f=="string"?f.split(/[.\[\]\"]+/).filter((Z)=>Z):f;if(J.length===0)return $;try{let[Z,...X]=J;return!Z||!(Z in $)?W:Sz($[Z],X,W)}catch{if(typeof W<"u")return W;throw new Error(`Invalid path: ${J.join(".")}`)}}function Mr($){return $===null}function T1($){return!Array.isArray($)&&typeof $=="object"&&$!==null}function qr($){return Object.prototype.toString.call($)==="[object Object]"}function U2($){return typeof $=="string"}function z9($){return typeof $=="number"}function Vr($){return typeof $=="number"&&Number.isInteger($)}function qH($){return typeof $=="boolean"}function w9($){return Array.isArray($)}function Qr($){return typeof $!="boolean"}function Ir($){return $!==void 0&&Qr($)&&"type"in $}function K$($){return $ instanceof hf}function Or($){return K$($)&&typeof $.toJSON()=="boolean"}function Ar($,f,W){if(!$)throw new Rr(f,W)}function X9($){if(w9($))return $.map(X9).sort();if(T1($)){let f=Object.entries($).sort(([W],[J])=>W.localeCompare(J)).map(([W,J])=>[W,X9(J)]);return Object.fromEntries(f)}return U2($)?$.normalize("NFC"):$}function xr($,f){return f.reduce((W,J)=>((J in $)&&(W[J]=$[J]),W),{})}function _r($,f,W={}){let J=f;try{J=structuredClone(f)}catch{J=JSON.parse(JSON.stringify(f))}let Z={resolver:W.resolver||new Nz($),depth:W.depth||0,dropUnknown:W.dropUnknown||!1};return Z.resolver.hasRef($,J)?Z.resolver.resolve($.$ref).coerce(J,{...Z,depth:Z.depth+1}):J}function Fz($,f,W={}){return $.map((J)=>J.validate(f,_z(W)).valid?J:void 0).filter(Boolean)}function Jl($,f,W={}){let J={keywordPath:W.keywordPath||[],instancePath:W.instancePath||[],coerce:W.coerce||!1,errors:W.errors||[],shortCircuit:W.shortCircuit||!1,ignoreUnsupported:W.ignoreUnsupported||!1,resolver:W.resolver||new Nz($),depth:W.depth?W.depth+1:0},Z=structuredClone(W?.coerce&&$.coerce?$.coerce(f,{resolver:J.resolver,depth:J.depth}):f);if(W.ignoreUnsupported!==!0){let X=["$defs"];for(let z of X)if($[z])throw new Error(`${z} not implemented`)}if(J.resolver.hasRef($,Z)){let X=J.resolver.resolve($.$ref).validate(Z,{...J,errors:[]});X.valid||J.errors.push(...X.errors)}else for(let[X,z]of Object.entries(Wl)){if($[X]===void 0||Z===void 0)continue;let w=z($,Z,{...J,errors:[]});if(!w.valid){if(W.shortCircuit)return w;J.errors.push(...w.errors)}}return{valid:J.errors.length===0,errors:J.errors}}function Bz($,f,W){return new class extends hf{type=$}(f,W)}function VH($){return new class extends hf{toJSON(){return $}validate(f,W){return $?b():C0(W,"","Always fails",f)}}}function XN($,f){return Array.isArray($)?$.map(f):$!==void 0?[f($)]:[]}function zN($,f,W=(J)=>J){return Object.fromEntries(Object.entries($).map(([J,Z])=>[J,W(f(Z),J)]))}function Z9($){if(qH($))return VH($);let f=structuredClone($);if(!T1(f))throw new Ur("non-object schemas not implemented",f);"properties"in f&&f.properties&&(f.properties=zN(f.properties,Z9,(X,z)=>("required"in f)&&Array.isArray(f.required)&&f.required.includes(z)?X:X.optional()));let W=["patternProperties","dependentSchemas","$defs"];for(let X of W)X in f&&f[X]&&(f[X]=zN(f[X],Z9));let J=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let X of J)X in f&&typeof f[X]<"u"&&(w9(f[X])?f[X]=XN(f[X],Z9):f[X]=Z9(f[X]));let Z=["anyOf","oneOf","allOf"];for(let X of Z)if(X in f){let{[X]:z}=f;f[X]=XN(z,Z9)}if(Ir(f))switch(f.type){case"string":return mJ(f);case"number":return IH(f);case"integer":return OH(f);case"boolean":return xH(f);case"object":{let{properties:X,...z}=f;return vJ(X,z)}case"array":{let{items:X,...z}=f;return AH(X,z)}}return QH(f)}function zl(){return{type($){let f=$.map((W)=>Array.isArray(W)?new Set(W):new Set([W])).reduce((W,J)=>W?new Set([...W].filter((Z)=>J.has(Z))):new Set(J));if(!f.size)throw new Error('Incompatible "type" in allOf');return f.size===1?[...f][0]:[...f]},enum($){let f=$.map((W)=>new Set(W)).reduce((W,J)=>new Set([...W].filter((Z)=>J.has(Z))));if(!f.size)throw new Error('Incompatible "enum" in allOf');return[...f]},required($){return[...new Set($.flat())]},properties($,f,W){return $.reduce((J,Z)=>W(J,Z),{})},patternProperties($,f,W){return $.reduce((J,Z)=>W(J,Z),{})},$defs($,f,W){return $.reduce((J,Z)=>W(J,Z),{})},definitions($,f,W){return $.reduce((J,Z)=>W(J,Z),{})},...Object.fromEntries(Zl.map(($)=>[$,(f)=>Math.min(...f)])),...Object.fromEntries(Xl.map(($)=>[$,(f)=>Math.max(...f)]))}}function wl($){let f={...zl(),...$.resolvers};function W(J,Z){if(Array.isArray(J)&&Array.isArray(Z))return[...new Set([...J,...Z])];if(MH(J)&&MH(Z)){let X={...J};for(let[z,w]of Object.entries(Z))if(z in X){let G=f[z];X[z]=G?G([X[z],w],z,W):UH(w)}else X[z]=UH(w);return X}return UH(Z)}return W}function Yl($,f={}){let W=f.deep!==!1,J=wl(f);function Z(X){if(Array.isArray(X))return X.map(Z);if(!MH(X))return X;if(Array.isArray(X.allOf)){let w=X.allOf.map(Z);if(w.some((q)=>q===!1))return!1;let G=w.filter((q)=>q!==!0);if(!G.length)return!0;let Y=G.reduce((q,V)=>J(q,V),{}),L=Gl(Y);if(L!==null)return L;let U={...X};delete U.allOf;let M=J(Y,W?Z(U):U);return W?Z(M):M}let z={};for(let[w,G]of Object.entries(X))z[w]=Z(G);return z}return Z($)}var RH=($=[],f="")=>"/"+[f,...$.map((W)=>String(W).replace(/\./g,"/"))].filter(Boolean).join("/"),wN=($)=>$.split("/").slice(1),C0=($={},f,W,J)=>({valid:!1,errors:[...$.errors??[],{keywordLocation:RH([...$.keywordPath??[],f]),instanceLocation:RH($.instancePath),error:typeof W=="string"?W:`Invalid value for ${f}`,data:J}]}),b=()=>({valid:!0,errors:[]}),Q6=($,f,W)=>{let J=Array.isArray(f)?f:[f],Z=W?Array.isArray(W)?W:[W]:[];return{...$,keywordPath:[...$.keywordPath??[],...J],instancePath:Z?[...$.instancePath??[],...Z]:$.instancePath}},_z=($={})=>({...$,errors:[]}),V6,Ur,Rr,Nz=class{constructor($){this.root=$,this.cache=new Map}cache;hasRef($,f){return f!==void 0&&"$ref"in $&&U2($.$ref)}resolve($){let f=this.cache.get($);if(!f){if(f=Hr(this.root,$),!K$(f))throw new Error(`ref not found: ${$}`);if("$ref"in f&&f.$ref===$)throw new Error(`ref loop: ${$}`);this.cache.set($,f)}return f}},Nr=({type:$},f,W={})=>{if($===void 0)return b();if(f===void 0)return b();let J,Z={string:U2,number:z9,integer:Vr,object:T1,array:w9,boolean:qH,null:Mr};if(Array.isArray($)){for(let X of $){if(!(X in Z))throw new V6(`Unknown type: ${X}`);if(Z[X](f))return b()}J=`Expected one of: ${$.join(", ")}`}else{if(!($ in Z))throw new V6(`Unknown type: ${$}`);Z[$](f)||(J=`Expected ${$}`)}return J?C0(W,"type",J,f):b()},Sr=({const:$},f,W={})=>{let J=JSON.stringify(X9($)),Z=JSON.stringify(X9(f));return J!==Z?C0(W,"const",`Expected const: ${J}`,Z):b()},Fr=({enum:$=[]},f,W={})=>{let J=JSON.stringify($.map(X9)),Z=JSON.stringify(X9(f));return J.includes(Z)?b():C0(W,"enum",`Expected enum: ${J}`,f)},Br=({anyOf:$=[]},f,W={})=>Fz($,f,W).length>0?b():C0(W,"anyOf","Expected at least one to match",f),Tr=({oneOf:$=[]},f,W={})=>Fz($,f).length===1?b():C0(W,"oneOf","Expected exactly one to match",f),Pr=({allOf:$=[]},f,W={})=>Fz($,f,W).length===$.length?b():C0(W,"allOf","Expected all to match",f),Cr=({not:$},f,W={})=>f===void 0?b():K$($)&&$.validate(f,W).valid?C0(W,"not","Expected not to match",f):b(),Er=({if:$,then:f,else:W},J,Z={})=>{if($&&(f||W)){if($.validate(J,_z(Z)).valid)return f?f.validate(J,_z(Z)):b();if(W)return W.validate(J,_z(Z))}return b()},hr=({pattern:$=""},f,W={})=>{if(!U2(f))return b();if($ instanceof RegExp){if($.test(f))return b()}else if(new RegExp($,"u").test(f))return b();return C0(W,"pattern",`Expected string matching pattern ${$}`,f)},Dr=({minLength:$=0},f,W={})=>U2(f)?[...X9(f)].length>=$?b():C0(W,"minLength",`Expected string with minimum length of ${$}`,f):b(),vr=({maxLength:$=0},f,W={})=>U2(f)?[...X9(f)].length<=$?b():C0(W,"maxLength",`Expected string with maximum length of ${$}`,f):b(),mr=({multipleOf:$=0},f,W={})=>{if(!z9(f))return b();if(!(Number.isFinite(f)&&Number.isFinite($))||$<=0)throw new V6("number");let J=f/$,Z=Number.EPSILON*Math.max(1,Math.abs(J));return Math.abs(J-Math.round(J))<=Z?b():C0(W,"multipleOf",`Expected number being a multiple of ${$}`,f)},kr=({maximum:$=0},f,W={})=>!z9(f)||f<=$?b():C0(W,"maximum",`Expected number less than or equal to ${$}`,f),yr=({exclusiveMaximum:$=0},f,W={})=>!z9(f)||f<$?b():C0(W,"exclusiveMaximum",`Expected number less than ${$}`,f),jr=({minimum:$=0},f,W={})=>!z9(f)||f>=$?b():C0(W,"minimum",`Expected number greater than or equal to ${$}`,f),gr=({exclusiveMinimum:$=0},f,W={})=>!z9(f)||f>$?b():C0(W,"exclusiveMinimum",`Expected number greater than ${$}`,f),br=({properties:$={}},f,W={})=>{if(!T1(f))return b();for(let[J,Z]of Object.entries(f)){let X=$[J];if(!K$(X))continue;let z=X.validate(Z,Q6(W,["properties",J],J));if(!z.valid)return z}return b()},ur=({properties:$={},additionalProperties:f,patternProperties:W},J,Z={})=>{if(!T1(J))return b();if(!K$(f))throw new V6("additionalProperties must be a boolean or a managed schema");let X=Object.keys($),z=T1(W)?Object.keys(J).filter((G)=>Object.keys(W).some((Y)=>new RegExp(Y).test(G))):[],w=Object.keys(J).filter((G)=>!X.includes(G)&&!z.includes(G));if(w.length>0){if(Or(f)){if(f.toJSON()===!0)return b();let G=w.reduce((Y,L)=>(Y[L]=J[L],Y),{});return C0(Z,"additionalProperties","Additional properties are not allowed",G)}else if(K$(f))for(let G of w){let Y=f.validate(J[G],Q6(Z,["additionalProperties"],G));if(!Y.valid)return Y}}return b()},cr=({dependentRequired:$},f,W={})=>{if(!T1(f))return b();let J=Object.keys(f).filter((Z)=>typeof f[Z]!="function");if(T1($)){for(let[Z,X]of Object.entries($))if(J.includes(Z)){for(let z of X)if(!J.includes(z))return C0(W,"dependentRequired",`Expected dependent required property ${z}`,f)}}return b()},dr=({required:$=[]},f,W={})=>{if(!T1(f))return b();let J=Object.keys(f).filter((Z)=>typeof f[Z]!="function");return $.every((Z)=>J.includes(Z))?b():C0(W,"required",`Expected object with required properties ${$.join(", ")}`,f)},ir=({dependentSchemas:$},f,W={})=>{if(!T1(f))return b();let J=Object.keys(f).filter((Z)=>typeof f[Z]!="function");if(T1($)){for(let[Z,X]of Object.entries($))if(J.includes(Z)){let z=X.validate(f,W);if(!z.valid)return z}}return b()},rr=({minProperties:$=0},f,W={})=>T1(f)?Object.keys(f).length>=$?b():C0(W,"minProperties",`Expected object with at least ${$} properties`,f):b(),lr=({maxProperties:$=0},f,W={})=>!T1(f)||Object.keys(f).length<=$?b():C0(W,"maxProperties",`Expected object with at most ${$} properties`,f),pr=({patternProperties:$={}},f,W={})=>{if(!T1(f))return b();if(!T1($))throw new V6("patternProperties must be an object");for(let[J,Z]of Object.entries(f))for(let[X,z]of Object.entries($))if(new RegExp(X,"u").test(J)){let w=z.validate(Z,Q6(W,["patternProperties"],J));if(!w.valid)return w}return b()},nr=({propertyNames:$},f,W={})=>{if(!T1(f)||$===void 0)return b();if(!K$($))throw new V6("propertyNames must be a managed schema");for(let J of Object.keys(f)){let Z=$.validate(J,Q6(W,["propertyNames"],J));if(!Z.valid)return Z}return b()},sr=({items:$,prefixItems:f=[]},W,J={})=>{if(!w9(W)||$===void 0)return b();if(!K$($))throw new V6("items must be a managed schema");for(let[Z,X]of W.slice(f.length).entries()){let z=$.validate(X,Q6(J,["items"],String(Z)));if(!z.valid)return z}return b()},tr=({minItems:$=0},f,W={})=>!w9(f)||f.length>=$?b():C0(W,"minItems",`Expected array with at least ${$} items`,f),ar=({maxItems:$=0},f,W={})=>!w9(f)||f.length<=$?b():C0(W,"maxItems",`Expected array with at most ${$} items`,f),or=({uniqueItems:$=!1},f,W={})=>{if(!w9(f)||!$)return b();let J=f.map(X9);return new Set(J.map((Z)=>JSON.stringify(Z))).size===f.length?b():C0(W,"uniqueItems","Expected array with unique items",f)},er=({contains:$,minContains:f,maxContains:W},J,Z={})=>{if(!K$($))throw new Error("contains must be a managed schema");if(!w9(J))return b();let X=J.filter((z)=>$.validate(z).valid).length;return X<(f??1)?C0(Z,f?"minContains":"contains",`Expected array to contain at least ${f??1}, but found ${X}`,J):W!==void 0&&X>W?C0(Z,"maxContains",`Expected array to contain at most ${W}, but found ${X}`,J):b()},$l=({prefixItems:$=[]},f,W={})=>{if(!w9(f))return b();for(let J=0;J<f.length;J++){let Z=$[J]?.validate(f[J],Q6(W,String(J),String(J)));if(Z&&Z?.valid!==!0)return Z}return b()},ZN,fl=({format:$},f,W={})=>!U2(f)||!$?b():ZN[$]?ZN[$](f)?b():C0(W,"format",`Expected format: ${$}`,f):b(),Wl,L$,hf,DJ=class{constructor($,f={}){this.schema=$,this.instancePath=f.instancePath||[],this.keywordPath=f.keywordPath||[];try{let W=Sz(f.data,this.instancePath);$.validate(W).valid&&(this.data=W)}catch{}}instancePath;keywordPath;data;appendInstancePath($){return this.instancePath=[...this.instancePath,...$],this}appendKeywordPath($){return this.keywordPath=[...this.keywordPath,...$],this}setData($){return this.data=structuredClone($),this}},QH=($)=>Bz($?.type,$),GN=($,f)=>Bz(void 0,{...f,const:$}),YN,vJ=($,f)=>new YN($,f),LN=($,f)=>vJ($,f).strict(),KN=($,f)=>vJ($,f).partial(),HN,UN=($,f)=>new HN($,f),Tz,mJ=($)=>new Tz($),RN=($,f,W)=>Bz($,W,{template:(J,Z)=>Z?.withExtendedOptional&&(J===void 0||!z9(J))?W?.minimum??0:J,coerce:(J)=>{if(U2(J)){let Z=f.parseFn(J);if(!Number.isNaN(Z))return Z}return J}}),IH=($)=>RN("number",{parseFn:Number},$),OH=($)=>RN("integer",{parseFn:Number.parseInt},$),MN,AH=($,f)=>new MN($,f),xH=($)=>Bz("boolean",$,{template:(f,W)=>W?.withExtendedOptional&&(f===void 0||!qH(f))?!1:f,coerce:(f)=>{if(U2(f)&&["true","false","1","0"].includes(f))return f==="true"||f==="1";if(z9(f)){if(f===1)return!0;if(f===0)return!1}return f}}),xz,qN,VN=($,f)=>new qN($,"anyOf",f),QN=($,f)=>new qN($,"oneOf",f),MH=($)=>typeof $=="object"&&$!==null&&!Array.isArray($),UH=($)=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone($):JSON.parse(JSON.stringify($)),Zl,Xl,Gl=($)=>$===!0||$===!1?$:null,IN=($,f)=>{let W=JSON.parse(JSON.stringify({...f,allOf:$}));return Z9(Yl(W))},_H,ON=($,f)=>new _H($,f),AN=($)=>new _H(void 0,$),xN=($)=>$(new hf({$ref:"#",coerce:(f,W)=>{let J=W?.resolver?.resolve("#");if(!K$(J))throw new Error("Ref not found: #");return J.coerce(f,W)}})),Ll;var NH=K(()=>{V6=class extends Error{constructor($){super(`Expected ${$}`)}},Ur=class extends Error{constructor($,f){super(`${$??"Invalid raw schema"}: ${JSON.stringify(f)}`);this.schema=f}},Rr=class extends Error{constructor($,f){super(`${$}, got: '${JSON.stringify(f)}'`);this.value=f}};ZN={email:($)=>{if($.length>318)return!1;if(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,20}(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,21}){0,2}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,60}[a-z0-9])?){0,3}$/i.test($))return!0;if(!$.includes("@")||/(^\.|^"|\.@|\.\.)/.test($))return!1;let[f,W,...J]=$.split("@");return!f||!W||J.length!==0||f.length>64||W.length>253||!/^[a-z0-9.-]+$/i.test(W)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(f)?!1:W.split(".").every((Z)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(Z))},hostname:($)=>$.length>($.endsWith(".")?254:253)?!1:/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i.test($),date:($)=>{if($.length!==10)return!1;if($[5]==="0"&&$[6]==="2"){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)$/.test($))return!0;let f=$.match(/^(\d\d\d\d)-02-29$/);if(!f)return!1;let W=Number(f[1]);return W%16===0||W%4===0&&W%25!==0}return $.endsWith("31")?/^\d\d\d\d-(?:0[13578]|1[02])-31$/.test($):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)$/.test($)},time:($)=>{if($.length>27||!/^(?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)?$/i.test($))return!1;if(!/:60/.test($))return!0;let f=$.match(/([0-9.]+|[^0-9.])/g);if(!f)return!1;let W=Number(f[0])*60+Number(f[2]);return f[5]==="+"?W+=1440-Number(f[6]||0)*60-Number(f[8]||0):f[5]==="-"&&(W+=Number(f[6]||0)*60+Number(f[8]||0)),W%1440===1439},"date-time":($)=>{if($.length>38)return!1;let f=/^\d\d\d\d-(?:0[1-9]|1[0-2])-(?:[0-2]\d|3[01])[t\s](?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)$/i,W=$[5]==="0"&&$[6]==="2";if(W&&$[8]==="3"||!f.test($))return!1;if($[17]==="6"){let J=$.slice(11).match(/([0-9.]+|[^0-9.])/g);if(!J)return!1;let Z=Number(J[0])*60+Number(J[2]);if(J[5]==="+"?Z+=1440-Number(J[6]||0)*60-Number(J[8]||0):J[5]==="-"&&(Z+=Number(J[6]||0)*60+Number(J[8]||0)),Z%1440!==1439)return!1}if(W){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)/.test($))return!0;let J=$.match(/^(\d\d\d\d)-02-29/);if(!J)return!1;let Z=Number(J[1]??0);return Z%16===0||Z%4===0&&Z%25!==0}return $[8]==="3"&&$[9]==="1"?/^\d\d\d\d-(?:0[13578]|1[02])-31/.test($):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)/.test($)},ipv4:($)=>$.length<=15&&/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)$/.test($),ipv6:($)=>{if($.length>45||$.length<2)return!1;let f=0,W=0,J=0,Z=!1,X=!1,z=0,w=!0;for(let Y=0;Y<$.length;Y++){let L=$.charCodeAt(Y);if(Y===1&&z===58&&L!==58)return!1;if(L>=48&&L<=57){if(++J>4)return!1}else if(L===46){if(f>6||W>=3||J===0||X)return!1;W++,J=0}else if(L===58){if(W>0||f>=7)return!1;if(z===58){if(Z)return!1;Z=!0}else Y===0&&(w=!1);f++,J=0,X=!1}else if(L>=97&&L<=102||L>=65&&L<=70){if(W>0||++J>4)return!1;X=!0}else return!1;z=L}if(f<2||W>0&&(W!==3||J===0))return!1;if(Z&&$.length===2)return!0;if(W>0&&!/(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test($))return!1;let G=W>0?6:7;return Z?(w||J>0)&&f<G:f===G&&w&&J>0},uri:($)=>/^[a-z][a-z0-9+\-.]*:(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test($),"uri-reference":($)=>/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)?(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test($),"uri-template":($)=>/^(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2}|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i.test($),"json-pointer":($)=>/^(?:|\/(?:[^~]|~0|~1)*)$/.test($),"relative-json-pointer":($)=>/^(?:0|[1-9][0-9]*)(?:|#|\/(?:[^~]|~0|~1)*)$/.test($),uuid:($)=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test($),duration:($)=>$.length>1&&$.length<80&&(/^P\d+([.,]\d+)?W$/.test($)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test($)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test($)),regex:($)=>{if(/[^\\]\\Z/.test($))return!1;try{return new RegExp($,"u"),!0}catch{return!1}}},Wl={type:Nr,const:Sr,enum:Fr,allOf:Pr,anyOf:Br,oneOf:Tr,not:Cr,minLength:Dr,maxLength:vr,pattern:hr,format:fl,minimum:jr,exclusiveMinimum:gr,maximum:kr,exclusiveMaximum:yr,multipleOf:mr,required:dr,dependentRequired:cr,dependentSchemas:ir,minProperties:rr,maxProperties:lr,propertyNames:nr,properties:br,patternProperties:pr,additionalProperties:ur,minItems:tr,maxItems:ar,uniqueItems:or,contains:er,prefixItems:$l,items:sr,if:Er};L$=Symbol.for("schema"),hf=class{"~standard";[L$];type;$id;$ref;$schema;title;description;readOnly;writeOnly;$comment;examples;constructor($,f){let{type:W,validate:J,coerce:Z,template:X,...z}=$||{};Object.assign(this,{type:W},z),this[L$]={raw:$,optional:!1,overrides:f},this["~standard"]={version:1,vendor:"jsonv-ts",validate:(w)=>{let G=this.validate(w);return G.valid?{value:w}:{issues:G.errors.map((Y)=>({message:Y.error,path:wN(Y.instanceLocation)}))}}}}template($,f){let W=this,J=$;if(W.const!==void 0?J=W.const:J===void 0&&(W.default!==void 0&&(J=W.default),f?.withExtendedOptional&&W.enum!==void 0&&(J=W.enum[0])),f?.withOptional!==!0&&J===void 0&&this.isOptional())return J;if(this[L$].raw?.template){let X=this[L$].raw.template(J,f);X!==void 0&&(J=X)}let Z=this[L$].overrides?.template?.(J,f);return Z!==void 0&&(J=Z),J}validate($,f){let W={keywordPath:f?.keywordPath||[],instancePath:f?.instancePath||[],coerce:f?.coerce||!1,errors:f?.errors||[],shortCircuit:f?.shortCircuit||!1,ignoreUnsupported:f?.ignoreUnsupported||!1,resolver:f?.resolver||new Nz(this),depth:f?.depth?f.depth+1:0},J=this[L$].raw?.validate;if(J!==void 0){let Z=J($,W);if(!Z.valid)return Z}return Jl(this,$,W)}coerce($,f){let W={...f,resolver:f?.resolver||new Nz(this),depth:f?.depth?f.depth+1:0,dropUnknown:f?.dropUnknown||!1},J=this[L$].raw?.coerce;if(J!==void 0)return J($,W);let Z=this[L$].overrides?.coerce?.($,W)??$;return _r(this,Z,W)}optional(){return this[L$].optional=!0,this}isOptional(){return this[L$].optional}children($){return[]}*walk({instancePath:$=[],keywordPath:f=[],...W}={}){W.includeSelf!==!1&&(yield new DJ(this,{instancePath:$,keywordPath:f,...W}));for(let J of this.children(W))yield*J.schema.walk({...W,instancePath:[...$,...J.instancePath],keywordPath:[...f,...J.keywordPath]})}*[Symbol.iterator]($){for(let f of this.walk($))yield f}toJSON(){let{toJSON:$,"~standard":f,...W}=this;return JSON.parse(JSON.stringify(W))}};YN=class $ extends hf{type="object";properties;required;constructor(f,W){let J=[];for(let[X,z]of Object.entries(f||{}))Ar(K$(z),"properties must be managed schemas",z),z[L$].optional||J.push(X);let Z=W?.additionalProperties===!1?VH(!1):W?.additionalProperties;J=J.length>0?J:void 0,super({...W,additionalProperties:Z,properties:f,required:J},{template:(X,z)=>{let w=structuredClone(T1(X)?X:{}),G={...w};if(this.properties)for(let[Y,L]of Object.entries(this.properties)){let U=Sz(w,Y);if(L.isOptional()&&z?.withOptional!==!0&&U===void 0&&X===void 0)continue;let M=L.template(U,z);M!==void 0&&(G[Y]=M)}if(!(Object.keys(G).length===0&&!z?.withExtendedOptional))return G},coerce:(X,z)=>{let w=structuredClone(X),G=Object.keys(this.properties),Y=G.length>0&&Object.values(this.properties).every((L)=>!L[L$].optional);if(qr(w)&&(z?.dropUnknown===!0||Y)&&(w=xr(w,G)),typeof w=="string"&&w.match(/^\{/)&&(w=JSON.parse(w)),!(typeof w!="object"||w===null)){if(this.properties)for(let[L,U]of Object.entries(this.properties)){let M=w[L];M!==void 0&&(w[L]=U.coerce(M,z))}return w}}}),this.properties=f,this.required=J}strict(){return new $(this.properties,{...this[L$].raw,additionalProperties:!1})}partial(){let f={...this.properties};for(let[,W]of Object.entries(f))W[L$].optional=!0;return new $(f,this[L$].raw)}children(f){let W=[];for(let[J,Z]of Object.entries(this.properties)){let X=new DJ(Z,f);X.appendInstancePath([J]),X.appendKeywordPath(["properties",J]),W.push(X)}return W}},HN=class extends hf{type="object";additionalProperties;constructor($,f){super({...f,additionalProperties:$},{template:(W,J)=>J?.withExtendedOptional&&(W===void 0||!T1(W))?{}:W}),this.additionalProperties=$}children($){let f=[],W=new DJ(this.additionalProperties,$);return W.appendKeywordPath(["additionalProperties"]),f.push(W),f}},Tz=class extends hf{type="string";constructor($){super($,{template:(f,W)=>W?.withExtendedOptional&&(f===void 0||!U2(f))?"":f,coerce:(f)=>z9(f)?String(f):f})}toJSON(){let{pattern:$,"~standard":f,...W}=this;return JSON.parse(JSON.stringify({...W,pattern:$ instanceof RegExp?$.source:$}))}},MN=class extends hf{constructor($,f={}){super({...f,items:$},{template:(W)=>W===void 0||!Array.isArray(W)?[]:W,coerce:(W,J)=>{try{let Z=typeof W=="string"?JSON.parse(W):W;if(!Array.isArray(Z))return;if(K$(this.items))for(let[X,z]of Z.entries())Z[X]=this.items.coerce(z,J);return Z}catch{}return W}});this.items=$,this.items=$}type="array";children($){let f=[];if(this.items){let W=new DJ(this.items,$);W.appendKeywordPath(["items"]),f.push(W)}return f}},xz=Symbol.for("unionType"),qN=class extends hf{[xz];constructor($,f,W){super({...W,[f]:$},{coerce:(J,Z)=>{let X=W?.coerce;if(X!==void 0)return X.bind(this)(J,Z);let z=Fz($,J,{ignoreUnsupported:!0,resolver:Z?.resolver,coerce:!0});return z.length>0?z[0].coerce(J,Z):J}}),this[xz]=f}get schemas(){return this[this[xz]]}children($){let f=[];for(let[W,J]of this.schemas.entries()){let Z=new DJ(J,$);Z.appendKeywordPath([this[xz],W]),f.push(Z)}return f}};Zl=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],Xl=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];_H=class extends hf{$ref;constructor($,f){if(!f&&!K$($))throw new Error("Ref not set");if(K$($)&&!$.$id)throw new Error("Ref must have an $id");let W=f??$?.$id;super({$ref:W},{coerce:(J,Z)=>{let X=Z?.resolver?.resolve(this.$ref);if(!K$(X))throw new Error(`Ref not found: ${this.$ref}`);return X.coerce(J,Z)}}),this.$ref=W}},Ll={boolean:xH,any:QH,literal:GN,object:vJ,strictObject:LN,partialObject:KN,record:UN,string:mJ,number:IH,integer:OH,array:AH,anyOf:VN,oneOf:QN,allOf:IN,ref:ON,refId:AN,recursive:xN}});var FH=($)=>{let f=$.split("/");if(f[0]==="")f.shift();return f},_N=($)=>{let{groups:f,path:W}=Kl($),J=FH(W);return Hl(J,f)},Kl=($)=>{let f=[];return $=$.replace(/\{[^}]+\}/g,(W,J)=>{let Z=`@${J}`;return f.push([Z,W]),Z}),{groups:f,path:$}},Hl=($,f)=>{for(let W=f.length-1;W>=0;W--){let[J]=f[W];for(let Z=$.length-1;Z>=0;Z--)if($[Z].includes(J)){$[Z]=$[Z].replace(J,f[W][1]);break}}return $},Pz,NN=($,f)=>{if($==="*")return"*";let W=$.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(W){let J=`${$}#${f}`;if(!Pz[J])if(W[2])Pz[J]=f&&f[0]!==":"&&f[0]!=="*"?[J,W[1],new RegExp(`^${W[2]}(?=/${f})`)]:[$,W[1],new RegExp(`^${W[2]}$`)];else Pz[J]=[$,W[1],!0];return Pz[J]}return null},a5=($,f)=>{try{return f($)}catch{return $.replace(/(?:%[0-9A-Fa-f]{2})+/g,(W)=>{try{return f(W)}catch{return W}})}},Ul=($)=>a5($,decodeURI),BH=($)=>{let f=$.url,W=f.indexOf("/",f.charCodeAt(9)===58?13:8),J=W;for(;J<f.length;J++){let Z=f.charCodeAt(J);if(Z===37){let X=f.indexOf("?",J),z=f.slice(W,X===-1?void 0:X);return Ul(z.includes("%25")?z.replace(/%25/g,"%2525"):z)}else if(Z===63)break}return f.slice(W,J)},SN=($)=>{let f=BH($);return f.length>1&&f.at(-1)==="/"?f.slice(0,-1):f},I6=($,f,...W)=>{if(W.length)f=I6(f,...W);return`${$?.[0]==="/"?"":"/"}${$}${f==="/"?"":`${$?.at(-1)==="/"?"":"/"}${f?.[0]==="/"?f.slice(1):f}`}`},Cz=($)=>{if($.charCodeAt($.length-1)!==63||!$.includes(":"))return null;let f=$.split("/"),W=[],J="";return f.forEach((Z)=>{if(Z!==""&&!/\:/.test(Z))J+="/"+Z;else if(/\:/.test(Z))if(/\?/.test(Z)){if(W.length===0&&J==="")W.push("/");else W.push(J);let X=Z.replace("?","");J+="/"+X,W.push(J)}else J+="/"+Z}),W.filter((Z,X,z)=>z.indexOf(Z)===X)},SH=($)=>{if(!/[%+]/.test($))return $;if($.indexOf("+")!==-1)$=$.replace(/\+/g," ");return $.indexOf("%")!==-1?a5($,kJ):$},FN=($,f,W)=>{let J;if(!W&&f&&!/[%+]/.test(f)){let z=$.indexOf(`?${f}`,8);if(z===-1)z=$.indexOf(`&${f}`,8);while(z!==-1){let w=$.charCodeAt(z+f.length+1);if(w===61){let G=z+f.length+2,Y=$.indexOf("&",G);return SH($.slice(G,Y===-1?void 0:Y))}else if(w==38||isNaN(w))return"";z=$.indexOf(`&${f}`,z+1)}if(J=/[%+]/.test($),!J)return}let Z={};J??=/[%+]/.test($);let X=$.indexOf("?",8);while(X!==-1){let z=$.indexOf("&",X+1),w=$.indexOf("=",X);if(w>z&&z!==-1)w=-1;let G=$.slice(X+1,w===-1?z===-1?void 0:z:w);if(J)G=SH(G);if(X=z,G==="")continue;let Y;if(w===-1)Y="";else if(Y=$.slice(w+1,z===-1?void 0:z),J)Y=SH(Y);if(W){if(!(Z[G]&&Array.isArray(Z[G])))Z[G]=[];Z[G].push(Y)}else Z[G]??=Y}return f?Z[f]:Z},BN,TN=($,f)=>{return FN($,f,!0)},kJ;var O6=K(()=>{Pz={},BN=FN,kJ=decodeURIComponent});var TH,PN=async($)=>{let f=typeof $==="string"?new TextEncoder().encode($):$;return await crypto.subtle.importKey("raw",f,TH,!1,["sign","verify"])},Rl=async($,f)=>{let W=await PN(f),J=await crypto.subtle.sign(TH.name,W,new TextEncoder().encode($));return btoa(String.fromCharCode(...new Uint8Array(J)))},Ml=async($,f,W)=>{try{let J=atob($),Z=new Uint8Array(J.length);for(let X=0,z=J.length;X<z;X++)Z[X]=J.charCodeAt(X);return await crypto.subtle.verify(TH,W,Z,new TextEncoder().encode(f))}catch{return!1}},ql,Vl,Ez=($,f)=>{if(f&&$.indexOf(f)===-1)return{};let W=$.trim().split(";"),J={};for(let Z of W){Z=Z.trim();let X=Z.indexOf("=");if(X===-1)continue;let z=Z.substring(0,X).trim();if(f&&f!==z||!ql.test(z))continue;let w=Z.substring(X+1).trim();if(w.startsWith('"')&&w.endsWith('"'))w=w.slice(1,-1);if(Vl.test(w)){if(J[z]=w.indexOf("%")!==-1?a5(w,kJ):w,f)break}}return J},PH=async($,f,W)=>{let J={},Z=await PN(f);for(let[X,z]of Object.entries(Ez($,W))){let w=z.lastIndexOf(".");if(w<1)continue;let G=z.substring(0,w),Y=z.substring(w+1);if(Y.length!==44||!Y.endsWith("="))continue;let L=await Ml(Y,G,Z);J[X]=L?G:!1}return J},CN=($,f,W={})=>{let J=`${$}=${f}`;if($.startsWith("__Secure-")&&!W.secure)throw new Error("__Secure- Cookie must have Secure attributes");if($.startsWith("__Host-")){if(!W.secure)throw new Error("__Host- Cookie must have Secure attributes");if(W.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(W.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(W&&typeof W.maxAge==="number"&&W.maxAge>=0){if(W.maxAge>34560000)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");J+=`; Max-Age=${W.maxAge|0}`}if(W.domain&&W.prefix!=="host")J+=`; Domain=${W.domain}`;if(W.path)J+=`; Path=${W.path}`;if(W.expires){if(W.expires.getTime()-Date.now()>34560000000)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");J+=`; Expires=${W.expires.toUTCString()}`}if(W.httpOnly)J+="; HttpOnly";if(W.secure)J+="; Secure";if(W.sameSite)J+=`; SameSite=${W.sameSite.charAt(0).toUpperCase()+W.sameSite.slice(1)}`;if(W.priority)J+=`; Priority=${W.priority}`;if(W.partitioned){if(!W.secure)throw new Error("Partitioned Cookie must have Secure attributes");J+="; Partitioned"}return J},hz=($,f,W)=>{return f=encodeURIComponent(f),CN($,f,W)},o5=async($,f,W,J={})=>{let Z=await Rl(f,W);return f=`${f}.${Z}`,f=encodeURIComponent(f),CN($,f,J)};var CH=K(()=>{O6();TH={name:"HMAC",hash:"SHA-256"},ql=/^[\w!#$%&'*.^`|~+-]+$/,Vl=/^[ !#-:<-[\]-~]*$/});var Dz=($,f,W)=>{let J=$.req.raw.headers.get("Cookie");if(typeof f==="string"){if(!J)return;let X=f;if(W==="secure")X="__Secure-"+f;else if(W==="host")X="__Host-"+f;return Ez(J,X)[X]}if(!J)return{};return Ez(J)},yJ=async($,f,W,J)=>{let Z=$.req.raw.headers.get("Cookie");if(typeof W==="string"){if(!Z)return;let z=W;if(J==="secure")z="__Secure-"+W;else if(J==="host")z="__Host-"+W;return(await PH(Z,f,z))[z]}if(!Z)return{};return await PH(Z,f)},EH=($,f,W,J)=>{let Z;if(J?.prefix==="secure")Z=hz("__Secure-"+f,W,{path:"/",...J,secure:!0});else if(J?.prefix==="host")Z=hz("__Host-"+f,W,{...J,path:"/",secure:!0,domain:void 0});else Z=hz(f,W,{path:"/",...J});$.header("Set-Cookie",Z,{append:!0})},vz=async($,f,W,J,Z)=>{let X;if(Z?.prefix==="secure")X=await o5("__Secure-"+f,W,J,{path:"/",...Z,secure:!0});else if(Z?.prefix==="host")X=await o5("__Host-"+f,W,J,{...Z,path:"/",secure:!0,domain:void 0});else X=await o5(f,W,J,{path:"/",...Z});$.header("set-cookie",X,{append:!0})},EN=($,f,W)=>{let J=Dz($,f,W?.prefix);return EH($,f,"",{...W,maxAge:0}),J};var e5=K(()=>{CH()});var mz;var hH=K(()=>{mz=class extends Error{res;status;constructor($=500,f){super(f?.message,{cause:f?.cause});this.res=f?.res,this.status=$}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var hN=()=>{};var DN=($,f)=>{return new Response($,{headers:{"Content-Type":f}}).formData()};var vN=K(()=>{hN()});var Ql,Il,Ol,DH=($,f)=>{return async(W,J)=>{let Z={},X=W.req.header("Content-Type");switch($){case"json":if(!X||!Ql.test(X))break;try{Z=await W.req.json()}catch{throw new mz(400,{message:"Malformed JSON in request body"})}break;case"form":{if(!X||!(Il.test(X)||Ol.test(X)))break;let w;if(W.req.bodyCache.formData)w=await W.req.bodyCache.formData;else try{let Y=await W.req.arrayBuffer();w=await DN(Y,X),W.req.bodyCache.formData=w}catch(Y){let L="Malformed FormData request.";throw L+=Y instanceof Error?` ${Y.message}`:` ${String(Y)}`,new mz(400,{message:L})}let G={};w.forEach((Y,L)=>{if(L.endsWith("[]"))(G[L]??=[]).push(Y);else if(Array.isArray(G[L]))G[L].push(Y);else if(L in G)G[L]=[G[L],Y];else G[L]=Y}),Z=G;break}case"query":Z=Object.fromEntries(Object.entries(W.req.queries()).map(([w,G])=>{return G.length===1?[w,G[0]]:[w,G]}));break;case"param":Z=W.req.param();break;case"header":Z=W.req.header();break;case"cookie":Z=Dz(W);break}let z=await f(Z,W);if(z instanceof Response)return z;W.req.addValidatedData($,z),await J()}};var mN=K(()=>{e5();hH();vN();Ql=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Il=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,Ol=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/});var kN=K(()=>{mN()});function Al($){return Object.prototype.toString.call($)==="[object Object]"}function xl($){return $!==null&&typeof $=="object"}function mH($,...f){for(let W of f)for(let[J,Z]of Object.entries(W))Z!==void 0&&(!Al(Z)&&!Array.isArray(Z)||Array.isArray(Z)&&!Array.isArray($[J])?$[J]=Z:xl($[J])?mH($[J],Z):$[J]=Z);return $}function jJ($,f){let W=_l[f],J=Nl[f];return W?{parameters:Object.entries($.properties).map(([Z,X])=>({name:Z,in:W,required:$.required?.includes(Z)||void 0,description:X?.description||void 0,schema:structuredClone(X.toJSON())}))}:J?{requestBody:{content:{[J.type]:{schema:structuredClone($.toJSON()),example:$.examples?.[0]??$.template({},{withOptional:!0,withExtendedOptional:!0})}}}}:{}}var kz,W0=($,f,W,J)=>{let Z=DH($,async(X,z)=>{let w=W?.coerce!==!1?f.coerce(X,{dropUnknown:W?.dropUnknown}):X,G=f.validate(w);if(!G.valid)return z.json({...G,schema:f},400);if(J){let Y=J({result:G,data:w},z);if(Y)return Y}return w});return W?.skipOpenAPI?Z:Object.assign(Z,{[kz]:{type:"parameters",value:{target:$,schema:f}}})},_l,Nl,Sl=($)=>$.split("/").map((f)=>{let W=f;if(W.startsWith(":")){let J=W.match(/^:([^{?]+)(?:{(.+)})?(\?)?$/);J?W=`{${J[1]}}`:(W=W.slice(1,W.length),W.endsWith("?")&&(W=W.slice(0,-1)),W=`{${W}}`)}return W}).join("/"),yN=($)=>$.charAt(0).toUpperCase()+$.slice(1),vH,Fl=($,f)=>{let W=`${$}:${f}`;if(vH.has(W))return vH.get(W);let J=$;if(f==="/")return`${J}Index`;for(let Z of f.split("/"))Z.charCodeAt(0)===123?J+=`By${yN(Z.slice(1,-1))}`:J+=yN(Z);return vH.set(W,J),J},yz=($,f={})=>{let W=!1;return async(J)=>{if(!W){W=!0,f.paths=f.paths??{};for(let Z of $.routes)if(kz in Z.handler){let X=Z.method.toLowerCase(),z=Sl(Z.path),{type:w,value:G}=Z.handler[kz];f.paths[z]||(f.paths[z]={}),f.paths[z][X]||(f.paths[z][X]={responses:{},operationId:Fl(X,z)});let Y=f.paths[z][X];switch(w){case"parameters":let{parameters:L,requestBody:U}=jJ(G.schema,G.target);L&&(Y.parameters||(Y.parameters=[]),Y.parameters.push(...L.filter((M)=>{try{return!Y.parameters.some((q)=>q.name===M.name&&q.in===M.in)}catch{return!0}}))),U&&(Y.requestBody||(Y.requestBody={}),mH(Y.requestBody,U));break;case"route-doc":mH(f.paths[z][X],G);break}}}return J.json({openapi:"3.1.0",info:{title:"API",...f.info},...f})}},G0=($)=>Object.assign(async(f,W)=>{await W()},{[kz]:{type:"route-doc",value:$}});var jz=K(()=>{kN();kz=Symbol.for("jsonv");_l={query:"query",param:"path",header:"header",cookie:"cookie"},Nl={json:{type:"application/json"},form:{type:"multipart/form-data"}};vH=new Map});var $8,gz=($)=>new $8($);var jN=K(()=>{NH();$8=class $8 extends Tz{}});function F0($,f,W){let J=W?.clone?Tl($):$,Z=W?.coerce!==!1?J.coerce(f,{dropUnknown:W?.coerceDropUnknown??!1}):f;if(W?.withDefaults!==!1)Z=J.template(Z,{withOptional:!0,withExtendedOptional:W?.withExtendedDefaults??!1});let X=$.validate(Z,{shortCircuit:!0,ignoreUnsupported:!0});if(!X.valid)if(W?.onError)W.onError(X.errors);else throw new G9(J,f,X.errors);return Z}var gJ=($)=>$,kH=($)=>$,Bl,G9,Tl=($)=>{let f=$.toJSON();return Z9(f)};var gN=K(()=>{NH();jz();jz();jN();Bl=mJ({pattern:"^[a-zA-Z_][a-zA-Z0-9_]*$",minLength:2,maxLength:150});G9=class G9 extends Error{schema;value;errors;constructor($,f,W=[]){super(`Invalid schema given for ${JSON.stringify(f,null,2)}
Error: ${JSON.stringify(W[0],null,2)}`);this.schema=$;this.value=f;this.errors=W}first(){return this.errors[0]}firstToString(){let $=this.first();return`${$.error} at ${$.instanceLocation}`}}});var _=K(()=>{kK();iK();x_();F_();XH();vK();p_();fN();WN();tK();JN();gN()});var w1,R2;var Y9=K(()=>{w1=class w1 extends Error{code=400;name="Exception";_context=void 0;constructor($,f){super($);if(f)this.code=f}context($){return this._context=$,this}toJSON(){return{error:this.message,type:this.name,context:this._context}}};R2=class R2 extends Error{details;type;constructor($,f,W){super($);this.details=f;this.type=W}static with($,f,W){throw new R2($,f,W)}toJSON(){return{type:this.type??"unknown",message:this.message,details:this.details}}}});class B0{name;constructor($){this.name=$;this.name=$}toJSON(){return{name:this.name}}}class yH{permission;config;constructor($,f){this.permission=$;this.config=f}}class A6{name;permissions;is_default;implicit_allow;constructor($,f=[],W=!1,J=!1){this.name=$;this.permissions=f;this.is_default=W;this.implicit_allow=J}static createWithPermissionNames($,f,W=!1,J=!1){return new A6($,f.map((Z)=>new yH(new B0(Z))),W,J)}static create($){return new A6($.name,$.permissions?.map((f)=>new yH(new B0(f)))??[],$.is_default,$.implicit_allow)}}var jH=()=>{};class bz{permissions;roles;config;constructor($=[],f=[],W){this.permissions=$,this.roles=f,this.config=W}static create($,f,W){let J=f?Y4(f,({permissions:X=[],is_default:z,implicit_allow:w},G)=>{return A6.createWithPermissionNames(G,X,z,w)}):{},Z=$.map((X)=>new B0(X));return new bz(Z,Object.values(J),W)}getPermissionNames(){return this.permissions.map(($)=>$.name)}getPermissions(){return this.permissions}permissionExists($){return!!this.permissions.find((f)=>f.name===$)}setRoles($){return this.roles=$,this}getRoles(){return this.roles}setConfig($){return this.config={...this.config,...$},this}registerPermission($){if(this.permissions.find((f)=>f.name===$.name))throw new Error(`Permission ${$.name} already exists`);return this.permissions.push($),this}registerPermissions($){let f=Array.isArray($)?$:Object.values($);for(let W of f)this.registerPermission(W);return this}getUserRole($){if($&&typeof $.role==="string"){let f=this.roles?.find((W)=>W.name===$?.role);if(f)return A.debug(`guard: role "${$.role}" found`),f}return A.debug("guard: role not found",{user:$}),this.getDefaultRole()}getDefaultRole(){return this.roles?.find(($)=>$.is_default)}isEnabled(){return this.config?.enabled===!0}hasPermission($,f){if(!this.isEnabled())return!0;let W=typeof $==="string"?$:$.name;if(A.debug("guard: checking permission",{name:W,user:{id:f?.id,role:f?.role}}),!this.permissionExists(W))throw new Error(`Permission ${W} does not exist`);let Z=this.getUserRole(f);if(!Z)return A.debug("guard: user has no role, denying"),!1;else if(Z.implicit_allow===!0)return A.debug(`guard: role "${Z.name}" has implicit allow, allowing`),!0;let X=Z.permissions.find((z)=>z.permission.name===W);return A.debug("guard: rolePermission, allowing?",{permission:W,role:Z.name,allowing:!!X}),!!X}granted($,f){let W=f&&"get"in f?f.get("auth")?.user:f;return this.hasPermission($,W)}throwUnlessGranted($,f){if(!this.granted($,f))throw new w1(`Permission "${typeof $==="string"?$:$.name}" not granted`,403)}}var bN=K(()=>{Y9();_();jH()});class gH{_context=[];_enabled=!0;id=Math.random().toString(36).substr(2,9);last=0;constructor($=!0){this._enabled=$}context($){return this._context.push($),this}clear(){return this._context.pop(),this}reset(){return this.last=0,this}log(...$){if(!this._enabled)return this;let f=performance.now(),W=this.last===0?0:Number.parseInt(String(f-this.last)),J=" ".repeat(Math.max(this._context.length-1,0)),Z=this._context.length>0?`[${this._context[this._context.length-1]}]`:"";return console.log(J,Z,W,...$),this.last=f,this}}class s0{_returning;static slug="untitled-event";params;returned=!1;validate($){throw new uN(this,$)}clone($){let f=new this.constructor($);return f.returned=!0,f}constructor($){this.params=$}}var L9,uN;var bH=K(()=>{L9=class L9 extends Error{constructor($,f){super(`Expected "${$}", got "${f}"`)}};uN=class uN extends Error{data;constructor($,f){super(`Event "${$.constructor.slug}" returned without validation`);this.data=f}}});class uH{mode="async";event;handler;once=!1;id;constructor($,f,W="async",J){this.event=$,this.handler=f,this.mode=W,this.id=J}}var cN=()=>{};class Q${options;events=[];listeners=[];enabled=!0;asyncs=[];constructor($,f){this.options=f;if($)this.registerEvents($);f?.listeners?.forEach((W)=>this.addListener(W))}enable(){return this.enabled=!0,this}disable(){return this.enabled=!1,this}clearEvents(){return this.events=[],this}clearAll(){return this.clearEvents(),this.listeners=[],this}getListeners(){return[...this.listeners]}get Events(){return new Proxy(this,{get:($,f)=>{return this.events.find((W)=>W.slug===f)}})}eventExists($){let f;if(typeof $==="string")f=$;else f=$.constructor?.slug??$.slug;return!!this.events.find((W)=>f===W.slug)}throwIfEventNotRegistered($){if(!this.eventExists($)){let f=$.constructor?.slug??$.slug??$;throw new Error(`Event "${f}" not registered`)}}registerEvent($,f=!1){if(this.eventExists($)){if(f)return this;throw new Error(`Event "${$.name}" already registered.`)}return this.events.push($),this}registerEvents($){return(typeof $==="object"?Object.values($):$).forEach((W)=>this.registerEvent(W,!0)),this}addListener($){if(this.throwIfEventNotRegistered($.event),$.id){if(this.listeners.find((W)=>W.id===$.id))return A.debug(`Listener with id "${$.id}" already exists.`),this}return this.listeners.push($),this}createEventListener($,f,W="async"){let J=typeof $==="string"?this.events.find((z)=>z.slug===$):$,Z=typeof W==="string"?{mode:W}:W,X=new uH(J,f,Z.mode);if(Z.once)X.once=!0;if(Z.id)X.id=`${J.slug}-${Z.id}`;this.addListener(X)}onEvent($,f,W){this.createEventListener($,f,W)}on($,f,W){this.createEventListener($,f,W)}onAny($,f){this.events.forEach((W)=>this.onEvent(W,$,f))}collectAsyncs($){this.asyncs.push(...$)}async executeAsyncs($=(f)=>Promise.all(f)){if(this.asyncs.length===0)return;let f=[...this.asyncs];this.asyncs=[],await $(f.map((W)=>W()))}async emit($){let f=$.constructor.slug;if(!this.enabled)return A.debug("EventManager disabled, not emitting",f),$;if(!this.eventExists($))throw new Error(`Event "${f}" not registered`);let W=[],J=[];this.listeners=this.listeners.filter((X)=>{if(X.event.slug!==f)return!0;if(X.mode==="sync")W.push(X);else J.push(async()=>await X.handler($,X.event.slug));return!X.once}),this.collectAsyncs(J);let Z=$;for(let X of W)try{let z=await X.handler(Z,X.event.slug);if(typeof z!=="undefined"){let w=Z.validate(z);if(w&&w.constructor.slug===f){if(!w.returned)throw new Error(`Returned event ${w.constructor.slug} must be marked as returned.`);Z=w}}}catch(z){if(z instanceof L9)this.options?.onInvalidReturn?.(Z,z),A.warn(`Invalid return of event listener for "${f}": ${z.message}`);else if(this.options?.onError)this.options.onError(Z,z);else throw z}return Z}}var dN=K(()=>{bH();cN();_()});var M2=K(()=>{bH();dN()});function cH($){return $!==null&&$.constructor.name==="Object"}function iN($){try{return $===null||$===void 0||typeof $==="string"||typeof $==="number"||typeof $==="boolean"||Array.isArray($)||cH($)}catch(f){return!1}}function rN($,f){let W=[];function J(Z,X,z){if(!iN(Z)||!iN(X))throw new Error("Diff: Only primitive types are supported");if(Z===X)return;if(typeof Z!==typeof X)W.push({t:"e",p:z,o:Z,n:X});else if(Array.isArray(Z)&&Array.isArray(X)){let w=Math.max(Z.length,X.length);for(let G=0;G<w;G++)if(G>=Z.length)W.push({t:"a",p:[...z,G],o:void 0,n:X[G]});else if(G>=X.length)W.push({t:"r",p:[...z,G],o:Z[G],n:void 0});else J(Z[G],X[G],[...z,G])}else if(cH(Z)&&cH(X)){let w=Object.keys(Z),G=Object.keys(X),Y=new Set([...w,...G]);for(let L of Y)if(!(L in Z))W.push({t:"a",p:[...z,L],o:void 0,n:X[L]});else if(!(L in X))W.push({t:"r",p:[...z,L],o:Z[L],n:void 0});else J(Z[L],X[L],[...z,L])}else W.push({t:"e",p:z,o:Z,n:X})}return J($,f,[]),W}function lN($,f){let W=f8($);for(let J of f)Pl(W,J);return W}function Pl($,f){let{p:W,t:J,n:Z}=f,X=Cl($,W.slice(0,-1)),z=W[W.length-1];if(J==="a"||J==="e")X[z]=Z;else if(J==="r")if(Array.isArray(X))X.splice(z,1);else delete X[z]}function Cl($,f){let W=$;for(let J of f){if(W[J]===void 0)W[J]=typeof J==="number"?[]:{};W=W[J]}return W}function f8($){return JSON.parse(JSON.stringify($))}var pN=()=>{};function H$($){return typeof $==="undefined"||$===void 0}function q0($){return typeof $==="string"}function Df($){return typeof $==="number"}function K9($){return typeof $==="boolean"}function K4($){return $===null}function W8($){return $ instanceof Date}function H4($){return typeof $==="bigint"}function uz($){return typeof Buffer!=="undefined"&&Buffer.isBuffer($)}function V0($){return typeof $==="function"}function t0($){return typeof $==="object"&&$!==null}function cz($){if(!t0($)||jl($)!=="[object Object]")return!1;if(Object.getPrototypeOf($)===null)return!0;let f=$;while(Object.getPrototypeOf(f)!==null)f=Object.getPrototypeOf(f);return Object.getPrototypeOf($)===f}function nN($){return $[$.length-1]}function H($){return Object.freeze($)}function bJ($){if(P1($))return $;else return[$]}function P1($){return Array.isArray($)}function q2($){return $}function dz($,f){if(P1($)&&P1(f))return hl($,f);else if(t0($)&&t0(f))return Dl($,f);return $===f}function hl($,f){if($.length!==f.length)return!1;for(let W=0;W<$.length;++W)if(!dz($[W],f[W]))return!1;return!0}function Dl($,f){if(uz($)&&uz(f))return vl($,f);else if(W8($)&&W8(f))return ml($,f);return kl($,f)}function vl($,f){return Buffer.compare($,f)===0}function ml($,f){return $.getTime()===f.getTime()}function kl($,f){let W=Object.keys($),J=Object.keys(f);if(W.length!==J.length)return!1;for(let Z of W)if(!dz($[Z],f[Z]))return!1;return!0}function jl($){if($==null)return $===void 0?"[object Undefined]":"[object Null]";return yl.call($)}var yl;var I=K(()=>{yl=Object.prototype.toString});var U0;var x6=K(()=>{I();U0=H({is($){return $.kind==="AlterTableNode"},create($){return H({kind:"AlterTableNode",table:$})},cloneWithTableProps($,f){return H({...$,...f})},cloneWithColumnAlteration($,f){return H({...$,columnAlterations:$.columnAlterations?[...$.columnAlterations,f]:[f]})}})});var p;var i0=K(()=>{I();p=H({is($){return $.kind==="IdentifierNode"},create($){return H({kind:"IdentifierNode",name:$})}})});var Xf;var iz=K(()=>{I();i0();Xf=H({is($){return $.kind==="CreateIndexNode"},create($){return H({kind:"CreateIndexNode",name:p.create($)})},cloneWith($,f){return H({...$,...f})},cloneWithColumns($,f){return H({...$,columns:[...$.columns||[],...f]})}})});var uJ;var rz=K(()=>{I();i0();uJ=H({is($){return $.kind==="CreateSchemaNode"},create($,f){return H({kind:"CreateSchemaNode",schema:p.create($),...f})},cloneWith($,f){return H({...$,...f})}})});var dH,b1;var J8=K(()=>{I();dH=["preserve rows","delete rows","drop"],b1=H({is($){return $.kind==="CreateTableNode"},create($){return H({kind:"CreateTableNode",table:$,columns:H([])})},cloneWithColumn($,f){return H({...$,columns:H([...$.columns,f])})},cloneWithConstraint($,f){return H({...$,constraints:$.constraints?H([...$.constraints,f]):H([f])})},cloneWithFrontModifier($,f){return H({...$,frontModifiers:$.frontModifiers?H([...$.frontModifiers,f]):H([f])})},cloneWithEndModifier($,f){return H({...$,endModifiers:$.endModifiers?H([...$.endModifiers,f]):H([f])})},cloneWith($,f){return H({...$,...f})}})});var U$;var U4=K(()=>{I();i0();U$=H({is($){return $.kind==="SchemableIdentifierNode"},create($){return H({kind:"SchemableIdentifierNode",identifier:p.create($)})},createWithSchema($,f){return H({kind:"SchemableIdentifierNode",schema:p.create($),identifier:p.create(f)})}})});var H9;var cJ=K(()=>{I();U4();H9=H({is($){return $.kind==="DropIndexNode"},create($,f){return H({kind:"DropIndexNode",name:U$.create($),...f})},cloneWith($,f){return H({...$,...f})}})});var Z8;var lz=K(()=>{I();i0();Z8=H({is($){return $.kind==="DropSchemaNode"},create($,f){return H({kind:"DropSchemaNode",schema:p.create($),...f})},cloneWith($,f){return H({...$,...f})}})});var X8;var pz=K(()=>{I();X8=H({is($){return $.kind==="DropTableNode"},create($,f){return H({kind:"DropTableNode",table:$,...f})},cloneWith($,f){return H({...$,...f})}})});var I1;var vf=K(()=>{I();I1=H({is($){return $.kind==="AliasNode"},create($,f){return H({kind:"AliasNode",node:$,alias:f})}})});var t1;var _6=K(()=>{I();U4();t1=H({is($){return $.kind==="TableNode"},create($){return H({kind:"TableNode",table:U$.create($)})},createWithSchema($,f){return H({kind:"TableNode",table:U$.createWithSchema($,f)})}})});function y0($){return t0($)&&V0($.toOperationNode)}var g$=K(()=>{I()});function iH($){return t0($)&&"expressionType"in $&&y0($)}function rH($){return t0($)&&"expression"in $&&q0($.alias)&&y0($)}var lH=K(()=>{g$();I()});var mf;var pH=K(()=>{I();mf=H({is($){return $.kind==="SelectModifierNode"},create($,f){return H({kind:"SelectModifierNode",modifier:$,of:f})},createWithExpression($){return H({kind:"SelectModifierNode",rawModifier:$})}})});var R$;var R4=K(()=>{I();R$=H({is($){return $.kind==="AndNode"},create($,f){return H({kind:"AndNode",left:$,right:f})}})});var zf;var N6=K(()=>{I();zf=H({is($){return $.kind==="OrNode"},create($,f){return H({kind:"OrNode",left:$,right:f})}})});var dJ;var nH=K(()=>{I();R4();N6();dJ=H({is($){return $.kind==="OnNode"},create($){return H({kind:"OnNode",on:$})},cloneWithOperation($,f,W){return H({...$,on:f==="And"?R$.create($.on,W):zf.create($.on,W)})}})});var U9;var iJ=K(()=>{I();nH();U9=H({is($){return $.kind==="JoinNode"},create($,f){return H({kind:"JoinNode",joinType:$,table:f,on:void 0})},createWithOn($,f,W){return H({kind:"JoinNode",joinType:$,table:f,on:dJ.create(W)})},cloneWithOn($,f){return H({...$,on:$.on?dJ.cloneWithOperation($.on,"And",f):dJ.create(f)})}})});var R9;var nz=K(()=>{I();R9=H({is($){return $.kind==="BinaryOperationNode"},create($,f,W){return H({kind:"BinaryOperationNode",leftOperand:$,operator:f,rightOperand:W})}})});function gl($){return q0($)&&sz.includes($)}function bl($){return q0($)&&oH.includes($)}function ul($){return q0($)&&sH.includes($)}function cl($){return q0($)&&tH.includes($)}function tz($){return q0($)&&aH.includes($)}var sH,tH,aH,oH,sN,tN,sz,I$;var S6=K(()=>{I();sH=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],tH=["+","-","*","/","%","^","&","|","#","<<",">>"],aH=["->","->>"],oH=[...sH,...tH,"&&","||"],sN=["exists","not exists"],tN=["not","-",...sN],sz=[...oH,...aH,...tN,"between","between symmetric"],I$=H({is($){return $.kind==="OperatorNode"},create($){return H({kind:"OperatorNode",operator:$})}})});var z0;var u1=K(()=>{I();i0();z0=H({is($){return $.kind==="ColumnNode"},create($){return H({kind:"ColumnNode",column:p.create($)})}})});var F6;var rJ=K(()=>{I();F6=H({is($){return $.kind==="SelectAllNode"},create(){return H({kind:"SelectAllNode"})}})});var V2;var lJ=K(()=>{rJ();I();V2=H({is($){return $.kind==="ReferenceNode"},create($,f){return H({kind:"ReferenceNode",table:f,column:$})},createSelectAll($){return H({kind:"ReferenceNode",table:$,column:F6.create()})}})});class eH{#$;get dynamicReference(){return this.#$}get refType(){return}constructor($){this.#$=$}toOperationNode(){return $U(this.#$)}}function az($){return t0($)&&y0($)&&q0($.dynamicReference)}var oz=K(()=>{g$();c1();I()});var pJ;var fU=K(()=>{I();pJ=H({is($){return $.kind==="OrderByItemNode"},create($,f){return H({kind:"OrderByItemNode",orderBy:$,direction:f})}})});var E0;var M9=K(()=>{I();E0=H({is($){return $.kind==="RawNode"},create($,f){return H({kind:"RawNode",sqlFragments:H($),parameters:H(f)})},createWithSql($){return E0.create([$],[])},createWithChild($){return E0.create(["",""],[$])},createWithChildren($){return E0.create(new Array($.length+1).fill(""),$)}})});function JU($){return $==="asc"||$==="desc"}function Q2($){if($.length===2)return[WU($[0],$[1])];if($.length===1){let[f]=$;if(Array.isArray(f))return f.map((W)=>WU(W));return[WU(f)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${$.length}`)}function WU($,f){let W=dl($);if(pJ.is(W)){if(f)throw new Error("Cannot specify direction twice!");return W}return pJ.create(W,aN(f))}function dl($){if(q9($))return O$($);if(az($))return $.toOperationNode();let[f,W]=$.split(" ");if(W){if(!JU(W))throw new Error(`Invalid order by direction: ${W}`);return pJ.create(b$(f),aN(W))}return b$($)}function aN($){if(!$)return;if($==="asc"||$==="desc")return E0.createWithSql($);return $.toOperationNode()}var z8=K(()=>{oz();fU();M9();kf();c1()});var B6;var ez=K(()=>{I();B6=H({is($){return $.kind==="JSONReferenceNode"},create($,f){return H({kind:"JSONReferenceNode",reference:$,traversal:f})},cloneWithTraversal($,f){return H({...$,traversal:f})}})});var nJ;var $3=K(()=>{I();nJ=H({is($){return $.kind==="JSONOperatorChainNode"},create($){return H({kind:"JSONOperatorChainNode",operator:$,values:H([])})},cloneWithValue($,f){return H({...$,values:H([...$.values,f])})}})});var V9;var sJ=K(()=>{I();V9=H({is($){return $.kind==="JSONPathNode"},create($){return H({kind:"JSONPathNode",inOperator:$,pathLegs:H([])})},cloneWithLeg($,f){return H({...$,pathLegs:H([...$.pathLegs,f])})}})});function $U($){if(q0($))return b$($);return $.toOperationNode()}function Q9($){if(P1($))return $.map((f)=>d1(f));else return[d1($)]}function d1($){if(q9($))return O$($);return $U($)}function oN($,f){let W=b$($);if(tz(f))return B6.create(W,nJ.create(I$.create(f)));let J=f.slice(0,-1);if(tz(J))return B6.create(W,V9.create(I$.create(J)));throw new Error(`Invalid JSON operator: ${f}`)}function b$($){if(!$.includes("."))return V2.create(z0.create($));let W=$.split(".").map(XU);if(W.length===3)return il(W);if(W.length===2)return rl(W);throw new Error(`invalid column reference ${$}`)}function eN($){if($.includes(" as ")){let[W,J]=$.split(" as ").map(XU);return I1.create(b$(W),p.create(J))}else return b$($)}function ZU($){return z0.create($)}function w8($){if($.includes(" ")){let[W,J]=$.split(" ").map(XU);if(!JU(J))throw new Error(`invalid order direction "${J}" next to "${W}"`);return Q2([W,J])[0]}else return ZU($)}function il($){let[f,W,J]=$;return V2.create(z0.create(J),t1.createWithSchema(f,W))}function rl($){let[f,W]=$;return V2.create(z0.create(W),t1.create(f))}function XU($){return $.trim()}var c1=K(()=>{vf();u1();lJ();_6();I();kf();i0();z8();S6();ez();$3();sJ()});var tJ;var f3=K(()=>{I();tJ=H({is($){return $.kind==="PrimitiveValueListNode"},create($){return H({kind:"PrimitiveValueListNode",values:H([...$])})}})});var T6;var aJ=K(()=>{I();T6=H({is($){return $.kind==="ValueListNode"},create($){return H({kind:"ValueListNode",values:H($)})}})});var U1;var I2=K(()=>{I();U1=H({is($){return $.kind==="ValueNode"},create($){return H({kind:"ValueNode",value:$})},createImmediate($){return H({kind:"ValueNode",value:$,immediate:!0})}})});function $S($){if(P1($))return ll($);return T0($)}function T0($){if(q9($))return O$($);return U1.create($)}function W3($){return Df($)||K9($)||K4($)}function oJ($){if(!W3($))throw new Error(`unsafe immediate value ${JSON.stringify($)}`);return U1.createImmediate($)}function ll($){if($.some(q9))return T6.create($.map((f)=>T0(f)));return tJ.create($)}var O2=K(()=>{f3();aJ();I2();I();kf()});var yf;var G8=K(()=>{I();yf=H({is($){return $.kind==="ParensNode"},create($){return H({kind:"ParensNode",node:$})}})});function h0($){if($.length===3)return J3($[0],$[1],$[2]);else if($.length===1)return T0($[0]);throw new Error(`invalid arguments: ${JSON.stringify($)}`)}function J3($,f,W){if(pl(f)&&WS(W))return R9.create(d1($),zU(f),U1.createImmediate(W));return R9.create(d1($),zU(f),$S(W))}function C1($,f,W){return R9.create(d1($),zU(f),d1(W))}function wU($,f){return Y8(Object.entries($).filter(([,W])=>!H$(W)).map(([W,J])=>J3(W,WS(J)?"is":"=",J)),f)}function Y8($,f,W=!0){let J=f==="and"?R$.create:zf.create;if($.length===0)return R9.create(U1.createImmediate(1),I$.create("="),U1.createImmediate(f==="and"?1:0));let Z=fS($[0]);for(let X=1;X<$.length;++X)Z=J(Z,fS($[X]));if($.length>1&&W)return yf.create(Z);return Z}function pl($){return $==="is"||$==="is not"}function WS($){return K4($)||K9($)}function zU($){if(q0($)&&sz.includes($))return I$.create($);if(y0($))return $.toOperationNode();throw new Error(`invalid operator ${JSON.stringify($)}`)}function fS($){return y0($)?$.toOperationNode():$}var u$=K(()=>{nz();I();g$();S6();c1();O2();I2();R4();G8();N6()});var c$;var L8=K(()=>{I();c$=H({is($){return $.kind==="OrderByNode"},create($){return H({kind:"OrderByNode",items:H([...$])})},cloneWithItems($,f){return H({...$,items:H([...$.items,...f])})}})});var Z3;var GU=K(()=>{I();Z3=H({is($){return $.kind==="PartitionByNode"},create($){return H({kind:"PartitionByNode",items:H($)})},cloneWithItems($,f){return H({...$,items:H([...$.items,...f])})}})});var K8;var X3=K(()=>{I();L8();GU();K8=H({is($){return $.kind==="OverNode"},create(){return H({kind:"OverNode"})},cloneWithOrderByItems($,f){return H({...$,orderBy:$.orderBy?c$.cloneWithItems($.orderBy,f):c$.create(f)})},cloneWithPartitionByItems($,f){return H({...$,partitionBy:$.partitionBy?Z3.cloneWithItems($.partitionBy,f):Z3.create(f)})}})});var M4;var eJ=K(()=>{I();M4=H({is($){return $.kind==="FromNode"},create($){return H({kind:"FromNode",froms:H($)})},cloneWithFroms($,f){return H({...$,froms:H([...$.froms,...f])})}})});var z3;var YU=K(()=>{I();z3=H({is($){return $.kind==="GroupByNode"},create($){return H({kind:"GroupByNode",items:H($)})},cloneWithItems($,f){return H({...$,items:H([...$.items,...f])})}})});var w3;var LU=K(()=>{I();R4();N6();w3=H({is($){return $.kind==="HavingNode"},create($){return H({kind:"HavingNode",having:$})},cloneWithOperation($,f,W){return H({...$,having:f==="And"?R$.create($.having,W):zf.create($.having,W)})}})});var Y0;var q4=K(()=>{I();eJ();YU();LU();L8();Y0=H({is($){return $.kind==="SelectQueryNode"},create($){return H({kind:"SelectQueryNode",...$&&{with:$}})},createFrom($,f){return H({kind:"SelectQueryNode",from:M4.create($),...f&&{with:f}})},cloneWithSelections($,f){return H({...$,selections:$.selections?H([...$.selections,...f]):H(f)})},cloneWithDistinctOn($,f){return H({...$,distinctOn:$.distinctOn?H([...$.distinctOn,...f]):H(f)})},cloneWithFrontModifier($,f){return H({...$,frontModifiers:$.frontModifiers?H([...$.frontModifiers,f]):H([f])})},cloneWithOrderByItems($,f){return H({...$,orderBy:$.orderBy?c$.cloneWithItems($.orderBy,f):c$.create(f)})},cloneWithGroupByItems($,f){return H({...$,groupBy:$.groupBy?z3.cloneWithItems($.groupBy,f):z3.create(f)})},cloneWithLimit($,f){return H({...$,limit:f})},cloneWithOffset($,f){return H({...$,offset:f})},cloneWithFetch($,f){return H({...$,fetch:f})},cloneWithHaving($,f){return H({...$,having:$.having?w3.cloneWithOperation($.having,"And",f):w3.create(f)})},cloneWithSetOperations($,f){return H({...$,setOperations:$.setOperations?H([...$.setOperations,...f]):H([...f])})},cloneWithoutSelections($){return H({...$,selections:[]})},cloneWithoutLimit($){return H({...$,limit:void 0})},cloneWithoutOffset($){return H({...$,offset:void 0})},cloneWithoutOrderBy($){return H({...$,orderBy:void 0})},cloneWithoutGroupBy($){return H({...$,groupBy:void 0})}})});function E($,f){Object.defineProperties($.prototype,{then:{enumerable:!1,value:()=>{throw new Error(f)}}})}class V4{#$;constructor($){this.#$=H($)}on(...$){return new V4({...this.#$,joinNode:U9.cloneWithOn(this.#$.joinNode,h0($))})}onRef($,f,W){return new V4({...this.#$,joinNode:U9.cloneWithOn(this.#$.joinNode,C1($,f,W))})}onTrue(){return new V4({...this.#$,joinNode:U9.cloneWithOn(this.#$.joinNode,E0.createWithSql("true"))})}$call($){return $(this)}toOperationNode(){return this.#$.joinNode}}var KU=K(()=>{iJ();M9();u$();I();E(V4,"don't await JoinBuilder instances. They are never executed directly and are always just a part of a query.")});var HU;var UU=K(()=>{I();HU=H({is($){return $.kind==="PartitionByItemNode"},create($){return H({kind:"PartitionByItemNode",partitionBy:$})}})});function JS($){return Q9($).map(HU.create)}var ZS=K(()=>{UU();c1()});class H8{#$;constructor($){this.#$=H($)}orderBy($,f){return new H8({overNode:K8.cloneWithOrderByItems(this.#$.overNode,Q2([$,f]))})}partitionBy($){return new H8({overNode:K8.cloneWithPartitionByItems(this.#$.overNode,JS($))})}$call($){return $(this)}toOperationNode(){return this.#$.overNode}}var XS=K(()=>{X3();z8();ZS();I();E(H8,"don't await OverBuilder instances. They are never executed directly and are always just a part of a query.")});var P6;var RU=K(()=>{I();lJ();rJ();P6=H({is($){return $.kind==="SelectionNode"},create($){return H({kind:"SelectionNode",selection:$})},createSelectAll(){return H({kind:"SelectionNode",selection:F6.create()})},createSelectAllFromTable($){return H({kind:"SelectionNode",selection:V2.createSelectAll($)})}})});function i1($){if(V0($))return i1($(d$()));else if(P1($))return $.map((f)=>zS(f));else return[zS($)]}function zS($){if(q0($))return P6.create(eN($));else if(az($))return P6.create($.toOperationNode());else return P6.create(G3($))}function a1($){if(!$)return[P6.createSelectAll()];else if(Array.isArray($))return $.map(wS);else return[wS($)]}function wS($){if(q0($))return P6.createSelectAllFromTable(Q0($));throw new Error(`invalid value selectAll expression: ${JSON.stringify($)}`)}var Q4=K(()=>{I();RU();c1();oz();kf();o1();I4()});var MU;var qU=K(()=>{I();MU=H({is($){return $.kind==="ValuesNode"},create($){return H({kind:"ValuesNode",values:H($)})}})});var VU;var QU=K(()=>{I();VU=H({is($){return $.kind==="DefaultInsertValueNode"},create(){return H({kind:"DefaultInsertValueNode"})}})});function Y3($){let f=V0($)?$(d$()):$,W=P1(f)?f:H([f]);return nl(W)}function nl($){let f=sl($);return[H([...f.keys()].map(z0.create)),MU.create($.map((W)=>tl(W,f)))]}function sl($){let f=new Map;for(let W of $){let J=Object.keys(W);for(let Z of J)if(!f.has(Z)&&W[Z]!==void 0)f.set(Z,f.size)}return f}function tl($,f){let W=Object.keys($),J=Array.from({length:f.size}),Z=!1,X=W.length;for(let w of W){let G=f.get(w);if(H$(G)){X--;continue}let Y=$[w];if(H$(Y)||q9(Y))Z=!0;J[G]=Y}if(X<f.size||Z){let w=VU.create();return T6.create(J.map((G)=>H$(G)?w:T0(G)))}return tJ.create(J)}var IU=K(()=>{u1();f3();aJ();I();O2();qU();kf();QU();I4()});var O1;var C6=K(()=>{I();O1=H({is($){return $.kind==="InsertQueryNode"},create($,f,W){return H({kind:"InsertQueryNode",into:$,...f&&{with:f},replace:W})},createWithoutInto(){return H({kind:"InsertQueryNode"})},cloneWith($,f){return H({...$,...f})}})});var jf;var U8=K(()=>{I();eJ();jf=H({is($){return $.kind==="UpdateQueryNode"},create($,f){return H({kind:"UpdateQueryNode",table:$,...f&&{with:f}})},createWithoutTable(){return H({kind:"UpdateQueryNode"})},cloneWithFromItems($,f){return H({...$,from:$.from?M4.cloneWithFroms($.from,f):M4.create(f)})},cloneWithUpdates($,f){return H({...$,updates:$.updates?H([...$.updates,...f]):f})},cloneWithLimit($,f){return H({...$,limit:f})}})});var L3;var OU=K(()=>{I();L3=H({is($){return $.kind==="UsingNode"},create($){return H({kind:"UsingNode",tables:H($)})},cloneWithTables($,f){return H({...$,tables:H([...$.tables,...f])})}})});var gf;var $Z=K(()=>{I();eJ();L8();OU();gf=H({is($){return $.kind==="DeleteQueryNode"},create($,f){return H({kind:"DeleteQueryNode",from:M4.create($),...f&&{with:f}})},cloneWithOrderByItems($,f){return H({...$,orderBy:$.orderBy?c$.cloneWithItems($.orderBy,f):c$.create(f)})},cloneWithoutOrderBy($){return H({...$,orderBy:void 0})},cloneWithLimit($,f){return H({...$,limit:f})},cloneWithoutLimit($){return H({...$,limit:void 0})},cloneWithUsing($,f){return H({...$,using:$.using!==void 0?L3.cloneWithTables($.using,f):L3.create(f)})}})});var E1;var fZ=K(()=>{I();R4();N6();E1=H({is($){return $.kind==="WhereNode"},create($){return H({kind:"WhereNode",where:$})},cloneWithOperation($,f,W){return H({...$,where:f==="And"?R$.create($.where,W):zf.create($.where,W)})}})});var K3;var AU=K(()=>{I();K3=H({is($){return $.kind==="ReturningNode"},create($){return H({kind:"ReturningNode",selections:H($)})},cloneWithSelections($,f){return H({...$,selections:$.selections?H([...$.selections,...f]):H(f)})}})});var xU;var _U=K(()=>{I();xU=H({is($){return $.kind==="ExplainNode"},create($,f){return H({kind:"ExplainNode",format:$,options:f})}})});var A2;var R8=K(()=>{I();A2=H({is($){return $.kind==="WhenNode"},create($){return H({kind:"WhenNode",condition:$})},cloneWithResult($,f){return H({...$,result:f})}})});var A1;var M8=K(()=>{I();R8();A1=H({is($){return $.kind==="MergeQueryNode"},create($,f){return H({kind:"MergeQueryNode",into:$,...f&&{with:f}})},cloneWithUsing($,f){return H({...$,using:f})},cloneWithWhen($,f){return H({...$,whens:$.whens?H([...$.whens,f]):H([f])})},cloneWithThen($,f){return H({...$,whens:$.whens?H([...$.whens.slice(0,-1),A2.cloneWithResult($.whens[$.whens.length-1],f)]):void 0})}})});var H3;var NU=K(()=>{I();H3=H({is($){return $.kind==="OutputNode"},create($){return H({kind:"OutputNode",selections:H($)})},cloneWithSelections($,f){return H({...$,selections:$.selections?H([...$.selections,...f]):H(f)})}})});var T;var I9=K(()=>{C6();q4();U8();$Z();fZ();I();AU();_U();M8();NU();T=H({is($){return Y0.is($)||O1.is($)||jf.is($)||gf.is($)||A1.is($)},cloneWithEndModifier($,f){return H({...$,endModifiers:$.endModifiers?H([...$.endModifiers,f]):H([f])})},cloneWithWhere($,f){return H({...$,where:$.where?E1.cloneWithOperation($.where,"And",f):E1.create(f)})},cloneWithJoin($,f){return H({...$,joins:$.joins?H([...$.joins,f]):H([f])})},cloneWithReturning($,f){return H({...$,returning:$.returning?K3.cloneWithSelections($.returning,f):K3.create(f)})},cloneWithoutReturning($){return H({...$,returning:void 0})},cloneWithoutWhere($){return H({...$,where:void 0})},cloneWithExplain($,f,W){return H({...$,explain:xU.create(f,W?.toOperationNode())})},cloneWithTop($,f){return H({...$,top:f})},cloneWithOutput($,f){return H({...$,output:$.output?H3.cloneWithSelections($.output,f):H3.create(f)})}})});var U3;var SU=K(()=>{I();U3=H({is($){return $.kind==="ColumnUpdateNode"},create($,f){return H({kind:"ColumnUpdateNode",column:$,value:f})}})});function GS(...$){if($.length===2)return[U3.create(d1($[0]),T0($[1]))];return WZ($[0])}function WZ($){let f=V0($)?$(d$()):$;return Object.entries(f).filter(([W,J])=>J!==void 0).map(([W,J])=>{return U3.create(z0.create(W),T0(J))})}var R3=K(()=>{u1();SU();I4();I();O2();c1()});var FU;var BU=K(()=>{I();FU=H({is($){return $.kind==="OnDuplicateKeyNode"},create($){return H({kind:"OnDuplicateKeyNode",updates:$})}})});class M3{insertId;numInsertedOrUpdatedRows;constructor($,f){this.insertId=$,this.numInsertedOrUpdatedRows=f}}function bf($){return Object.prototype.hasOwnProperty.call($,"prototype")}var wf;var E6=K(()=>{wf=class wf extends Error{node;constructor($){super("no result");this.node=$}}});var e1;var q3=K(()=>{I();fZ();e1=H({is($){return $.kind==="OnConflictNode"},create(){return H({kind:"OnConflictNode"})},cloneWith($,f){return H({...$,...f})},cloneWithIndexWhere($,f){return H({...$,indexWhere:$.indexWhere?E1.cloneWithOperation($.indexWhere,"And",f):E1.create(f)})},cloneWithIndexOrWhere($,f){return H({...$,indexWhere:$.indexWhere?E1.cloneWithOperation($.indexWhere,"Or",f):E1.create(f)})},cloneWithUpdateWhere($,f){return H({...$,updateWhere:$.updateWhere?E1.cloneWithOperation($.updateWhere,"And",f):E1.create(f)})},cloneWithUpdateOrWhere($,f){return H({...$,updateWhere:$.updateWhere?E1.cloneWithOperation($.updateWhere,"Or",f):E1.create(f)})},cloneWithoutIndexWhere($){return H({...$,indexWhere:void 0})},cloneWithoutUpdateWhere($){return H({...$,updateWhere:void 0})}})});class Gf{#$;constructor($){this.#$=H($)}column($){let f=z0.create($);return new Gf({...this.#$,onConflictNode:e1.cloneWith(this.#$.onConflictNode,{columns:this.#$.onConflictNode.columns?H([...this.#$.onConflictNode.columns,f]):H([f])})})}columns($){let f=$.map(z0.create);return new Gf({...this.#$,onConflictNode:e1.cloneWith(this.#$.onConflictNode,{columns:this.#$.onConflictNode.columns?H([...this.#$.onConflictNode.columns,...f]):H(f)})})}constraint($){return new Gf({...this.#$,onConflictNode:e1.cloneWith(this.#$.onConflictNode,{constraint:p.create($)})})}expression($){return new Gf({...this.#$,onConflictNode:e1.cloneWith(this.#$.onConflictNode,{indexExpression:$.toOperationNode()})})}where(...$){return new Gf({...this.#$,onConflictNode:e1.cloneWithIndexWhere(this.#$.onConflictNode,h0($))})}whereRef($,f,W){return new Gf({...this.#$,onConflictNode:e1.cloneWithIndexWhere(this.#$.onConflictNode,C1($,f,W))})}clearWhere(){return new Gf({...this.#$,onConflictNode:e1.cloneWithoutIndexWhere(this.#$.onConflictNode)})}doNothing(){return new V3({...this.#$,onConflictNode:e1.cloneWith(this.#$.onConflictNode,{doNothing:!0})})}doUpdateSet($){return new h6({...this.#$,onConflictNode:e1.cloneWith(this.#$.onConflictNode,{updates:WZ($)})})}$call($){return $(this)}}class V3{#$;constructor($){this.#$=H($)}toOperationNode(){return this.#$.onConflictNode}}class h6{#$;constructor($){this.#$=H($)}where(...$){return new h6({...this.#$,onConflictNode:e1.cloneWithUpdateWhere(this.#$.onConflictNode,h0($))})}whereRef($,f,W){return new h6({...this.#$,onConflictNode:e1.cloneWithUpdateWhere(this.#$.onConflictNode,C1($,f,W))})}clearWhere(){return new h6({...this.#$,onConflictNode:e1.cloneWithoutUpdateWhere(this.#$.onConflictNode)})}$call($){return $(this)}toOperationNode(){return this.#$.onConflictNode}}var TU=K(()=>{u1();i0();q3();u$();R3();I();E(Gf,"don't await OnConflictBuilder instances.");E(V3,"don't await OnConflictDoNothingBuilder instances.");E(h6,"don't await OnConflictUpdateBuilder instances.")});var PU;var CU=K(()=>{I();PU=H({is($){return $.kind==="TopNode"},create($,f){return H({kind:"TopNode",expression:$,modifiers:f})}})});function uf($,f){if(!Df($)&&!H4($))throw new Error(`Invalid top expression: ${$}`);if(!H$(f)&&!al(f))throw new Error(`Invalid top modifiers: ${f}`);return PU.create($,f)}function al($){return $==="percent"||$==="with ties"||$==="percent with ties"}var q8=K(()=>{CU();I()});class j0{#$;constructor($){this.#$=H($)}values($){let[f,W]=Y3($);return new j0({...this.#$,queryNode:O1.cloneWith(this.#$.queryNode,{columns:f,values:W})})}columns($){return new j0({...this.#$,queryNode:O1.cloneWith(this.#$.queryNode,{columns:H($.map(z0.create))})})}expression($){return new j0({...this.#$,queryNode:O1.cloneWith(this.#$.queryNode,{values:O$($)})})}defaultValues(){return new j0({...this.#$,queryNode:O1.cloneWith(this.#$.queryNode,{defaultValues:!0})})}modifyEnd($){return new j0({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}ignore(){return new j0({...this.#$,queryNode:O1.cloneWith(this.#$.queryNode,{ignore:!0})})}top($,f){return new j0({...this.#$,queryNode:T.cloneWithTop(this.#$.queryNode,uf($,f))})}onConflict($){return new j0({...this.#$,queryNode:O1.cloneWith(this.#$.queryNode,{onConflict:$(new Gf({onConflictNode:e1.create()})).toOperationNode()})})}onDuplicateKeyUpdate($){return new j0({...this.#$,queryNode:O1.cloneWith(this.#$.queryNode,{onDuplicateKey:FU.create(WZ($))})})}returning($){return new j0({...this.#$,queryNode:T.cloneWithReturning(this.#$.queryNode,i1($))})}returningAll(){return new j0({...this.#$,queryNode:T.cloneWithReturning(this.#$.queryNode,a1())})}output($){return new j0({...this.#$,queryNode:T.cloneWithOutput(this.#$.queryNode,i1($))})}outputAll($){return new j0({...this.#$,queryNode:T.cloneWithOutput(this.#$.queryNode,a1($))})}clearReturning(){return new j0({...this.#$,queryNode:T.cloneWithoutReturning(this.#$.queryNode)})}$call($){return $(this)}$if($,f){if($)return f(this);return new j0({...this.#$})}$castTo(){return new j0(this.#$)}$narrowType(){return new j0(this.#$)}$assertType(){return new j0(this.#$)}withPlugin($){return new j0({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){let $=this.compile(),f=await this.#$.executor.executeQuery($,this.#$.queryId),{adapter:W}=this.#$.executor,J=$.query;if(J.returning&&W.supportsReturning||J.output&&W.supportsOutput)return f.rows;return[new M3(f.insertId,f.numAffectedRows??f.numUpdatedOrDeletedRows)]}async executeTakeFirst(){let[$]=await this.execute();return $}async executeTakeFirstOrThrow($=wf){let f=await this.executeTakeFirst();if(f===void 0)throw bf($)?new $(this.toOperationNode()):$(this.toOperationNode());return f}async*stream($=100){let f=this.compile(),W=this.#$.executor.stream(f,$,this.#$.queryId);for await(let J of W)yield*J.rows}async explain($,f){return await new j0({...this.#$,queryNode:T.cloneWithExplain(this.#$.queryNode,$,f)}).execute()}}var EU=K(()=>{Q4();IU();C6();I9();R3();I();BU();E6();kf();u1();TU();q3();q8();E(j0,"don't await InsertQueryBuilder instances directly. To execute the query you need to call `execute` or `executeTakeFirst`.")});class Q3{numDeletedRows;constructor($){this.numDeletedRows=$}}var D6;var JZ=K(()=>{I();D6=H({is($){return $.kind==="LimitNode"},create($){return H({kind:"LimitNode",limit:$})}})});class _0{#$;constructor($){this.#$=H($)}where(...$){return new _0({...this.#$,queryNode:T.cloneWithWhere(this.#$.queryNode,h0($))})}whereRef($,f,W){return new _0({...this.#$,queryNode:T.cloneWithWhere(this.#$.queryNode,C1($,f,W))})}clearWhere(){return new _0({...this.#$,queryNode:T.cloneWithoutWhere(this.#$.queryNode)})}top($,f){return new _0({...this.#$,queryNode:T.cloneWithTop(this.#$.queryNode,uf($,f))})}using($){return new _0({...this.#$,queryNode:gf.cloneWithUsing(this.#$.queryNode,x2($))})}innerJoin(...$){return new _0({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("InnerJoin",$))})}leftJoin(...$){return new _0({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("LeftJoin",$))})}rightJoin(...$){return new _0({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("RightJoin",$))})}fullJoin(...$){return new _0({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("FullJoin",$))})}returning($){return new _0({...this.#$,queryNode:T.cloneWithReturning(this.#$.queryNode,i1($))})}returningAll($){return new _0({...this.#$,queryNode:T.cloneWithReturning(this.#$.queryNode,a1($))})}output($){return new _0({...this.#$,queryNode:T.cloneWithOutput(this.#$.queryNode,i1($))})}outputAll($){return new _0({...this.#$,queryNode:T.cloneWithOutput(this.#$.queryNode,a1($))})}clearReturning(){return new _0({...this.#$,queryNode:T.cloneWithoutReturning(this.#$.queryNode)})}clearLimit(){return new _0({...this.#$,queryNode:gf.cloneWithoutLimit(this.#$.queryNode)})}clearOrderBy(){return new _0({...this.#$,queryNode:gf.cloneWithoutOrderBy(this.#$.queryNode)})}orderBy($,f){return new _0({...this.#$,queryNode:gf.cloneWithOrderByItems(this.#$.queryNode,Q2([$,f]))})}limit($){return new _0({...this.#$,queryNode:gf.cloneWithLimit(this.#$.queryNode,D6.create(T0($)))})}modifyEnd($){return new _0({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}$call($){return $(this)}$if($,f){if($)return f(this);return new _0({...this.#$})}$castTo(){return new _0(this.#$)}$narrowType(){return new _0(this.#$)}$assertType(){return new _0(this.#$)}withPlugin($){return new _0({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){let $=this.compile(),f=await this.#$.executor.executeQuery($,this.#$.queryId),{adapter:W}=this.#$.executor,J=$.query;if(J.returning&&W.supportsReturning||J.output&&W.supportsOutput)return f.rows;return[new Q3(f.numAffectedRows??f.numUpdatedOrDeletedRows??BigInt(0))]}async executeTakeFirst(){let[$]=await this.execute();return $}async executeTakeFirstOrThrow($=wf){let f=await this.executeTakeFirst();if(f===void 0)throw bf($)?new $(this.toOperationNode()):$(this.toOperationNode());return f}async*stream($=100){let f=this.compile(),W=this.#$.executor.stream(f,$,this.#$.queryId);for await(let J of W)yield*J.rows}async explain($,f){return await new _0({...this.#$,queryNode:T.cloneWithExplain(this.#$.queryNode,$,f)}).execute()}}var hU=K(()=>{ZZ();o1();Q4();I9();I();E6();$Z();JZ();z8();u$();O2();q8();E(_0,"don't await DeleteQueryBuilder instances directly. To execute the query you need to call `execute` or `executeTakeFirst`.")});class I3{numUpdatedRows;numChangedRows;constructor($,f){this.numUpdatedRows=$,this.numChangedRows=f}}class N0{#$;constructor($){this.#$=H($)}where(...$){return new N0({...this.#$,queryNode:T.cloneWithWhere(this.#$.queryNode,h0($))})}whereRef($,f,W){return new N0({...this.#$,queryNode:T.cloneWithWhere(this.#$.queryNode,C1($,f,W))})}clearWhere(){return new N0({...this.#$,queryNode:T.cloneWithoutWhere(this.#$.queryNode)})}top($,f){return new N0({...this.#$,queryNode:T.cloneWithTop(this.#$.queryNode,uf($,f))})}from($){return new N0({...this.#$,queryNode:jf.cloneWithFromItems(this.#$.queryNode,x2($))})}innerJoin(...$){return new N0({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("InnerJoin",$))})}leftJoin(...$){return new N0({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("LeftJoin",$))})}rightJoin(...$){return new N0({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("RightJoin",$))})}fullJoin(...$){return new N0({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("FullJoin",$))})}limit($){return new N0({...this.#$,queryNode:jf.cloneWithLimit(this.#$.queryNode,D6.create(T0($)))})}set(...$){return new N0({...this.#$,queryNode:jf.cloneWithUpdates(this.#$.queryNode,GS(...$))})}returning($){return new N0({...this.#$,queryNode:T.cloneWithReturning(this.#$.queryNode,i1($))})}returningAll($){return new N0({...this.#$,queryNode:T.cloneWithReturning(this.#$.queryNode,a1($))})}output($){return new N0({...this.#$,queryNode:T.cloneWithOutput(this.#$.queryNode,i1($))})}outputAll($){return new N0({...this.#$,queryNode:T.cloneWithOutput(this.#$.queryNode,a1($))})}modifyEnd($){return new N0({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}clearReturning(){return new N0({...this.#$,queryNode:T.cloneWithoutReturning(this.#$.queryNode)})}$call($){return $(this)}$if($,f){if($)return f(this);return new N0({...this.#$})}$castTo(){return new N0(this.#$)}$narrowType(){return new N0(this.#$)}$assertType(){return new N0(this.#$)}withPlugin($){return new N0({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){let $=this.compile(),f=await this.#$.executor.executeQuery($,this.#$.queryId),{adapter:W}=this.#$.executor,J=$.query;if(J.returning&&W.supportsReturning||J.output&&W.supportsOutput)return f.rows;return[new I3(f.numAffectedRows??f.numUpdatedOrDeletedRows??BigInt(0),f.numChangedRows)]}async executeTakeFirst(){let[$]=await this.execute();return $}async executeTakeFirstOrThrow($=wf){let f=await this.executeTakeFirst();if(f===void 0)throw bf($)?new $(this.toOperationNode()):$(this.toOperationNode());return f}async*stream($=100){let f=this.compile(),W=this.#$.executor.stream(f,$,this.#$.queryId);for await(let J of W)yield*J.rows}async explain($,f){return await new N0({...this.#$,queryNode:T.cloneWithExplain(this.#$.queryNode,$,f)}).execute()}}var O3=K(()=>{ZZ();o1();Q4();I9();U8();R3();I();E6();u$();O2();JZ();q8();E(N0,"don't await UpdateQueryBuilder instances directly. To execute the query you need to call `execute` or `executeTakeFirst`.")});var A3;var DU=K(()=>{I();u1();_6();A3=H({is($){return $.kind==="CommonTableExpressionNameNode"},create($,f){return H({kind:"CommonTableExpressionNameNode",table:t1.create($),columns:f?H(f.map(z0.create)):void 0})}})});var v6;var x3=K(()=>{I();v6=H({is($){return $.kind==="CommonTableExpressionNode"},create($,f){return H({kind:"CommonTableExpressionNode",name:$,expression:f})},cloneWith($,f){return H({...$,...f})}})});class V8{#$;constructor($){this.#$=H($)}materialized(){return new V8({...this.#$,node:v6.cloneWith(this.#$.node,{materialized:!0})})}notMaterialized(){return new V8({...this.#$,node:v6.cloneWith(this.#$.node,{materialized:!1})})}toOperationNode(){return this.#$.node}}var YS=K(()=>{x3();I();E(V8,"don't await CTEBuilder instances. They are never executed directly and are always just a part of a query.")});function vU($,f){let W=f(HS()).toOperationNode();if(V0($))return $(ol(W)).toOperationNode();return v6.create(LS($),W)}function ol($){return(f)=>{return new V8({node:v6.create(LS(f),$)})}}function LS($){if($.includes("(")){let f=$.split(/[\(\)]/),W=f[0],J=f[1].split(",").map((Z)=>Z.trim());return A3.create(W,J)}else return A3.create($)}var KS=K(()=>{DU();_3();I();YS();x3()});var Q8;var mU=K(()=>{I();Q8=H({is($){return $.kind==="WithNode"},create($,f){return H({kind:"WithNode",expressions:H([$]),...f})},cloneWithExpression($,f){return H({...$,expressions:H([...$.expressions,f])})}})});function N3($){let f="";for(let W=0;W<$;++W)f+=el();return f}function el(){return US[~~(Math.random()*US.length)]}var US;var kU=K(()=>{US=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"]});function R0(){return new RS}class RS{#$;get queryId(){if(this.#$===void 0)this.#$=N3(8);return this.#$}}var m6=K(()=>{kU()});function S($){return $}class _2{nodeStack=[];#$=H({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this)});transformNode($){if(!$)return $;this.nodeStack.push($);let f=this.transformNodeImpl($);return this.nodeStack.pop(),H(f)}transformNodeImpl($){return this.#$[$.kind]($)}transformNodeList($){if(!$)return $;return H($.map((f)=>this.transformNode(f)))}transformSelectQuery($){return S({kind:"SelectQueryNode",from:this.transformNode($.from),selections:this.transformNodeList($.selections),distinctOn:this.transformNodeList($.distinctOn),joins:this.transformNodeList($.joins),groupBy:this.transformNode($.groupBy),orderBy:this.transformNode($.orderBy),where:this.transformNode($.where),frontModifiers:this.transformNodeList($.frontModifiers),endModifiers:this.transformNodeList($.endModifiers),limit:this.transformNode($.limit),offset:this.transformNode($.offset),with:this.transformNode($.with),having:this.transformNode($.having),explain:this.transformNode($.explain),setOperations:this.transformNodeList($.setOperations),fetch:this.transformNode($.fetch),top:this.transformNode($.top)})}transformSelection($){return S({kind:"SelectionNode",selection:this.transformNode($.selection)})}transformColumn($){return S({kind:"ColumnNode",column:this.transformNode($.column)})}transformAlias($){return S({kind:"AliasNode",node:this.transformNode($.node),alias:this.transformNode($.alias)})}transformTable($){return S({kind:"TableNode",table:this.transformNode($.table)})}transformFrom($){return S({kind:"FromNode",froms:this.transformNodeList($.froms)})}transformReference($){return S({kind:"ReferenceNode",column:this.transformNode($.column),table:this.transformNode($.table)})}transformAnd($){return S({kind:"AndNode",left:this.transformNode($.left),right:this.transformNode($.right)})}transformOr($){return S({kind:"OrNode",left:this.transformNode($.left),right:this.transformNode($.right)})}transformValueList($){return S({kind:"ValueListNode",values:this.transformNodeList($.values)})}transformParens($){return S({kind:"ParensNode",node:this.transformNode($.node)})}transformJoin($){return S({kind:"JoinNode",joinType:$.joinType,table:this.transformNode($.table),on:this.transformNode($.on)})}transformRaw($){return S({kind:"RawNode",sqlFragments:H([...$.sqlFragments]),parameters:this.transformNodeList($.parameters)})}transformWhere($){return S({kind:"WhereNode",where:this.transformNode($.where)})}transformInsertQuery($){return S({kind:"InsertQueryNode",into:this.transformNode($.into),columns:this.transformNodeList($.columns),values:this.transformNode($.values),returning:this.transformNode($.returning),onConflict:this.transformNode($.onConflict),onDuplicateKey:this.transformNode($.onDuplicateKey),endModifiers:this.transformNodeList($.endModifiers),with:this.transformNode($.with),ignore:$.ignore,replace:$.replace,explain:this.transformNode($.explain),defaultValues:$.defaultValues,top:this.transformNode($.top),output:this.transformNode($.output)})}transformValues($){return S({kind:"ValuesNode",values:this.transformNodeList($.values)})}transformDeleteQuery($){return S({kind:"DeleteQueryNode",from:this.transformNode($.from),using:this.transformNode($.using),joins:this.transformNodeList($.joins),where:this.transformNode($.where),returning:this.transformNode($.returning),endModifiers:this.transformNodeList($.endModifiers),with:this.transformNode($.with),orderBy:this.transformNode($.orderBy),limit:this.transformNode($.limit),explain:this.transformNode($.explain),top:this.transformNode($.top),output:this.transformNode($.output)})}transformReturning($){return S({kind:"ReturningNode",selections:this.transformNodeList($.selections)})}transformCreateTable($){return S({kind:"CreateTableNode",table:this.transformNode($.table),columns:this.transformNodeList($.columns),constraints:this.transformNodeList($.constraints),temporary:$.temporary,ifNotExists:$.ifNotExists,onCommit:$.onCommit,frontModifiers:this.transformNodeList($.frontModifiers),endModifiers:this.transformNodeList($.endModifiers),selectQuery:this.transformNode($.selectQuery)})}transformColumnDefinition($){return S({kind:"ColumnDefinitionNode",column:this.transformNode($.column),dataType:this.transformNode($.dataType),references:this.transformNode($.references),primaryKey:$.primaryKey,autoIncrement:$.autoIncrement,unique:$.unique,notNull:$.notNull,unsigned:$.unsigned,defaultTo:this.transformNode($.defaultTo),check:this.transformNode($.check),generated:this.transformNode($.generated),frontModifiers:this.transformNodeList($.frontModifiers),endModifiers:this.transformNodeList($.endModifiers),nullsNotDistinct:$.nullsNotDistinct,identity:$.identity,ifNotExists:$.ifNotExists})}transformAddColumn($){return S({kind:"AddColumnNode",column:this.transformNode($.column)})}transformDropTable($){return S({kind:"DropTableNode",table:this.transformNode($.table),ifExists:$.ifExists,cascade:$.cascade})}transformOrderBy($){return S({kind:"OrderByNode",items:this.transformNodeList($.items)})}transformOrderByItem($){return S({kind:"OrderByItemNode",orderBy:this.transformNode($.orderBy),direction:this.transformNode($.direction)})}transformGroupBy($){return S({kind:"GroupByNode",items:this.transformNodeList($.items)})}transformGroupByItem($){return S({kind:"GroupByItemNode",groupBy:this.transformNode($.groupBy)})}transformUpdateQuery($){return S({kind:"UpdateQueryNode",table:this.transformNode($.table),from:this.transformNode($.from),joins:this.transformNodeList($.joins),where:this.transformNode($.where),updates:this.transformNodeList($.updates),returning:this.transformNode($.returning),endModifiers:this.transformNodeList($.endModifiers),with:this.transformNode($.with),explain:this.transformNode($.explain),limit:this.transformNode($.limit),top:this.transformNode($.top),output:this.transformNode($.output)})}transformColumnUpdate($){return S({kind:"ColumnUpdateNode",column:this.transformNode($.column),value:this.transformNode($.value)})}transformLimit($){return S({kind:"LimitNode",limit:this.transformNode($.limit)})}transformOffset($){return S({kind:"OffsetNode",offset:this.transformNode($.offset)})}transformOnConflict($){return S({kind:"OnConflictNode",columns:this.transformNodeList($.columns),constraint:this.transformNode($.constraint),indexExpression:this.transformNode($.indexExpression),indexWhere:this.transformNode($.indexWhere),updates:this.transformNodeList($.updates),updateWhere:this.transformNode($.updateWhere),doNothing:$.doNothing})}transformOnDuplicateKey($){return S({kind:"OnDuplicateKeyNode",updates:this.transformNodeList($.updates)})}transformCreateIndex($){return S({kind:"CreateIndexNode",name:this.transformNode($.name),table:this.transformNode($.table),columns:this.transformNodeList($.columns),unique:$.unique,using:this.transformNode($.using),ifNotExists:$.ifNotExists,where:this.transformNode($.where),nullsNotDistinct:$.nullsNotDistinct})}transformList($){return S({kind:"ListNode",items:this.transformNodeList($.items)})}transformDropIndex($){return S({kind:"DropIndexNode",name:this.transformNode($.name),table:this.transformNode($.table),ifExists:$.ifExists,cascade:$.cascade})}transformPrimaryKeyConstraint($){return S({kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList($.columns),name:this.transformNode($.name)})}transformUniqueConstraint($){return S({kind:"UniqueConstraintNode",columns:this.transformNodeList($.columns),name:this.transformNode($.name),nullsNotDistinct:$.nullsNotDistinct})}transformForeignKeyConstraint($){return S({kind:"ForeignKeyConstraintNode",columns:this.transformNodeList($.columns),references:this.transformNode($.references),name:this.transformNode($.name),onDelete:$.onDelete,onUpdate:$.onUpdate})}transformSetOperation($){return S({kind:"SetOperationNode",operator:$.operator,expression:this.transformNode($.expression),all:$.all})}transformReferences($){return S({kind:"ReferencesNode",table:this.transformNode($.table),columns:this.transformNodeList($.columns),onDelete:$.onDelete,onUpdate:$.onUpdate})}transformCheckConstraint($){return S({kind:"CheckConstraintNode",expression:this.transformNode($.expression),name:this.transformNode($.name)})}transformWith($){return S({kind:"WithNode",expressions:this.transformNodeList($.expressions),recursive:$.recursive})}transformCommonTableExpression($){return S({kind:"CommonTableExpressionNode",name:this.transformNode($.name),materialized:$.materialized,expression:this.transformNode($.expression)})}transformCommonTableExpressionName($){return S({kind:"CommonTableExpressionNameNode",table:this.transformNode($.table),columns:this.transformNodeList($.columns)})}transformHaving($){return S({kind:"HavingNode",having:this.transformNode($.having)})}transformCreateSchema($){return S({kind:"CreateSchemaNode",schema:this.transformNode($.schema),ifNotExists:$.ifNotExists})}transformDropSchema($){return S({kind:"DropSchemaNode",schema:this.transformNode($.schema),ifExists:$.ifExists,cascade:$.cascade})}transformAlterTable($){return S({kind:"AlterTableNode",table:this.transformNode($.table),renameTo:this.transformNode($.renameTo),setSchema:this.transformNode($.setSchema),columnAlterations:this.transformNodeList($.columnAlterations),addConstraint:this.transformNode($.addConstraint),dropConstraint:this.transformNode($.dropConstraint),addIndex:this.transformNode($.addIndex),dropIndex:this.transformNode($.dropIndex)})}transformDropColumn($){return S({kind:"DropColumnNode",column:this.transformNode($.column)})}transformRenameColumn($){return S({kind:"RenameColumnNode",column:this.transformNode($.column),renameTo:this.transformNode($.renameTo)})}transformAlterColumn($){return S({kind:"AlterColumnNode",column:this.transformNode($.column),dataType:this.transformNode($.dataType),dataTypeExpression:this.transformNode($.dataTypeExpression),setDefault:this.transformNode($.setDefault),dropDefault:$.dropDefault,setNotNull:$.setNotNull,dropNotNull:$.dropNotNull})}transformModifyColumn($){return S({kind:"ModifyColumnNode",column:this.transformNode($.column)})}transformAddConstraint($){return S({kind:"AddConstraintNode",constraint:this.transformNode($.constraint)})}transformDropConstraint($){return S({kind:"DropConstraintNode",constraintName:this.transformNode($.constraintName),ifExists:$.ifExists,modifier:$.modifier})}transformCreateView($){return S({kind:"CreateViewNode",name:this.transformNode($.name),temporary:$.temporary,orReplace:$.orReplace,ifNotExists:$.ifNotExists,materialized:$.materialized,columns:this.transformNodeList($.columns),as:this.transformNode($.as)})}transformDropView($){return S({kind:"DropViewNode",name:this.transformNode($.name),ifExists:$.ifExists,materialized:$.materialized,cascade:$.cascade})}transformGenerated($){return S({kind:"GeneratedNode",byDefault:$.byDefault,always:$.always,identity:$.identity,stored:$.stored,expression:this.transformNode($.expression)})}transformDefaultValue($){return S({kind:"DefaultValueNode",defaultValue:this.transformNode($.defaultValue)})}transformOn($){return S({kind:"OnNode",on:this.transformNode($.on)})}transformSelectModifier($){return S({kind:"SelectModifierNode",modifier:$.modifier,rawModifier:this.transformNode($.rawModifier),of:this.transformNodeList($.of)})}transformCreateType($){return S({kind:"CreateTypeNode",name:this.transformNode($.name),enum:this.transformNode($.enum)})}transformDropType($){return S({kind:"DropTypeNode",name:this.transformNode($.name),ifExists:$.ifExists})}transformExplain($){return S({kind:"ExplainNode",format:$.format,options:this.transformNode($.options)})}transformSchemableIdentifier($){return S({kind:"SchemableIdentifierNode",schema:this.transformNode($.schema),identifier:this.transformNode($.identifier)})}transformAggregateFunction($){return S({kind:"AggregateFunctionNode",aggregated:this.transformNodeList($.aggregated),distinct:$.distinct,orderBy:this.transformNode($.orderBy),filter:this.transformNode($.filter),func:$.func,over:this.transformNode($.over)})}transformOver($){return S({kind:"OverNode",orderBy:this.transformNode($.orderBy),partitionBy:this.transformNode($.partitionBy)})}transformPartitionBy($){return S({kind:"PartitionByNode",items:this.transformNodeList($.items)})}transformPartitionByItem($){return S({kind:"PartitionByItemNode",partitionBy:this.transformNode($.partitionBy)})}transformBinaryOperation($){return S({kind:"BinaryOperationNode",leftOperand:this.transformNode($.leftOperand),operator:this.transformNode($.operator),rightOperand:this.transformNode($.rightOperand)})}transformUnaryOperation($){return S({kind:"UnaryOperationNode",operator:this.transformNode($.operator),operand:this.transformNode($.operand)})}transformUsing($){return S({kind:"UsingNode",tables:this.transformNodeList($.tables)})}transformFunction($){return S({kind:"FunctionNode",func:$.func,arguments:this.transformNodeList($.arguments)})}transformCase($){return S({kind:"CaseNode",value:this.transformNode($.value),when:this.transformNodeList($.when),else:this.transformNode($.else),isStatement:$.isStatement})}transformWhen($){return S({kind:"WhenNode",condition:this.transformNode($.condition),result:this.transformNode($.result)})}transformJSONReference($){return S({kind:"JSONReferenceNode",reference:this.transformNode($.reference),traversal:this.transformNode($.traversal)})}transformJSONPath($){return S({kind:"JSONPathNode",inOperator:this.transformNode($.inOperator),pathLegs:this.transformNodeList($.pathLegs)})}transformJSONPathLeg($){return S({kind:"JSONPathLegNode",type:$.type,value:$.value})}transformJSONOperatorChain($){return S({kind:"JSONOperatorChainNode",operator:this.transformNode($.operator),values:this.transformNodeList($.values)})}transformTuple($){return S({kind:"TupleNode",values:this.transformNodeList($.values)})}transformMergeQuery($){return S({kind:"MergeQueryNode",into:this.transformNode($.into),using:this.transformNode($.using),whens:this.transformNodeList($.whens),with:this.transformNode($.with),top:this.transformNode($.top),endModifiers:this.transformNodeList($.endModifiers),output:this.transformNode($.output)})}transformMatched($){return S({kind:"MatchedNode",not:$.not,bySource:$.bySource})}transformAddIndex($){return S({kind:"AddIndexNode",name:this.transformNode($.name),columns:this.transformNodeList($.columns),unique:$.unique,using:this.transformNode($.using),ifNotExists:$.ifNotExists})}transformCast($){return S({kind:"CastNode",expression:this.transformNode($.expression),dataType:this.transformNode($.dataType)})}transformFetch($){return S({kind:"FetchNode",rowCount:this.transformNode($.rowCount),modifier:$.modifier})}transformTop($){return S({kind:"TopNode",expression:$.expression,modifiers:$.modifiers})}transformOutput($){return S({kind:"OutputNode",selections:this.transformNodeList($.selections)})}transformDataType($){return $}transformSelectAll($){return $}transformIdentifier($){return $}transformValue($){return $}transformPrimitiveValueList($){return $}transformOperator($){return $}transformDefaultInsertValue($){return $}}var I8=K(()=>{I()});var $p,fp,yU;var MS=K(()=>{vf();i0();I8();U4();_6();I();$p=H({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),fp={json_agg:!0,to_json:!0};yU=class yU extends _2{#$;#f=new Set;#W=new Set;constructor($){super();this.#$=$}transformNodeImpl($){if(!this.#Z($))return super.transformNodeImpl($);let f=this.#z($);for(let Z of f)this.#W.add(Z);let W=this.#X($);for(let Z of W)this.#f.add(Z);let J=super.transformNodeImpl($);for(let Z of W)this.#f.delete(Z);for(let Z of f)this.#W.delete(Z);return J}transformSchemableIdentifier($){let f=super.transformSchemableIdentifier($);if(f.schema||!this.#f.has($.identifier.name))return f;return{...f,schema:p.create(this.#$)}}transformReferences($){let f=super.transformReferences($);if(f.table.table.schema)return f;return{...f,table:t1.createWithSchema(this.#$,f.table.table.identifier.name)}}transformAggregateFunction($){return{...super.transformAggregateFunction({...$,aggregated:[]}),aggregated:this.#J($,"aggregated")}}transformFunction($){return{...super.transformFunction({...$,arguments:[]}),arguments:this.#J($,"arguments")}}#J($,f){return fp[$.func]?$[f].map((W)=>!t1.is(W)||W.table.schema?this.transformNode(W):{...W,table:this.transformIdentifier(W.table.identifier)}):this.transformNodeList($[f])}#Z($){return $.kind in $p}#X($){let f=new Set;if("name"in $&&$.name&&U$.is($.name))this.#G($.name,f);if("from"in $&&$.from)for(let W of $.from.froms)this.#w(W,f);if("into"in $&&$.into)this.#w($.into,f);if("table"in $&&$.table)this.#w($.table,f);if("joins"in $&&$.joins)for(let W of $.joins)this.#w(W.table,f);if("using"in $&&$.using)this.#w($.using,f);return f}#z($){let f=new Set;if("with"in $&&$.with)this.#Y($.with,f);return f}#w($,f){let W=t1.is($)?$:I1.is($)&&t1.is($.node)?$.node:null;if(W)this.#G(W.table,f)}#G($,f){let W=$.identifier.name;if(!this.#f.has(W)&&!this.#W.has(W))f.add(W)}#Y($,f){for(let W of $.expressions){let J=W.name.table.table.identifier.name;if(!this.#W.has(J))f.add(J)}}}});class i${#$;constructor($){this.#$=new yU($)}transformQuery($){return this.#$.transformNode($.node)}async transformResult($){return $.result}}var k6=K(()=>{MS()});var jU;var gU=K(()=>{I();jU=H({is($){return $.kind==="MatchedNode"},create($,f=!1){return H({kind:"MatchedNode",not:$,bySource:f})}})});function bU($,f,W){return A2.create(Y8([jU.create(!$.isMatched,$.bySource),...f&&f.length>0?[f.length===3&&W?C1(f[0],f[1],f[2]):h0(f)]:[]],"and",!1))}function O8($){if(q0($))return E0.create([$],[]);if(y0($))return $.toOperationNode();return $}var qS=K(()=>{gU();g$();M9();R8();I();u$()});class y6{#$;#f;#W;constructor(){this.#$=new Promise(($,f)=>{this.#W=f,this.#f=$})}get promise(){return this.#$}resolve=($)=>{if(this.#f)this.#f($)};reject=($)=>{if(this.#W)this.#W($)}}function S3($){if(VS.has($))return;VS.add($),console.log($)}var VS;var uU=K(()=>{VS=new Set});class XZ{#$;constructor($=Wp){this.#$=$}get plugins(){return this.#$}transformQuery($,f){for(let W of this.#$){let J=W.transformQuery({node:$,queryId:f});if(J.kind===$.kind)$=J;else throw new Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${$.kind}`,`but it returned a ${J.kind}`].join(" "))}return $}async executeQuery($,f){return await this.provideConnection(async(W)=>{let J=await W.executeQuery($),Z=await this.#f(J,f);return Jp(J,Z),Z})}async*stream($,f,W){let J=new y6,Z=new y6;this.provideConnection(async(z)=>{return J.resolve(z),await Z.promise}).catch((z)=>J.reject(z));let X=await J.promise;try{for await(let z of X.streamQuery($,f))yield await this.#f(z,W)}finally{Z.resolve()}}async#f($,f){for(let W of this.#$)$=await W.transformResult({result:$,queryId:f});return $}}function Jp($,f){let{numAffectedRows:W}=$;if(W===void 0&&$.numUpdatedOrDeletedRows===void 0||W!==void 0&&f.numAffectedRows!==void 0)return;S3("kysely:warning: outdated driver/plugin detected! QueryResult.numUpdatedOrDeletedRows is deprecated and will be removed in a future release.")}var Wp;var cU=K(()=>{I();uU();Wp=H([])});var j6,O9;var A8=K(()=>{cU();j6=class j6 extends XZ{get adapter(){throw new Error("this query cannot be compiled to SQL")}compileQuery(){throw new Error("this query cannot be compiled to SQL")}provideConnection(){throw new Error("this query cannot be executed")}withConnectionProvider(){throw new Error("this query cannot have a connection provider")}withPlugin($){return new j6([...this.plugins,$])}withPlugins($){return new j6([...this.plugins,...$])}withPluginAtFront($){return new j6([$,...this.plugins])}withoutPlugins(){return new j6([])}};O9=new j6});class F3{numChangedRows;constructor($){this.numChangedRows=$}}class A9{#$;constructor($){this.#$=H($)}modifyEnd($){return new A9({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}top($,f){return new A9({...this.#$,queryNode:T.cloneWithTop(this.#$.queryNode,uf($,f))})}using(...$){return new A$({...this.#$,queryNode:A1.cloneWithUsing(this.#$.queryNode,x1("Using",$))})}output($){return new A9({...this.#$,queryNode:T.cloneWithOutput(this.#$.queryNode,i1($))})}outputAll($){return new A9({...this.#$,queryNode:T.cloneWithOutput(this.#$.queryNode,a1($))})}}class A${#$;constructor($){this.#$=H($)}modifyEnd($){return new A$({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,$.toOperationNode())})}top($,f){return new A$({...this.#$,queryNode:T.cloneWithTop(this.#$.queryNode,uf($,f))})}whenMatched(){return this.#f([])}whenMatchedAnd(...$){return this.#f($)}whenMatchedAndRef($,f,W){return this.#f([$,f,W],!0)}#f($,f){return new zZ({...this.#$,queryNode:A1.cloneWithWhen(this.#$.queryNode,bU({isMatched:!0},$,f))})}whenNotMatched(){return this.#W([])}whenNotMatchedAnd(...$){return this.#W($)}whenNotMatchedAndRef($,f,W){return this.#W([$,f,W],!0)}whenNotMatchedBySource(){return this.#W([],!1,!0)}whenNotMatchedBySourceAnd(...$){return this.#W($,!1,!0)}whenNotMatchedBySourceAndRef($,f,W){return this.#W([$,f,W],!0,!0)}output($){return new A$({...this.#$,queryNode:T.cloneWithOutput(this.#$.queryNode,i1($))})}outputAll($){return new A$({...this.#$,queryNode:T.cloneWithOutput(this.#$.queryNode,a1($))})}#W($,f=!1,W=!1){let J={...this.#$,queryNode:A1.cloneWithWhen(this.#$.queryNode,bU({isMatched:!1,bySource:W},$,f))};return new(W?zZ:B3)(J)}$call($){return $(this)}$if($,f){if($)return f(this);return new A$({...this.#$})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){let $=this.compile(),f=await this.#$.executor.executeQuery($,this.#$.queryId);if($.query.output&&this.#$.executor.adapter.supportsOutput)return f.rows;return[new F3(f.numAffectedRows)]}async executeTakeFirst(){let[$]=await this.execute();return $}async executeTakeFirstOrThrow($=wf){let f=await this.executeTakeFirst();if(f===void 0)throw bf($)?new $(this.toOperationNode()):$(this.toOperationNode());return f}}class zZ{#$;constructor($){this.#$=H($)}thenDelete(){return new A$({...this.#$,queryNode:A1.cloneWithThen(this.#$.queryNode,O8("delete"))})}thenDoNothing(){return new A$({...this.#$,queryNode:A1.cloneWithThen(this.#$.queryNode,O8("do nothing"))})}thenUpdate($){return new A$({...this.#$,queryNode:A1.cloneWithThen(this.#$.queryNode,O8($(new N0({queryId:this.#$.queryId,executor:O9,queryNode:jf.createWithoutTable()}))))})}thenUpdateSet(...$){return this.thenUpdate((f)=>f.set(...$))}}class B3{#$;constructor($){this.#$=H($)}thenDoNothing(){return new A$({...this.#$,queryNode:A1.cloneWithThen(this.#$.queryNode,O8("do nothing"))})}thenInsertValues($){let[f,W]=Y3($);return new A$({...this.#$,queryNode:A1.cloneWithThen(this.#$.queryNode,O8(O1.cloneWith(O1.createWithoutInto(),{columns:f,values:W})))})}}var dU=K(()=>{C6();M8();I9();U8();IU();ZZ();qS();Q4();q8();A8();I();E6();O3();E(A9,"don't await MergeQueryBuilder instances directly. To execute the query you need to call `execute` when available.");E(A$,"don't await WheneableMergeQueryBuilder instances directly. To execute the query you need to call `execute`.");E(zZ,"don't await MatchedThenableMergeQueryBuilder instances directly. To execute the query you need to call `execute` when available.");E(B3,"don't await NotMatchedThenableMergeQueryBuilder instances directly. To execute the query you need to call `execute` when available.")});class cf{#$;constructor($){this.#$=H($)}selectFrom($){return g6({queryId:R0(),executor:this.#$.executor,queryNode:Y0.createFrom(x2($),this.#$.withNode)})}selectNoFrom($){return g6({queryId:R0(),executor:this.#$.executor,queryNode:Y0.cloneWithSelections(Y0.create(this.#$.withNode),i1($))})}insertInto($){return new j0({queryId:R0(),executor:this.#$.executor,queryNode:O1.create(Q0($),this.#$.withNode)})}replaceInto($){return new j0({queryId:R0(),executor:this.#$.executor,queryNode:O1.create(Q0($),this.#$.withNode,!0)})}deleteFrom($){return new _0({queryId:R0(),executor:this.#$.executor,queryNode:gf.create(x2($),this.#$.withNode)})}updateTable($){return new N0({queryId:R0(),executor:this.#$.executor,queryNode:jf.create(O4($),this.#$.withNode)})}mergeInto($){return new A9({queryId:R0(),executor:this.#$.executor,queryNode:A1.create(iU($),this.#$.withNode)})}with($,f){let W=vU($,f);return new cf({...this.#$,withNode:this.#$.withNode?Q8.cloneWithExpression(this.#$.withNode,W):Q8.create(W)})}withRecursive($,f){let W=vU($,f);return new cf({...this.#$,withNode:this.#$.withNode?Q8.cloneWithExpression(this.#$.withNode,W):Q8.create(W,{recursive:!0})})}withPlugin($){return new cf({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new cf({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new cf({...this.#$,executor:this.#$.executor.withPluginAtFront(new i$($))})}}var T3=K(()=>{wZ();EU();hU();O3();$Z();C6();q4();U8();o1();KS();mU();m6();k6();I();Q4();dU();M8()});function HS(){return new cf({executor:O9})}function QS($,f){return new V4({joinNode:U9.create($,O4(f))})}function IS(){return new H8({overNode:K8.create()})}var _3=K(()=>{iJ();X3();q4();KU();XS();wZ();T3();A8();m6();o1()});function x1($,f){if(f.length===3)return Xp($,f[0],f[1],f[2]);else if(f.length===2)return Zp($,f[0],f[1]);else throw new Error("not implemented")}function Zp($,f,W){return W(QS($,f)).toOperationNode()}function Xp($,f,W,J){return U9.createWithOn($,O4(f),C1(W,"=",J))}var ZZ=K(()=>{iJ();o1();u$();_3()});var rU;var lU=K(()=>{I();rU=H({is($){return $.kind==="OffsetNode"},create($){return H({kind:"OffsetNode",offset:$})}})});var pU;var nU=K(()=>{I();pU=H({is($){return $.kind==="GroupByItemNode"},create($){return H({kind:"GroupByItemNode",groupBy:$})}})});function OS($){return $=V0($)?$(d$()):$,Q9($).map(pU.create)}var AS=K(()=>{nU();I4();I();c1()});var GZ;var P3=K(()=>{I();GZ=H({is($){return $.kind==="SetOperationNode"},create($,f,W){return H({kind:"SetOperationNode",operator:$,expression:f,all:W})}})});function b6($,f,W){if(V0(f))f=f(C3());if(!P1(f))f=[f];return f.map((J)=>GZ.create($,O$(J),W))}var xS=K(()=>{I4();P3();I();kf()});class H0{#$;constructor($){this.#$=$}get expressionType(){return}as($){return new KZ(this,$)}or(...$){return new YZ(zf.create(this.#$,h0($)))}and(...$){return new LZ(R$.create(this.#$,h0($)))}$castTo(){return new H0(this.#$)}$notNull(){return new H0(this.#$)}toOperationNode(){return this.#$}}class KZ{#$;#f;constructor($,f){this.#$=$,this.#f=f}get expression(){return this.#$}get alias(){return this.#f}toOperationNode(){return I1.create(this.#$.toOperationNode(),y0(this.#f)?this.#f.toOperationNode():p.create(this.#f))}}class YZ{#$;constructor($){this.#$=$}get expressionType(){return}as($){return new KZ(this,$)}or(...$){return new YZ(zf.create(this.#$,h0($)))}$castTo(){return new YZ(this.#$)}toOperationNode(){return yf.create(this.#$)}}class LZ{#$;constructor($){this.#$=$}get expressionType(){return}as($){return new KZ(this,$)}and(...$){return new LZ(R$.create(this.#$,h0($)))}$castTo(){return new LZ(this.#$)}toOperationNode(){return yf.create(this.#$)}}var u6=K(()=>{vf();R4();i0();g$();N6();G8();u$()});var sU;var tU=K(()=>{I2();sU={is($){return $.kind==="FetchNode"},create($,f){return{kind:"FetchNode",rowCount:U1.create($),modifier:f}}}});function _S($,f){if(!Df($)&&!H4($))throw new Error(`Invalid fetch row count: ${$}`);if(!zp(f))throw new Error(`Invalid fetch modifier: ${f}`);return sU.create($,f)}function zp($){return $==="only"||$==="with ties"}var NS=K(()=>{tU();I()});class s{#$;constructor($){this.#$=H($)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...$){return new s({...this.#$,queryNode:T.cloneWithWhere(this.#$.queryNode,h0($))})}whereRef($,f,W){return new s({...this.#$,queryNode:T.cloneWithWhere(this.#$.queryNode,C1($,f,W))})}having(...$){return new s({...this.#$,queryNode:Y0.cloneWithHaving(this.#$.queryNode,h0($))})}havingRef($,f,W){return new s({...this.#$,queryNode:Y0.cloneWithHaving(this.#$.queryNode,C1($,f,W))})}select($){return new s({...this.#$,queryNode:Y0.cloneWithSelections(this.#$.queryNode,i1($))})}distinctOn($){return new s({...this.#$,queryNode:Y0.cloneWithDistinctOn(this.#$.queryNode,Q9($))})}modifyFront($){return new s({...this.#$,queryNode:Y0.cloneWithFrontModifier(this.#$.queryNode,mf.createWithExpression($.toOperationNode()))})}modifyEnd($){return new s({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,mf.createWithExpression($.toOperationNode()))})}distinct(){return new s({...this.#$,queryNode:Y0.cloneWithFrontModifier(this.#$.queryNode,mf.create("Distinct"))})}forUpdate($){return new s({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,mf.create("ForUpdate",$?bJ($).map(Q0):void 0))})}forShare($){return new s({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,mf.create("ForShare",$?bJ($).map(Q0):void 0))})}forKeyShare($){return new s({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,mf.create("ForKeyShare",$?bJ($).map(Q0):void 0))})}forNoKeyUpdate($){return new s({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,mf.create("ForNoKeyUpdate",$?bJ($).map(Q0):void 0))})}skipLocked(){return new s({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,mf.create("SkipLocked"))})}noWait(){return new s({...this.#$,queryNode:T.cloneWithEndModifier(this.#$.queryNode,mf.create("NoWait"))})}selectAll($){return new s({...this.#$,queryNode:Y0.cloneWithSelections(this.#$.queryNode,a1($))})}innerJoin(...$){return new s({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("InnerJoin",$))})}leftJoin(...$){return new s({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("LeftJoin",$))})}rightJoin(...$){return new s({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("RightJoin",$))})}fullJoin(...$){return new s({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("FullJoin",$))})}innerJoinLateral(...$){return new s({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("LateralInnerJoin",$))})}leftJoinLateral(...$){return new s({...this.#$,queryNode:T.cloneWithJoin(this.#$.queryNode,x1("LateralLeftJoin",$))})}orderBy(...$){return new s({...this.#$,queryNode:Y0.cloneWithOrderByItems(this.#$.queryNode,Q2($))})}groupBy($){return new s({...this.#$,queryNode:Y0.cloneWithGroupByItems(this.#$.queryNode,OS($))})}limit($){return new s({...this.#$,queryNode:Y0.cloneWithLimit(this.#$.queryNode,D6.create(T0($)))})}offset($){return new s({...this.#$,queryNode:Y0.cloneWithOffset(this.#$.queryNode,rU.create(T0($)))})}fetch($,f="only"){return new s({...this.#$,queryNode:Y0.cloneWithFetch(this.#$.queryNode,_S($,f))})}top($,f){return new s({...this.#$,queryNode:T.cloneWithTop(this.#$.queryNode,uf($,f))})}union($){return new s({...this.#$,queryNode:Y0.cloneWithSetOperations(this.#$.queryNode,b6("union",$,!1))})}unionAll($){return new s({...this.#$,queryNode:Y0.cloneWithSetOperations(this.#$.queryNode,b6("union",$,!0))})}intersect($){return new s({...this.#$,queryNode:Y0.cloneWithSetOperations(this.#$.queryNode,b6("intersect",$,!1))})}intersectAll($){return new s({...this.#$,queryNode:Y0.cloneWithSetOperations(this.#$.queryNode,b6("intersect",$,!0))})}except($){return new s({...this.#$,queryNode:Y0.cloneWithSetOperations(this.#$.queryNode,b6("except",$,!1))})}exceptAll($){return new s({...this.#$,queryNode:Y0.cloneWithSetOperations(this.#$.queryNode,b6("except",$,!0))})}as($){return new aU(this,$)}clearSelect(){return new s({...this.#$,queryNode:Y0.cloneWithoutSelections(this.#$.queryNode)})}clearWhere(){return new s({...this.#$,queryNode:T.cloneWithoutWhere(this.#$.queryNode)})}clearLimit(){return new s({...this.#$,queryNode:Y0.cloneWithoutLimit(this.#$.queryNode)})}clearOffset(){return new s({...this.#$,queryNode:Y0.cloneWithoutOffset(this.#$.queryNode)})}clearOrderBy(){return new s({...this.#$,queryNode:Y0.cloneWithoutOrderBy(this.#$.queryNode)})}clearGroupBy(){return new s({...this.#$,queryNode:Y0.cloneWithoutGroupBy(this.#$.queryNode)})}$call($){return $(this)}$if($,f){if($)return f(this);return new s({...this.#$})}$castTo(){return new s(this.#$)}$narrowType(){return new s(this.#$)}$assertType(){return new s(this.#$)}$asTuple(){return new H0(this.toOperationNode())}withPlugin($){return new s({...this.#$,executor:this.#$.executor.withPlugin($)})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.queryNode,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){let $=this.compile();return(await this.#$.executor.executeQuery($,this.#$.queryId)).rows}async executeTakeFirst(){let[$]=await this.execute();return $}async executeTakeFirstOrThrow($=wf){let f=await this.executeTakeFirst();if(f===void 0)throw bf($)?new $(this.toOperationNode()):$(this.toOperationNode());return f}async*stream($=100){let f=this.compile(),W=this.#$.executor.stream(f,$,this.#$.queryId);for await(let J of W)yield*J.rows}async explain($,f){return await new s({...this.#$,queryNode:T.cloneWithExplain(this.#$.queryNode,$,f)}).execute()}}function g6($){return new s($)}class aU{#$;#f;constructor($,f){this.#$=$,this.#f=f}get expression(){return this.#$}get alias(){return this.#f}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return I1.create(this.#$.toOperationNode(),p.create(this.#f))}}var wZ=K(()=>{vf();pH();ZZ();o1();Q4();c1();q4();I9();z8();JZ();lU();I();AS();E6();i0();xS();u$();u6();O2();NS();q8();E(s,"don't await SelectQueryBuilder instances directly. To execute the query you need to call `execute` or `executeTakeFirst`.");E(aU,"don't await AliasedSelectQueryBuilder instances directly. AliasedSelectQueryBuilder should never be executed directly since it's always a part of another query.")});var df;var E3=K(()=>{I();fZ();L8();df=H({is($){return $.kind==="AggregateFunctionNode"},create($,f=[]){return H({kind:"AggregateFunctionNode",func:$,aggregated:f})},cloneWithDistinct($){return H({...$,distinct:!0})},cloneWithOrderBy($,f){return H({...$,orderBy:$.orderBy?c$.cloneWithItems($.orderBy,f):c$.create(f)})},cloneWithFilter($,f){return H({...$,filter:$.filter?E1.cloneWithOperation($.filter,"And",f):E1.create(f)})},cloneWithOrFilter($,f){return H({...$,filter:$.filter?E1.cloneWithOperation($.filter,"Or",f):E1.create(f)})},cloneWithOver($,f){return H({...$,over:f})}})});var h3;var oU=K(()=>{I();h3=H({is($){return $.kind==="FunctionNode"},create($,f){return H({kind:"FunctionNode",func:$,arguments:f})}})});class x${#$;constructor($){this.#$=H($)}get expressionType(){return}as($){return new eU(this,$)}distinct(){return new x$({...this.#$,aggregateFunctionNode:df.cloneWithDistinct(this.#$.aggregateFunctionNode)})}orderBy($,f){return new x$({...this.#$,aggregateFunctionNode:df.cloneWithOrderBy(this.#$.aggregateFunctionNode,Q2([$,f]))})}filterWhere(...$){return new x$({...this.#$,aggregateFunctionNode:df.cloneWithFilter(this.#$.aggregateFunctionNode,h0($))})}filterWhereRef($,f,W){return new x$({...this.#$,aggregateFunctionNode:df.cloneWithFilter(this.#$.aggregateFunctionNode,C1($,f,W))})}over($){let f=IS();return new x$({...this.#$,aggregateFunctionNode:df.cloneWithOver(this.#$.aggregateFunctionNode,($?$(f):f).toOperationNode())})}$call($){return $(this)}$castTo(){return new x$(this.#$)}$notNull(){return new x$(this.#$)}toOperationNode(){return this.#$.aggregateFunctionNode}}class eU{#$;#f;constructor($,f){this.#$=$,this.#f=f}get expression(){return this.#$}get alias(){return this.#f}toOperationNode(){return I1.create(this.#$.toOperationNode(),p.create(this.#f))}}var $R=K(()=>{I();E3();vf();i0();_3();u$();z8();E(x$,"don't await AggregateFunctionBuilder instances. They are never executed directly and are always just a part of a query.")});function HZ(){let $=(W,J)=>{return new H0(h3.create(W,Q9(J??[])))},f=(W,J)=>{return new x$({aggregateFunctionNode:df.create(W,J?Q9(J):void 0)})};return Object.assign($,{agg:f,avg(W){return f("avg",[W])},coalesce(...W){return $("coalesce",W)},count(W){return f("count",[W])},countAll(W){return new x$({aggregateFunctionNode:df.create("count",a1(W))})},max(W){return f("max",[W])},min(W){return f("min",[W])},sum(W){return f("sum",[W])},any(W){return $("any",[W])},jsonAgg(W){return new x$({aggregateFunctionNode:df.create("json_agg",[q0(W)?Q0(W):W.toOperationNode()])})},toJson(W){return new H0(h3.create("to_json",[q0(W)?Q0(W):W.toOperationNode()]))}})}var D3=K(()=>{u6();E3();oU();c1();Q4();$R();I();o1()});var fR;var WR=K(()=>{I();fR=H({is($){return $.kind==="UnaryOperationNode"},create($,f){return H({kind:"UnaryOperationNode",operator:$,operand:f})}})});function SS($,f){return fR.create(I$.create($),d1(f))}var FS=K(()=>{S6();WR();c1()});var _$;var UZ=K(()=>{I();R8();_$=H({is($){return $.kind==="CaseNode"},create($){return H({kind:"CaseNode",value:$})},cloneWithWhen($,f){return H({...$,when:H($.when?[...$.when,f]:[f])})},cloneWithThen($,f){return H({...$,when:$.when?H([...$.when.slice(0,-1),A2.cloneWithResult($.when[$.when.length-1],f)]):void 0})},cloneWith($,f){return H({...$,...f})}})});class x8{#$;constructor($){this.#$=H($)}when(...$){return new v3({...this.#$,node:_$.cloneWithWhen(this.#$.node,A2.create(h0($)))})}}class v3{#$;constructor($){this.#$=H($)}then($){return new JR({...this.#$,node:_$.cloneWithThen(this.#$.node,W3($)?oJ($):T0($))})}}class JR{#$;constructor($){this.#$=H($)}when(...$){return new v3({...this.#$,node:_$.cloneWithWhen(this.#$.node,A2.create(h0($)))})}else($){return new ZR({...this.#$,node:_$.cloneWith(this.#$.node,{else:W3($)?oJ($):T0($)})})}end(){return new H0(_$.cloneWith(this.#$.node,{isStatement:!1}))}endCase(){return new H0(_$.cloneWith(this.#$.node,{isStatement:!0}))}}class ZR{#$;constructor($){this.#$=H($)}end(){return new H0(_$.cloneWith(this.#$.node,{isStatement:!1}))}endCase(){return new H0(_$.cloneWith(this.#$.node,{isStatement:!0}))}}var m3=K(()=>{u6();I();UZ();R8();u$();O2()});var k3;var XR=K(()=>{I();k3=H({is($){return $.kind==="JSONPathLegNode"},create($,f){return H({kind:"JSONPathLegNode",type:$,value:f})}})});class N8{#$;constructor($){this.#$=$}at($){return this.#f("ArrayLocation",$)}key($){return this.#f("Member",$)}#f($,f){if(B6.is(this.#$))return new _8(B6.cloneWithTraversal(this.#$,V9.is(this.#$.traversal)?V9.cloneWithLeg(this.#$.traversal,k3.create($,f)):nJ.cloneWithValue(this.#$.traversal,U1.createImmediate(f))));return new _8(V9.cloneWithLeg(this.#$,k3.create($,f)))}}class zR{#$;#f;constructor($,f){this.#$=$,this.#f=f}get expression(){return this.#$}get alias(){return this.#f}toOperationNode(){return I1.create(this.#$.toOperationNode(),y0(this.#f)?this.#f.toOperationNode():p.create(this.#f))}}var _8;var wR=K(()=>{vf();i0();$3();XR();sJ();ez();g$();I2();_8=class _8 extends N8{#$;constructor($){super($);this.#$=$}get expressionType(){return}as($){return new zR(this,$)}$castTo(){return new _8(this.#$)}$notNull(){return new _8(this.#$)}toOperationNode(){return this.#$}}});var y3;var GR=K(()=>{I();y3=H({is($){return $.kind==="TupleNode"},create($){return H({kind:"TupleNode",values:H($)})}})});function LR($){if(wp.includes($))return!0;if(Gp.some((f)=>f.test($)))return!0;return!1}var wp,Gp,YR;var KR=K(()=>{I();wp=["varchar","char","text","integer","int2","int4","int8","smallint","bigint","boolean","real","double precision","float4","float8","decimal","numeric","binary","bytea","date","datetime","time","timetz","timestamp","timestamptz","serial","bigserial","uuid","json","jsonb","blob","varbinary","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange"],Gp=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],YR=H({is($){return $.kind==="DataTypeNode"},create($){return H({kind:"DataTypeNode",dataType:$})}})});function rf($){if(y0($))return $.toOperationNode();if(LR($))return YR.create($);throw new Error(`invalid column data type ${JSON.stringify($)}`)}var RZ=K(()=>{KR();g$()});var HR;var UR=K(()=>{I();HR=H({is($){return $.kind==="CastNode"},create($,f){return H({kind:"CastNode",expression:$,dataType:f})}})});function C3($=O9){function f(Z,X,z){return new H0(J3(Z,X,z))}function W(Z,X){return new H0(SS(Z,X))}let J=Object.assign(f,{fn:void 0,eb:void 0,selectFrom(Z){return g6({queryId:R0(),executor:$,queryNode:Y0.createFrom(x2(Z))})},case(Z){return new x8({node:_$.create(H$(Z)?void 0:d1(Z))})},ref(Z,X){if(H$(X))return new H0(b$(Z));return new N8(oN(Z,X))},jsonPath(){return new N8(V9.create())},table(Z){return new H0(Q0(Z))},val(Z){return new H0(T0(Z))},refTuple(...Z){return new H0(y3.create(Z.map(d1)))},tuple(...Z){return new H0(y3.create(Z.map(T0)))},lit(Z){return new H0(oJ(Z))},unary:W,not(Z){return W("not",Z)},exists(Z){return W("exists",Z)},neg(Z){return W("-",Z)},between(Z,X,z){return new H0(R9.create(d1(Z),I$.create("between"),R$.create(T0(X),T0(z))))},betweenSymmetric(Z,X,z){return new H0(R9.create(d1(Z),I$.create("between symmetric"),R$.create(T0(X),T0(z))))},and(Z){if(P1(Z))return new H0(Y8(Z,"and"));return new H0(wU(Z,"and"))},or(Z){if(P1(Z))return new H0(Y8(Z,"or"));return new H0(wU(Z,"or"))},parens(...Z){let X=h0(Z);if(yf.is(X))return new H0(X);else return new H0(yf.create(X))},cast(Z,X){return new H0(HR.create(d1(Z),rf(X)))},withSchema(Z){return C3($.withPluginAtFront(new i$(Z)))}});return J.fn=HZ(),J.eb=J,J}function d$($){return C3()}var I4=K(()=>{wZ();q4();o1();k6();m6();D3();c1();u$();G8();u6();S6();FS();O2();A8();m3();UZ();I();wR();nz();R4();GR();sJ();RZ();UR()});function O$($){if(y0($))return $.toOperationNode();else if(V0($))return $(d$()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify($)}`)}function G3($){if(y0($))return $.toOperationNode();else if(V0($))return $(d$()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify($)}`)}function q9($){return iH($)||rH($)||V0($)}var kf=K(()=>{lH();g$();I4();I()});function x2($){if(P1($))return $.map((f)=>O4(f));else return[O4($)]}function O4($){if(q0($))return iU($);else return G3($)}function iU($){if($.includes(" as ")){let[W,J]=$.split(" as ").map(BS);return I1.create(Q0(W),p.create(J))}else return Q0($)}function Q0($){if($.includes(".")){let[W,J]=$.split(".").map(BS);return t1.createWithSchema(W,J)}else return t1.create($)}function BS($){return $.trim()}var o1=K(()=>{I();vf();_6();kf();i0()});var j3;var RR=K(()=>{I();j3=H({is($){return $.kind==="AddColumnNode"},create($){return H({kind:"AddColumnNode",column:$})}})});var D0;var MZ=K(()=>{I();u1();D0=H({is($){return $.kind==="ColumnDefinitionNode"},create($,f){return H({kind:"ColumnDefinitionNode",column:z0.create($),dataType:f})},cloneWithFrontModifier($,f){return H({...$,frontModifiers:$.frontModifiers?H([...$.frontModifiers,f]):[f]})},cloneWithEndModifier($,f){return H({...$,endModifiers:$.endModifiers?H([...$.endModifiers,f]):[f]})},cloneWith($,f){return H({...$,...f})}})});var g3;var MR=K(()=>{I();u1();g3=H({is($){return $.kind==="DropColumnNode"},create($){return H({kind:"DropColumnNode",column:z0.create($)})}})});var b3;var qR=K(()=>{I();u1();b3=H({is($){return $.kind==="RenameColumnNode"},create($,f){return H({kind:"RenameColumnNode",column:z0.create($),renameTo:z0.create(f)})}})});var c6;var qZ=K(()=>{I();i0();c6=H({is($){return $.kind==="CheckConstraintNode"},create($,f){return H({kind:"CheckConstraintNode",expression:$,name:f?p.create(f):void 0})}})});var VR,d6;var VZ=K(()=>{I();VR=["no action","restrict","cascade","set null","set default"],d6=H({is($){return $.kind==="ReferencesNode"},create($,f){return H({kind:"ReferencesNode",table:$,columns:H([...f])})},cloneWithOnDelete($,f){return H({...$,onDelete:f})},cloneWithOnUpdate($,f){return H({...$,onUpdate:f})}})});function u3($){return y0($)?$.toOperationNode():U1.createImmediate($)}var QR=K(()=>{g$();I2()});var S8;var IR=K(()=>{I();S8=H({is($){return $.kind==="GeneratedNode"},create($){return H({kind:"GeneratedNode",...$})},createWithExpression($){return H({kind:"GeneratedNode",always:!0,expression:$})},cloneWith($,f){return H({...$,...f})}})});var OR;var AR=K(()=>{I();OR=H({is($){return $.kind==="DefaultValueNode"},create($){return H({kind:"DefaultValueNode",defaultValue:$})}})});function F8($){if(VR.includes($))return $;throw new Error(`invalid OnModifyForeignAction ${$}`)}var xR=K(()=>{VZ()});class P0{#$;constructor($){this.#$=$}autoIncrement(){return new P0(D0.cloneWith(this.#$,{autoIncrement:!0}))}identity(){return new P0(D0.cloneWith(this.#$,{identity:!0}))}primaryKey(){return new P0(D0.cloneWith(this.#$,{primaryKey:!0}))}references($){let f=b$($);if(!f.table||F6.is(f.column))throw new Error(`invalid call references('${$}'). The reference must have format table.column or schema.table.column`);return new P0(D0.cloneWith(this.#$,{references:d6.create(f.table,[f.column])}))}onDelete($){if(!this.#$.references)throw new Error("on delete constraint can only be added for foreign keys");return new P0(D0.cloneWith(this.#$,{references:d6.cloneWithOnDelete(this.#$.references,F8($))}))}onUpdate($){if(!this.#$.references)throw new Error("on update constraint can only be added for foreign keys");return new P0(D0.cloneWith(this.#$,{references:d6.cloneWithOnUpdate(this.#$.references,F8($))}))}unique(){return new P0(D0.cloneWith(this.#$,{unique:!0}))}notNull(){return new P0(D0.cloneWith(this.#$,{notNull:!0}))}unsigned(){return new P0(D0.cloneWith(this.#$,{unsigned:!0}))}defaultTo($){return new P0(D0.cloneWith(this.#$,{defaultTo:OR.create(u3($))}))}check($){return new P0(D0.cloneWith(this.#$,{check:c6.create($.toOperationNode())}))}generatedAlwaysAs($){return new P0(D0.cloneWith(this.#$,{generated:S8.createWithExpression($.toOperationNode())}))}generatedAlwaysAsIdentity(){return new P0(D0.cloneWith(this.#$,{generated:S8.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new P0(D0.cloneWith(this.#$,{generated:S8.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#$.generated)throw new Error("stored() can only be called after generatedAlwaysAs");return new P0(D0.cloneWith(this.#$,{generated:S8.cloneWith(this.#$.generated,{stored:!0})}))}modifyFront($){return new P0(D0.cloneWithFrontModifier(this.#$,$.toOperationNode()))}nullsNotDistinct(){return new P0(D0.cloneWith(this.#$,{nullsNotDistinct:!0}))}ifNotExists(){return new P0(D0.cloneWith(this.#$,{ifNotExists:!0}))}modifyEnd($){return new P0(D0.cloneWithEndModifier(this.#$,$.toOperationNode()))}$call($){return $(this)}toOperationNode(){return this.#$}}var c3=K(()=>{qZ();VZ();rJ();c1();MZ();QR();IR();AR();xR();E(P0,"don't await ColumnDefinitionBuilder instances directly.")});var d3;var _R=K(()=>{I();d3=H({is($){return $.kind==="ModifyColumnNode"},create($){return H({kind:"ModifyColumnNode",column:$})}})});var A4;var QZ=K(()=>{I();i0();VZ();A4=H({is($){return $.kind==="ForeignKeyConstraintNode"},create($,f,W,J){return H({kind:"ForeignKeyConstraintNode",columns:$,references:d6.create(f,W),name:J?p.create(J):void 0})},cloneWith($,f){return H({...$,...f})}})});class x9{#$;constructor($){this.#$=$}onDelete($){return new x9(A4.cloneWith(this.#$,{onDelete:F8($)}))}onUpdate($){return new x9(A4.cloneWith(this.#$,{onUpdate:F8($)}))}$call($){return $(this)}toOperationNode(){return this.#$}}var i3=K(()=>{QZ();xR();E(x9,"don't await ForeignKeyConstraintBuilder instances directly.")});var i6;var r3=K(()=>{I();i6=H({is($){return $.kind==="AddConstraintNode"},create($){return H({kind:"AddConstraintNode",constraint:$})}})});var r6;var IZ=K(()=>{I();u1();i0();r6=H({is($){return $.kind==="UniqueConstraintNode"},create($,f,W){return H({kind:"UniqueConstraintNode",columns:H($.map(z0.create)),name:f?p.create(f):void 0,nullsNotDistinct:W})},cloneWith($,f){return H({...$,...f})}})});var l6;var l3=K(()=>{I();i0();l6=H({is($){return $.kind==="DropConstraintNode"},create($){return H({kind:"DropConstraintNode",constraintName:p.create($)})},cloneWith($,f){return H({...$,...f})}})});var p6;var NR=K(()=>{I();u1();p6=H({is($){return $.kind==="AlterColumnNode"},create($,f,W){return H({kind:"AlterColumnNode",column:z0.create($),[f]:W})}})});class B8{#$;constructor($){this.#$=$}setDataType($){return new x4(p6.create(this.#$,"dataType",rf($)))}setDefault($){return new x4(p6.create(this.#$,"setDefault",u3($)))}dropDefault(){return new x4(p6.create(this.#$,"dropDefault",!0))}setNotNull(){return new x4(p6.create(this.#$,"setNotNull",!0))}dropNotNull(){return new x4(p6.create(this.#$,"dropNotNull",!0))}$call($){return $(this)}}class x4{#$;constructor($){this.#$=$}toOperationNode(){return this.#$}}var SR=K(()=>{NR();RZ();QR();E(B8,"don't await AlterColumnBuilder instances");E(x4,"don't await AlteredColumnBuilder instances")});class _9{#$;constructor($){this.#$=H($)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var TS=K(()=>{I();E(_9,"don't await AlterTableExecutor instances directly. To execute the query you need to call `execute`")});class T8{#$;constructor($){this.#$=H($)}onDelete($){return new T8({...this.#$,constraintBuilder:this.#$.constraintBuilder.onDelete($)})}onUpdate($){return new T8({...this.#$,constraintBuilder:this.#$.constraintBuilder.onUpdate($)})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(U0.cloneWithTableProps(this.#$.node,{addConstraint:i6.create(this.#$.constraintBuilder.toOperationNode())}),this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var PS=K(()=>{r3();x6();I();E(T8,"don't await AlterTableAddForeignKeyConstraintBuilder instances directly. To execute the query you need to call `execute`")});class n6{#$;constructor($){this.#$=H($)}ifExists(){return new n6({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{dropConstraint:l6.cloneWith(this.#$.node.dropConstraint,{ifExists:!0})})})}cascade(){return new n6({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{dropConstraint:l6.cloneWith(this.#$.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new n6({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{dropConstraint:l6.cloneWith(this.#$.node.dropConstraint,{modifier:"restrict"})})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var CS=K(()=>{x6();l3();I();E(n6,"don't await AlterTableDropConstraintBuilder instances directly. To execute the query you need to call `execute`")});var OZ;var p3=K(()=>{I();u1();i0();OZ=H({is($){return $.kind==="PrimaryKeyConstraintNode"},create($,f){return H({kind:"PrimaryKeyConstraintNode",columns:H($.map(z0.create)),name:f?p.create(f):void 0})}})});var N9;var n3=K(()=>{I();i0();N9=H({is($){return $.kind==="AddIndexNode"},create($){return H({kind:"AddIndexNode",name:p.create($)})},cloneWith($,f){return H({...$,...f})},cloneWithColumns($,f){return H({...$,columns:[...$.columns||[],...f]})}})});class S9{#$;constructor($){this.#$=H($)}unique(){return new S9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{addIndex:N9.cloneWith(this.#$.node.addIndex,{unique:!0})})})}column($){return new S9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{addIndex:N9.cloneWithColumns(this.#$.node.addIndex,[w8($)])})})}columns($){return new S9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{addIndex:N9.cloneWithColumns(this.#$.node.addIndex,$.map(w8))})})}expression($){return new S9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{addIndex:N9.cloneWithColumns(this.#$.node.addIndex,[$.toOperationNode()])})})}using($){return new S9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{addIndex:N9.cloneWith(this.#$.node.addIndex,{using:E0.createWithSql($)})})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var ES=K(()=>{n3();x6();M9();c1();I();E(S9,"don't await AlterTableAddIndexBuilder instances directly. To execute the query you need to call `execute`")});class s6{#$;constructor($){this.#$=$}toOperationNode(){return this.#$}nullsNotDistinct(){return new s6(r6.cloneWith(this.#$,{nullsNotDistinct:!0}))}}var FR=K(()=>{IZ();E(s6,"don't await UniqueConstraintNodeBuilder instances directly.")});class AZ{#$;constructor($){this.#$=H($)}renameTo($){return new _9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{renameTo:Q0($)})})}setSchema($){return new _9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{setSchema:p.create($)})})}alterColumn($,f){let W=f(new B8($));return new r$({...this.#$,node:U0.cloneWithColumnAlteration(this.#$.node,W.toOperationNode())})}dropColumn($){return new r$({...this.#$,node:U0.cloneWithColumnAlteration(this.#$.node,g3.create($))})}renameColumn($,f){return new r$({...this.#$,node:U0.cloneWithColumnAlteration(this.#$.node,b3.create($,f))})}addColumn($,f,W=q2){let J=W(new P0(D0.create($,rf(f))));return new r$({...this.#$,node:U0.cloneWithColumnAlteration(this.#$.node,j3.create(J.toOperationNode()))})}modifyColumn($,f,W=q2){let J=W(new P0(D0.create($,rf(f))));return new r$({...this.#$,node:U0.cloneWithColumnAlteration(this.#$.node,d3.create(J.toOperationNode()))})}addUniqueConstraint($,f,W=q2){let J=W(new s6(r6.create(f,$)));return new _9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{addConstraint:i6.create(J.toOperationNode())})})}addCheckConstraint($,f){return new _9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{addConstraint:i6.create(c6.create(f.toOperationNode(),$))})})}addForeignKeyConstraint($,f,W,J){return new T8({...this.#$,constraintBuilder:new x9(A4.create(f.map(z0.create),Q0(W),J.map(z0.create),$))})}addPrimaryKeyConstraint($,f){return new _9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{addConstraint:i6.create(OZ.create(f,$))})})}dropConstraint($){return new n6({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{dropConstraint:l6.create($)})})}addIndex($){return new S9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{addIndex:N9.create($)})})}dropIndex($){return new _9({...this.#$,node:U0.cloneWithTableProps(this.#$.node,{dropIndex:H9.create($)})})}$call($){return $(this)}}class r${#$;constructor($){this.#$=H($)}alterColumn($,f){let W=f(new B8($));return new r$({...this.#$,node:U0.cloneWithColumnAlteration(this.#$.node,W.toOperationNode())})}dropColumn($){return new r$({...this.#$,node:U0.cloneWithColumnAlteration(this.#$.node,g3.create($))})}renameColumn($,f){return new r$({...this.#$,node:U0.cloneWithColumnAlteration(this.#$.node,b3.create($,f))})}addColumn($,f,W=q2){let J=W(new P0(D0.create($,rf(f))));return new r$({...this.#$,node:U0.cloneWithColumnAlteration(this.#$.node,j3.create(J.toOperationNode()))})}modifyColumn($,f,W=q2){let J=W(new P0(D0.create($,rf(f))));return new r$({...this.#$,node:U0.cloneWithColumnAlteration(this.#$.node,d3.create(J.toOperationNode()))})}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var BR=K(()=>{RR();x6();MZ();MR();i0();qR();I();c3();_R();RZ();i3();r3();IZ();qZ();QZ();u1();o1();l3();SR();TS();PS();CS();p3();cJ();n3();ES();FR();E(AZ,"don't await AlterTableBuilder instances");E(r$,"don't await AlterTableColumnAlteringBuilder instances directly. To execute the query you need to call `execute`")});var xZ;var TR=K(()=>{I8();xZ=class xZ extends _2{transformValue($){return{...super.transformValue($),immediate:!0}}}});class N${#$;constructor($){this.#$=H($)}ifNotExists(){return new N$({...this.#$,node:Xf.cloneWith(this.#$.node,{ifNotExists:!0})})}unique(){return new N$({...this.#$,node:Xf.cloneWith(this.#$.node,{unique:!0})})}nullsNotDistinct(){return new N$({...this.#$,node:Xf.cloneWith(this.#$.node,{nullsNotDistinct:!0})})}on($){return new N$({...this.#$,node:Xf.cloneWith(this.#$.node,{table:Q0($)})})}column($){return new N$({...this.#$,node:Xf.cloneWithColumns(this.#$.node,[w8($)])})}columns($){return new N$({...this.#$,node:Xf.cloneWithColumns(this.#$.node,$.map(w8))})}expression($){return new N$({...this.#$,node:Xf.cloneWithColumns(this.#$.node,[$.toOperationNode()])})}using($){return new N$({...this.#$,node:Xf.cloneWith(this.#$.node,{using:E0.createWithSql($)})})}where(...$){let f=new xZ;return new N$({...this.#$,node:T.cloneWithWhere(this.#$.node,f.transformNode(h0($)))})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var PR=K(()=>{iz();M9();c1();o1();I();u$();I9();TR();E(N$,"don't await CreateIndexBuilder instances directly. To execute the query you need to call `execute`")});class P8{#$;constructor($){this.#$=H($)}ifNotExists(){return new P8({...this.#$,node:uJ.cloneWith(this.#$.node,{ifNotExists:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var CR=K(()=>{rz();I();E(P8,"don't await CreateSchemaBuilder instances directly. To execute the query you need to call `execute`")});function hS($){if(dH.includes($))return $;throw new Error(`invalid OnCommitAction ${$}`)}var DS=K(()=>{J8()});class $${#$;constructor($){this.#$=H($)}temporary(){return new $$({...this.#$,node:b1.cloneWith(this.#$.node,{temporary:!0})})}onCommit($){return new $$({...this.#$,node:b1.cloneWith(this.#$.node,{onCommit:hS($)})})}ifNotExists(){return new $$({...this.#$,node:b1.cloneWith(this.#$.node,{ifNotExists:!0})})}addColumn($,f,W=q2){let J=W(new P0(D0.create($,rf(f))));return new $$({...this.#$,node:b1.cloneWithColumn(this.#$.node,J.toOperationNode())})}addPrimaryKeyConstraint($,f){return new $$({...this.#$,node:b1.cloneWithConstraint(this.#$.node,OZ.create(f,$))})}addUniqueConstraint($,f,W=q2){let J=W(new s6(r6.create(f,$)));return new $$({...this.#$,node:b1.cloneWithConstraint(this.#$.node,J.toOperationNode())})}addCheckConstraint($,f){return new $$({...this.#$,node:b1.cloneWithConstraint(this.#$.node,c6.create(f.toOperationNode(),$))})}addForeignKeyConstraint($,f,W,J,Z=q2){let X=Z(new x9(A4.create(f.map(z0.create),Q0(W),J.map(z0.create),$)));return new $$({...this.#$,node:b1.cloneWithConstraint(this.#$.node,X.toOperationNode())})}modifyFront($){return new $$({...this.#$,node:b1.cloneWithFrontModifier(this.#$.node,$.toOperationNode())})}modifyEnd($){return new $$({...this.#$,node:b1.cloneWithEndModifier(this.#$.node,$.toOperationNode())})}as($){return new $$({...this.#$,node:b1.cloneWith(this.#$.node,{selectQuery:O$($)})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var ER=K(()=>{MZ();J8();c3();I();QZ();u1();i3();RZ();p3();IZ();qZ();o1();DS();FR();kf();E($$,"don't await CreateTableBuilder instances directly. To execute the query you need to call `execute`")});class _4{#$;constructor($){this.#$=H($)}on($){return new _4({...this.#$,node:H9.cloneWith(this.#$.node,{table:Q0($)})})}ifExists(){return new _4({...this.#$,node:H9.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new _4({...this.#$,node:H9.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var hR=K(()=>{cJ();o1();I();E(_4,"don't await DropIndexBuilder instances directly. To execute the query you need to call `execute`")});class t6{#$;constructor($){this.#$=H($)}ifExists(){return new t6({...this.#$,node:Z8.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new t6({...this.#$,node:Z8.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var DR=K(()=>{lz();I();E(t6,"don't await DropSchemaBuilder instances directly. To execute the query you need to call `execute`")});class a6{#$;constructor($){this.#$=H($)}ifExists(){return new a6({...this.#$,node:X8.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new a6({...this.#$,node:X8.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var vR=K(()=>{pz();I();E(a6,"don't await DropTableBuilder instances directly. To execute the query you need to call `execute`")});var Yf;var _Z=K(()=>{I();U4();Yf=H({is($){return $.kind==="CreateViewNode"},create($){return H({kind:"CreateViewNode",name:U$.create($)})},cloneWith($,f){return H({...$,...f})}})});class mR{#$=new xZ;transformQuery($){return this.#$.transformNode($.node)}transformResult($){return Promise.resolve($.result)}}var vS=K(()=>{TR()});class lf{#$;constructor($){this.#$=H($)}temporary(){return new lf({...this.#$,node:Yf.cloneWith(this.#$.node,{temporary:!0})})}materialized(){return new lf({...this.#$,node:Yf.cloneWith(this.#$.node,{materialized:!0})})}ifNotExists(){return new lf({...this.#$,node:Yf.cloneWith(this.#$.node,{ifNotExists:!0})})}orReplace(){return new lf({...this.#$,node:Yf.cloneWith(this.#$.node,{orReplace:!0})})}columns($){return new lf({...this.#$,node:Yf.cloneWith(this.#$.node,{columns:$.map(ZU)})})}as($){let f=$.withPlugin(new mR).toOperationNode();return new lf({...this.#$,node:Yf.cloneWith(this.#$.node,{as:f})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var kR=K(()=>{I();_Z();c1();vS();E(lf,"don't await CreateViewBuilder instances directly. To execute the query you need to call `execute`")});var o6;var s3=K(()=>{I();U4();o6=H({is($){return $.kind==="DropViewNode"},create($){return H({kind:"DropViewNode",name:U$.create($)})},cloneWith($,f){return H({...$,...f})}})});class N4{#$;constructor($){this.#$=H($)}materialized(){return new N4({...this.#$,node:o6.cloneWith(this.#$.node,{materialized:!0})})}ifExists(){return new N4({...this.#$,node:o6.cloneWith(this.#$.node,{ifExists:!0})})}cascade(){return new N4({...this.#$,node:o6.cloneWith(this.#$.node,{cascade:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var yR=K(()=>{I();s3();E(N4,"don't await DropViewBuilder instances directly. To execute the query you need to call `execute`")});var NZ;var t3=K(()=>{I();aJ();I2();NZ=H({is($){return $.kind==="CreateTypeNode"},create($){return H({kind:"CreateTypeNode",name:$})},cloneWithEnum($,f){return H({...$,enum:T6.create(f.map((W)=>U1.createImmediate(W)))})}})});class C8{#$;constructor($){this.#$=H($)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}asEnum($){return new C8({...this.#$,node:NZ.cloneWithEnum(this.#$.node,$)})}$call($){return $(this)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var jR=K(()=>{I();t3();E(C8,"don't await CreateTypeBuilder instances directly. To execute the query you need to call `execute`")});var SZ;var a3=K(()=>{I();SZ=H({is($){return $.kind==="DropTypeNode"},create($){return H({kind:"DropTypeNode",name:$})},cloneWith($,f){return H({...$,...f})}})});class E8{#$;constructor($){this.#$=H($)}ifExists(){return new E8({...this.#$,node:SZ.cloneWith(this.#$.node,{ifExists:!0})})}$call($){return $(this)}toOperationNode(){return this.#$.executor.transformQuery(this.#$.node,this.#$.queryId)}compile(){return this.#$.executor.compileQuery(this.toOperationNode(),this.#$.queryId)}async execute(){await this.#$.executor.executeQuery(this.compile(),this.#$.queryId)}}var gR=K(()=>{a3();I();E(E8,"don't await DropTypeBuilder instances directly. To execute the query you need to call `execute`")});function bR($){if($.includes(".")){let W=$.split(".").map(Yp);if(W.length===2)return U$.createWithSchema(W[0],W[1]);else throw new Error(`invalid schemable identifier ${$}`)}else return U$.create($)}function Yp($){return $.trim()}var mS=K(()=>{U4()});class e6{#$;constructor($){this.#$=$}createTable($){return new $$({queryId:R0(),executor:this.#$,node:b1.create(Q0($))})}dropTable($){return new a6({queryId:R0(),executor:this.#$,node:X8.create(Q0($))})}createIndex($){return new N$({queryId:R0(),executor:this.#$,node:Xf.create($)})}dropIndex($){return new _4({queryId:R0(),executor:this.#$,node:H9.create($)})}createSchema($){return new P8({queryId:R0(),executor:this.#$,node:uJ.create($)})}dropSchema($){return new t6({queryId:R0(),executor:this.#$,node:Z8.create($)})}alterTable($){return new AZ({queryId:R0(),executor:this.#$,node:U0.create(Q0($))})}createView($){return new lf({queryId:R0(),executor:this.#$,node:Yf.create($)})}dropView($){return new N4({queryId:R0(),executor:this.#$,node:o6.create($)})}createType($){return new C8({queryId:R0(),executor:this.#$,node:NZ.create(bR($))})}dropType($){return new E8({queryId:R0(),executor:this.#$,node:SZ.create(bR($))})}withPlugin($){return new e6(this.#$.withPlugin($))}withoutPlugins(){return new e6(this.#$.withoutPlugins())}withSchema($){return new e6(this.#$.withPluginAtFront(new i$($)))}}var uR=K(()=>{x6();iz();rz();J8();cJ();lz();pz();o1();BR();PR();CR();ER();hR();DR();vR();m6();k6();kR();_Z();yR();s3();jR();gR();t3();a3();mS()});class o3{ref($){return new eH($)}}var cR=K(()=>{oz()});class e3{#$;constructor($){this.#$=$}async provideConnection($){let f=await this.#$.acquireConnection();try{return await $(f)}finally{await this.#$.releaseConnection(f)}}}var F9;var dR=K(()=>{cU();F9=class F9 extends XZ{#$;#f;#W;constructor($,f,W,J=[]){super(J);this.#$=$,this.#f=f,this.#W=W}get adapter(){return this.#f}compileQuery($){return this.#$.compileQuery($)}provideConnection($){return this.#W.provideConnection($)}withPlugins($){return new F9(this.#$,this.#f,this.#W,[...this.plugins,...$])}withPlugin($){return new F9(this.#$,this.#f,this.#W,[...this.plugins,$])}withPluginAtFront($){return new F9(this.#$,this.#f,this.#W,[$,...this.plugins])}withConnectionProvider($){return new F9(this.#$,this.#f,$,[...this.plugins])}withoutPlugins(){return new F9(this.#$,this.#f,this.#W,[])}}});function iR(){if(typeof performance!=="undefined"&&V0(performance.now))return performance.now();else return Date.now()}var kS=K(()=>{I()});class rR{#$;#f;#W;#J;#Z;#X=new WeakSet;constructor($,f){this.#J=!1,this.#$=$,this.#f=f}async init(){if(this.#Z)throw new Error("driver has already been destroyed");if(!this.#W)this.#W=this.#$.init().then(()=>{this.#J=!0}).catch(($)=>{return this.#W=void 0,Promise.reject($)});await this.#W}async acquireConnection(){if(this.#Z)throw new Error("driver has already been destroyed");if(!this.#J)await this.init();let $=await this.#$.acquireConnection();if(!this.#X.has($)){if(this.#z())this.#w($);this.#X.add($)}return $}async releaseConnection($){await this.#$.releaseConnection($)}beginTransaction($,f){return this.#$.beginTransaction($,f)}commitTransaction($){return this.#$.commitTransaction($)}rollbackTransaction($){return this.#$.rollbackTransaction($)}async destroy(){if(!this.#W)return;if(await this.#W,!this.#Z)this.#Z=this.#$.destroy().catch(($)=>{return this.#Z=void 0,Promise.reject($)});await this.#Z}#z(){return this.#f.isLevelEnabled("query")||this.#f.isLevelEnabled("error")}#w($){let f=$.executeQuery;$.executeQuery=async(W)=>{let J,Z=iR();try{return await f.call($,W)}catch(X){throw J=X,await this.#G(X,W,Z),X}finally{if(!J)await this.#Y(W,Z)}}}async#G($,f,W){await this.#f.error(()=>({level:"error",error:$,query:f,queryDurationMillis:this.#K(W)}))}async#Y($,f){await this.#f.query(()=>({level:"query",query:$,queryDurationMillis:this.#K(f)}))}#K($){return iR()-$}}var yS=K(()=>{kS()});class FZ{#$;#f;constructor($){this.#$=$}async provideConnection($){while(this.#f)await this.#f.catch(Lp);return this.#f=this.#W($).finally(()=>{this.#f=void 0}),this.#f}async#W($){return await $(this.#$)}}var Lp=()=>{};var lR;var pR=K(()=>{lR=["read uncommitted","read committed","repeatable read","serializable","snapshot"]});class $w{#$;#f;constructor($){if(V0($))this.#f=$,this.#$=H({query:!0,error:!0});else this.#f=Hp,this.#$=H({query:$.includes("query"),error:$.includes("error")})}isLevelEnabled($){return this.#$[$]}async query($){if(this.#$.query)await this.#f($())}async error($){if(this.#$.error)await this.#f($())}}function Hp($){if($.level==="query")console.log(`kysely:query: ${$.query.sql}`),console.log(`kysely:query: duration: ${$.queryDurationMillis.toFixed(1)}ms`);else if($.level==="error")if($.error instanceof Error)console.error(`kysely:error: ${$.error.stack??$.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:$.error,query:$.query.sql,queryDurationMillis:$.queryDurationMillis})}`)}var Kp;var nR=K(()=>{I();Kp=H(["query","error"])});function sR($){return t0($)&&V0($.compile)}var tR=K(()=>{I()});function jS($){return t0($)&&t0($.config)&&t0($.driver)&&t0($.executor)&&t0($.dialect)}class fw{#$;constructor($){this.#$=H($)}async execute($){return this.#$.executor.provideConnection(async(f)=>{let W=this.#$.executor.withConnectionProvider(new FZ(f)),J=new N2({...this.#$,executor:W});return await $(J)})}}class BZ{#$;constructor($){this.#$=H($)}setIsolationLevel($){return new BZ({...this.#$,isolationLevel:$})}async execute($){let{isolationLevel:f,...W}=this.#$,J={isolationLevel:f};return Up(J),this.#$.executor.provideConnection(async(Z)=>{let X=this.#$.executor.withConnectionProvider(new FZ(Z)),z=new $5({...W,executor:X});try{await this.#$.driver.beginTransaction(Z,J);let w=await $(z);return await this.#$.driver.commitTransaction(Z),w}catch(w){throw await this.#$.driver.rollbackTransaction(Z),w}})}}function Up($){if($.isolationLevel&&!lR.includes($.isolationLevel))throw new Error(`invalid transaction isolation level ${$.isolationLevel}`)}var N2,$5;var gS=K(()=>{uR();cR();T3();dR();I();yS();pR();D3();nR();m6();tR();m3();UZ();kf();k6();N2=class N2 extends cf{#$;constructor($){let f,W;if(jS($))f={executor:$.executor},W={...$};else{let J=$.dialect,Z=J.createDriver(),X=J.createQueryCompiler(),z=J.createAdapter(),w=new $w($.log??[]),G=new rR(Z,w),Y=new e3(G),L=new F9(X,z,Y,$.plugins??[]);f={executor:L},W={config:$,executor:L,dialect:J,driver:G}}super(f);this.#$=H(W)}get schema(){return new e6(this.#$.executor)}get dynamic(){return new o3}get introspection(){return this.#$.dialect.createIntrospector(this.withoutPlugins())}case($){return new x8({node:_$.create(H$($)?void 0:O$($))})}get fn(){return HZ()}transaction(){return new BZ({...this.#$})}connection(){return new fw({...this.#$})}withPlugin($){return new N2({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new N2({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new N2({...this.#$,executor:this.#$.executor.withPluginAtFront(new i$($))})}withTables(){return new N2({...this.#$})}async destroy(){await this.#$.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#$.executor}executeQuery($,f=R0()){let W=sR($)?$.compile():$;return this.getExecutor().executeQuery(W,f)}};$5=class $5 extends N2{#$;constructor($){super($);this.#$=$}get isTransaction(){return!0}transaction(){throw new Error("calling the transaction method for a Transaction is not supported")}connection(){throw new Error("calling the connection method for a Transaction is not supported")}async destroy(){throw new Error("calling the destroy method for a Transaction is not supported")}withPlugin($){return new $5({...this.#$,executor:this.#$.executor.withPlugin($)})}withoutPlugins(){return new $5({...this.#$,executor:this.#$.executor.withoutPlugins()})}withSchema($){return new $5({...this.#$,executor:this.#$.executor.withPluginAtFront(new i$($))})}withTables(){return new $5({...this.#$})}};E(fw,"don't await ConnectionBuilder instances directly. To execute the query you need to call the `execute` method");E(BZ,"don't await TransactionBuilder instances directly. To execute the transaction you need to call the `execute` method")});var bS=()=>{};var uS=()=>{};var cS=()=>{};var dS=()=>{};class h8{#$;constructor($){this.#$=H($)}get expressionType(){return}get isRawBuilder(){return!0}as($){return new aR(this,$)}$castTo(){return new h8({...this.#$})}$notNull(){return new h8(this.#$)}withPlugin($){return new h8({...this.#$,plugins:this.#$.plugins!==void 0?H([...this.#$.plugins,$]):H([$])})}toOperationNode(){return this.#W(this.#f())}compile($){return this.#J(this.#f($))}async execute($){let f=this.#f($);return f.executeQuery(this.#J(f),this.#$.queryId)}#f($){let f=$!==void 0?$.getExecutor():O9;return this.#$.plugins!==void 0?f.withPlugins(this.#$.plugins):f}#W($){return $.transformQuery(this.#$.rawNode,this.#$.queryId)}#J($){return $.compileQuery(this.#W($),this.#$.queryId)}}function S2($){return new h8($)}class aR{#$;#f;constructor($,f){this.#$=$,this.#f=f}get expression(){return this.#$}get alias(){return this.#f}get rawBuilder(){return this.#$}toOperationNode(){return I1.create(this.#$.toOperationNode(),y0(this.#f)?this.#f.toOperationNode():p.create(this.#f))}}var oR=K(()=>{vf();I();A8();i0();g$();E(h8,"don't await RawBuilder instances directly. To execute the query you need to call `execute`");E(aR,"don't await AliasedRawBuilder instances directly. AliasedRawBuilder should never be executed directly since it's always a part of another query.")});function iS($){if(y0($))return $.toOperationNode();return T0($)}var J0;var B9=K(()=>{i0();g$();M9();I2();c1();o1();O2();m6();oR();J0=Object.assign(($,...f)=>{return S2({queryId:R0(),rawNode:E0.create($,f?.map(iS)??[])})},{ref($){return S2({queryId:R0(),rawNode:E0.createWithChild(b$($))})},val($){return S2({queryId:R0(),rawNode:E0.createWithChild(T0($))})},value($){return this.val($)},table($){return S2({queryId:R0(),rawNode:E0.createWithChild(Q0($))})},id(...$){let f=new Array($.length+1).fill(".");return f[0]="",f[f.length-1]="",S2({queryId:R0(),rawNode:E0.create(f,$.map(p.create))})},lit($){return S2({queryId:R0(),rawNode:E0.createWithChild(U1.createImmediate($))})},literal($){return this.lit($)},raw($){return S2({queryId:R0(),rawNode:E0.createWithSql($)})},join($,f=J0`, `){let W=new Array(2*$.length-1),J=f.toOperationNode();for(let Z=0;Z<$.length;++Z)if(W[2*Z]=iS($[Z]),Z!==$.length-1)W[2*Z+1]=J;return S2({queryId:R0(),rawNode:E0.createWithChildren(W)})}})});var rS=()=>{};var lS=()=>{};class Ww{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#$=H({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this)});visitNode=($)=>{this.nodeStack.push($),this.#$[$.kind]($),this.nodeStack.pop()}}var eR=K(()=>{I()});var F2,Rp,pS,Mp;var f5=K(()=>{J8();C6();eR();S6();G8();I9();I();_Z();P3();M8();F2=class F2 extends Ww{#$="";#f=[];get numParameters(){return this.#f.length}compileQuery($){return this.#$="",this.#f=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode($),H({query:$,sql:this.getSql(),parameters:[...this.#f]})}getSql(){return this.#$}visitSelectQuery($){let f=this.parentNode!==void 0&&!yf.is(this.parentNode)&&!O1.is(this.parentNode)&&!b1.is(this.parentNode)&&!Yf.is(this.parentNode)&&!GZ.is(this.parentNode);if(this.parentNode===void 0&&$.explain)this.visitNode($.explain),this.append(" ");if(f)this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append("select"),$.distinctOn)this.append(" "),this.compileDistinctOn($.distinctOn);if($.frontModifiers?.length)this.append(" "),this.compileList($.frontModifiers," ");if($.top)this.append(" "),this.visitNode($.top);if($.selections)this.append(" "),this.compileList($.selections);if($.from)this.append(" "),this.visitNode($.from);if($.joins)this.append(" "),this.compileList($.joins," ");if($.where)this.append(" "),this.visitNode($.where);if($.groupBy)this.append(" "),this.visitNode($.groupBy);if($.having)this.append(" "),this.visitNode($.having);if($.setOperations)this.append(" "),this.compileList($.setOperations," ");if($.orderBy)this.append(" "),this.visitNode($.orderBy);if($.limit)this.append(" "),this.visitNode($.limit);if($.offset)this.append(" "),this.visitNode($.offset);if($.fetch)this.append(" "),this.visitNode($.fetch);if($.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers([...$.endModifiers])," ");if(f)this.append(")")}visitFrom($){this.append("from "),this.compileList($.froms)}visitSelection($){this.visitNode($.selection)}visitColumn($){this.visitNode($.column)}compileDistinctOn($){this.append("distinct on ("),this.compileList($),this.append(")")}compileList($,f=", "){let W=$.length-1;for(let J=0;J<=W;J++)if(this.visitNode($[J]),J<W)this.append(f)}visitWhere($){this.append("where "),this.visitNode($.where)}visitHaving($){this.append("having "),this.visitNode($.having)}visitInsertQuery($){let f=this.nodeStack.find(T.is),W=f!==$;if(!W&&$.explain)this.visitNode($.explain),this.append(" ");if(W&&!A1.is(f))this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append($.replace?"replace":"insert"),$.ignore)this.append(" ignore");if($.top)this.append(" "),this.visitNode($.top);if($.into)this.append(" into "),this.visitNode($.into);if($.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.output)this.append(" "),this.visitNode($.output);if($.values)this.append(" "),this.visitNode($.values);if($.defaultValues)this.append(" "),this.append("default values");if($.onConflict)this.append(" "),this.visitNode($.onConflict);if($.onDuplicateKey)this.append(" "),this.visitNode($.onDuplicateKey);if($.returning)this.append(" "),this.visitNode($.returning);if(W&&!A1.is(f))this.append(")");if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitValues($){this.append("values "),this.compileList($.values)}visitDeleteQuery($){let f=this.nodeStack.find(T.is)!==$;if(!f&&$.explain)this.visitNode($.explain),this.append(" ");if(f)this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append("delete "),$.top)this.visitNode($.top),this.append(" ");if(this.visitNode($.from),$.output)this.append(" "),this.visitNode($.output);if($.using)this.append(" "),this.visitNode($.using);if($.joins)this.append(" "),this.compileList($.joins," ");if($.where)this.append(" "),this.visitNode($.where);if($.orderBy)this.append(" "),this.visitNode($.orderBy);if($.limit)this.append(" "),this.visitNode($.limit);if($.returning)this.append(" "),this.visitNode($.returning);if(f)this.append(")");if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitReturning($){this.append("returning "),this.compileList($.selections)}visitAlias($){this.visitNode($.node),this.append(" as "),this.visitNode($.alias)}visitReference($){if($.table)this.visitNode($.table),this.append(".");this.visitNode($.column)}visitSelectAll($){this.append("*")}visitIdentifier($){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier($),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier($){if(!q0($.name))throw new Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier($.name))}visitAnd($){this.visitNode($.left),this.append(" and "),this.visitNode($.right)}visitOr($){this.visitNode($.left),this.append(" or "),this.visitNode($.right)}visitValue($){if($.immediate)this.appendImmediateValue($.value);else this.appendValue($.value)}visitValueList($){this.append("("),this.compileList($.values),this.append(")")}visitTuple($){this.append("("),this.compileList($.values),this.append(")")}visitPrimitiveValueList($){this.append("(");let{values:f}=$;for(let W=0;W<f.length;++W)if(this.appendValue(f[W]),W!==f.length-1)this.append(", ");this.append(")")}visitParens($){this.append("("),this.visitNode($.node),this.append(")")}visitJoin($){if(this.append(Mp[$.joinType]),this.append(" "),this.visitNode($.table),$.on)this.append(" "),this.visitNode($.on)}visitOn($){this.append("on "),this.visitNode($.on)}visitRaw($){let{sqlFragments:f,parameters:W}=$;for(let J=0;J<f.length;++J)if(this.append(f[J]),W.length>J)this.visitNode(W[J])}visitOperator($){this.append($.operator)}visitTable($){this.visitNode($.table)}visitSchemableIdentifier($){if($.schema)this.visitNode($.schema),this.append(".");this.visitNode($.identifier)}visitCreateTable($){if(this.append("create "),$.frontModifiers&&$.frontModifiers.length>0)this.compileList($.frontModifiers," "),this.append(" ");if($.temporary)this.append("temporary ");if(this.append("table "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.table),$.selectQuery)this.append(" as "),this.visitNode($.selectQuery);else{if(this.append(" ("),this.compileList([...$.columns,...$.constraints??[]]),this.append(")"),$.onCommit)this.append(" on commit "),this.append($.onCommit);if($.endModifiers&&$.endModifiers.length>0)this.append(" "),this.compileList($.endModifiers," ")}}visitColumnDefinition($){if($.ifNotExists)this.append("if not exists ");if(this.visitNode($.column),this.append(" "),this.visitNode($.dataType),$.unsigned)this.append(" unsigned");if($.frontModifiers&&$.frontModifiers.length>0)this.append(" "),this.compileList($.frontModifiers," ");if($.generated)this.append(" "),this.visitNode($.generated);if($.identity)this.append(" identity");if($.defaultTo)this.append(" "),this.visitNode($.defaultTo);if($.notNull)this.append(" not null");if($.unique)this.append(" unique");if($.nullsNotDistinct)this.append(" nulls not distinct");if($.primaryKey)this.append(" primary key");if($.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if($.references)this.append(" "),this.visitNode($.references);if($.check)this.append(" "),this.visitNode($.check);if($.endModifiers&&$.endModifiers.length>0)this.append(" "),this.compileList($.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences($){if(this.append("references "),this.visitNode($.table),this.append(" ("),this.compileList($.columns),this.append(")"),$.onDelete)this.append(" on delete "),this.append($.onDelete);if($.onUpdate)this.append(" on update "),this.append($.onUpdate)}visitDropTable($){if(this.append("drop table "),$.ifExists)this.append("if exists ");if(this.visitNode($.table),$.cascade)this.append(" cascade")}visitDataType($){this.append($.dataType)}visitOrderBy($){this.append("order by "),this.compileList($.items)}visitOrderByItem($){if(this.visitNode($.orderBy),$.direction)this.append(" "),this.visitNode($.direction)}visitGroupBy($){this.append("group by "),this.compileList($.items)}visitGroupByItem($){this.visitNode($.groupBy)}visitUpdateQuery($){let f=this.nodeStack.find(T.is),W=f!==$;if(!W&&$.explain)this.visitNode($.explain),this.append(" ");if(W&&!A1.is(f))this.append("(");if($.with)this.visitNode($.with),this.append(" ");if(this.append("update "),$.top)this.visitNode($.top),this.append(" ");if($.table)this.visitNode($.table),this.append(" ");if(this.append("set "),$.updates)this.compileList($.updates);if($.output)this.append(" "),this.visitNode($.output);if($.from)this.append(" "),this.visitNode($.from);if($.joins)this.append(" "),this.compileList($.joins," ");if($.where)this.append(" "),this.visitNode($.where);if($.limit)this.append(" "),this.visitNode($.limit);if($.returning)this.append(" "),this.visitNode($.returning);if(W&&!A1.is(f))this.append(")");if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitColumnUpdate($){this.visitNode($.column),this.append(" = "),this.visitNode($.value)}visitLimit($){this.append("limit "),this.visitNode($.limit)}visitOffset($){this.append("offset "),this.visitNode($.offset)}visitOnConflict($){if(this.append("on conflict"),$.columns)this.append(" ("),this.compileList($.columns),this.append(")");else if($.constraint)this.append(" on constraint "),this.visitNode($.constraint);else if($.indexExpression)this.append(" ("),this.visitNode($.indexExpression),this.append(")");if($.indexWhere)this.append(" "),this.visitNode($.indexWhere);if($.doNothing===!0)this.append(" do nothing");else if($.updates){if(this.append(" do update set "),this.compileList($.updates),$.updateWhere)this.append(" "),this.visitNode($.updateWhere)}}visitOnDuplicateKey($){this.append("on duplicate key update "),this.compileList($.updates)}visitCreateIndex($){if(this.append("create "),$.unique)this.append("unique ");if(this.append("index "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.name),$.table)this.append(" on "),this.visitNode($.table);if($.using)this.append(" using "),this.visitNode($.using);if($.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.nullsNotDistinct)this.append(" nulls not distinct");if($.where)this.append(" "),this.visitNode($.where)}visitDropIndex($){if(this.append("drop index "),$.ifExists)this.append("if exists ");if(this.visitNode($.name),$.table)this.append(" on "),this.visitNode($.table);if($.cascade)this.append(" cascade")}visitCreateSchema($){if(this.append("create schema "),$.ifNotExists)this.append("if not exists ");this.visitNode($.schema)}visitDropSchema($){if(this.append("drop schema "),$.ifExists)this.append("if exists ");if(this.visitNode($.schema),$.cascade)this.append(" cascade")}visitPrimaryKeyConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");this.append("primary key ("),this.compileList($.columns),this.append(")")}visitUniqueConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");if(this.append("unique"),$.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList($.columns),this.append(")")}visitCheckConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");this.append("check ("),this.visitNode($.expression),this.append(")")}visitForeignKeyConstraint($){if($.name)this.append("constraint "),this.visitNode($.name),this.append(" ");if(this.append("foreign key ("),this.compileList($.columns),this.append(") "),this.visitNode($.references),$.onDelete)this.append(" on delete "),this.append($.onDelete);if($.onUpdate)this.append(" on update "),this.append($.onUpdate)}visitList($){this.compileList($.items)}visitWith($){if(this.append("with "),$.recursive)this.append("recursive ");this.compileList($.expressions)}visitCommonTableExpression($){if(this.visitNode($.name),this.append(" as "),K9($.materialized)){if(!$.materialized)this.append("not ");this.append("materialized ")}this.visitNode($.expression)}visitCommonTableExpressionName($){if(this.visitNode($.table),$.columns)this.append("("),this.compileList($.columns),this.append(")")}visitAlterTable($){if(this.append("alter table "),this.visitNode($.table),this.append(" "),$.renameTo)this.append("rename to "),this.visitNode($.renameTo);if($.setSchema)this.append("set schema "),this.visitNode($.setSchema);if($.addConstraint)this.visitNode($.addConstraint);if($.dropConstraint)this.visitNode($.dropConstraint);if($.columnAlterations)this.compileColumnAlterations($.columnAlterations);if($.addIndex)this.visitNode($.addIndex);if($.dropIndex)this.visitNode($.dropIndex)}visitAddColumn($){this.append("add column "),this.visitNode($.column)}visitRenameColumn($){this.append("rename column "),this.visitNode($.column),this.append(" to "),this.visitNode($.renameTo)}visitDropColumn($){this.append("drop column "),this.visitNode($.column)}visitAlterColumn($){if(this.append("alter column "),this.visitNode($.column),this.append(" "),$.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode($.dataType),$.dataTypeExpression)this.append("using "),this.visitNode($.dataTypeExpression)}if($.setDefault)this.append("set default "),this.visitNode($.setDefault);if($.dropDefault)this.append("drop default");if($.setNotNull)this.append("set not null");if($.dropNotNull)this.append("drop not null")}visitModifyColumn($){this.append("modify column "),this.visitNode($.column)}visitAddConstraint($){this.append("add "),this.visitNode($.constraint)}visitDropConstraint($){if(this.append("drop constraint "),$.ifExists)this.append("if exists ");if(this.visitNode($.constraintName),$.modifier==="cascade")this.append(" cascade");else if($.modifier==="restrict")this.append(" restrict")}visitSetOperation($){if(this.append($.operator),this.append(" "),$.all)this.append("all ");this.visitNode($.expression)}visitCreateView($){if(this.append("create "),$.orReplace)this.append("or replace ");if($.materialized)this.append("materialized ");if($.temporary)this.append("temporary ");if(this.append("view "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.name),this.append(" "),$.columns)this.append("("),this.compileList($.columns),this.append(") ");if($.as)this.append("as "),this.visitNode($.as)}visitDropView($){if(this.append("drop "),$.materialized)this.append("materialized ");if(this.append("view "),$.ifExists)this.append("if exists ");if(this.visitNode($.name),$.cascade)this.append(" cascade")}visitGenerated($){if(this.append("generated "),$.always)this.append("always ");if($.byDefault)this.append("by default ");if(this.append("as "),$.identity)this.append("identity");if($.expression)this.append("("),this.visitNode($.expression),this.append(")");if($.stored)this.append(" stored")}visitDefaultValue($){this.append("default "),this.visitNode($.defaultValue)}visitSelectModifier($){if($.rawModifier)this.visitNode($.rawModifier);else this.append(Rp[$.modifier]);if($.of)this.append(" of "),this.compileList($.of,", ")}visitCreateType($){if(this.append("create type "),this.visitNode($.name),$.enum)this.append(" as enum "),this.visitNode($.enum)}visitDropType($){if(this.append("drop type "),$.ifExists)this.append("if exists ");this.visitNode($.name)}visitExplain($){if(this.append("explain"),$.options||$.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),$.options){if(this.visitNode($.options),$.format)this.append(this.getExplainOptionsDelimiter())}if($.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append($.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue($){this.append("default")}visitAggregateFunction($){if(this.append($.func),this.append("("),$.distinct)this.append("distinct ");if(this.compileList($.aggregated),$.orderBy)this.append(" "),this.visitNode($.orderBy);if(this.append(")"),$.filter)this.append(" filter("),this.visitNode($.filter),this.append(")");if($.over)this.append(" "),this.visitNode($.over)}visitOver($){if(this.append("over("),$.partitionBy){if(this.visitNode($.partitionBy),$.orderBy)this.append(" ")}if($.orderBy)this.visitNode($.orderBy);this.append(")")}visitPartitionBy($){this.append("partition by "),this.compileList($.items)}visitPartitionByItem($){this.visitNode($.partitionBy)}visitBinaryOperation($){this.visitNode($.leftOperand),this.append(" "),this.visitNode($.operator),this.append(" "),this.visitNode($.rightOperand)}visitUnaryOperation($){if(this.visitNode($.operator),!this.isMinusOperator($.operator))this.append(" ");this.visitNode($.operand)}isMinusOperator($){return I$.is($)&&$.operator==="-"}visitUsing($){this.append("using "),this.compileList($.tables)}visitFunction($){this.append($.func),this.append("("),this.compileList($.arguments),this.append(")")}visitCase($){if(this.append("case"),$.value)this.append(" "),this.visitNode($.value);if($.when)this.append(" "),this.compileList($.when," ");if($.else)this.append(" else "),this.visitNode($.else);if(this.append(" end"),$.isStatement)this.append(" case")}visitWhen($){if(this.append("when "),this.visitNode($.condition),$.result)this.append(" then "),this.visitNode($.result)}visitJSONReference($){this.visitNode($.reference),this.visitNode($.traversal)}visitJSONPath($){if($.inOperator)this.visitNode($.inOperator);this.append("'$");for(let f of $.pathLegs)this.visitNode(f);this.append("'")}visitJSONPathLeg($){let f=$.type==="ArrayLocation";if(this.append(f?"[":"."),this.append(String($.value)),f)this.append("]")}visitJSONOperatorChain($){for(let f=0,W=$.values.length;f<W;f++){if(f===W-1)this.visitNode($.operator);else this.append("->");this.visitNode($.values[f])}}visitMergeQuery($){if($.with)this.visitNode($.with),this.append(" ");if(this.append("merge "),$.top)this.visitNode($.top),this.append(" ");if(this.append("into "),this.visitNode($.into),$.using)this.append(" "),this.visitNode($.using);if($.whens)this.append(" "),this.compileList($.whens," ");if($.output)this.append(" "),this.visitNode($.output);if($.endModifiers?.length)this.append(" "),this.compileList($.endModifiers," ")}visitMatched($){if($.not)this.append("not ");if(this.append("matched"),$.bySource)this.append(" by source")}visitAddIndex($){if(this.append("add "),$.unique)this.append("unique ");if(this.append("index "),this.visitNode($.name),$.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.using)this.append(" using "),this.visitNode($.using)}visitCast($){this.append("cast("),this.visitNode($.expression),this.append(" as "),this.visitNode($.dataType),this.append(")")}visitFetch($){this.append("fetch next "),this.visitNode($.rowCount),this.append(` rows ${$.modifier}`)}visitOutput($){this.append("output "),this.compileList($.selections)}visitTop($){if(this.append(`top(${$.expression})`),$.modifiers)this.append(` ${$.modifiers}`)}append($){this.#$+=$}appendValue($){this.addParameter($),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier($){let f=this.getLeftIdentifierWrapper(),W=this.getRightIdentifierWrapper(),J="";for(let Z of $)if(J+=Z,Z===f)J+=f;else if(Z===W)J+=W;return J}addParameter($){this.#f.push($)}appendImmediateValue($){if(q0($))this.append(`'${$}'`);else if(Df($)||K9($))this.append($.toString());else if(K4($))this.append("null");else if(W8($))this.appendImmediateValue($.toISOString());else if(H4($))this.appendImmediateValue($.toString());else throw new Error(`invalid immediate value ${$}`)}sortSelectModifiers($){return $.sort((f,W)=>f.modifier&&W.modifier?pS[f.modifier]-pS[W.modifier]:1),H($)}compileColumnAlterations($){this.compileList($)}announcesNewColumnDataType(){return!0}};Rp=H({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),pS=H({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),Mp=H({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",Using:"using"})});var G1;var D8=K(()=>{M9();I();G1=H({raw($,f=[]){return H({sql:$,query:E0.createWithSql($),parameters:H(f)})}})});var nS=()=>{};var sS=()=>{};class tS{async init(){}async acquireConnection(){return new aS}async beginTransaction(){}async commitTransaction(){}async rollbackTransaction(){}async releaseConnection(){}async destroy(){}}class aS{async executeQuery(){return{rows:[]}}async*streamQuery(){}}var oS=()=>{};var eS=()=>{};class B2{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}var $F=()=>{};class Jw{#$;#f=new WF;#W;#J;constructor($){this.#$=H({...$})}async init(){if(this.#W=V0(this.#$.database)?await this.#$.database():this.#$.database,this.#J=new fF(this.#W),this.#$.onCreateConnection)await this.#$.onCreateConnection(this.#J)}async acquireConnection(){return await this.#f.lock(),this.#J}async beginTransaction($){await $.executeQuery(G1.raw("begin"))}async commitTransaction($){await $.executeQuery(G1.raw("commit"))}async rollbackTransaction($){await $.executeQuery(G1.raw("rollback"))}async releaseConnection(){this.#f.unlock()}async destroy(){this.#W?.close()}}class fF{#$;constructor($){this.#$=$}executeQuery($){let{sql:f,parameters:W}=$,J=this.#$.prepare(f);if(J.reader)return Promise.resolve({rows:J.all(W)});else{let{changes:Z,lastInsertRowid:X}=J.run(W),z=Z!==void 0&&Z!==null?BigInt(Z):void 0;return Promise.resolve({numUpdatedOrDeletedRows:z,numAffectedRows:z,insertId:X!==void 0&&X!==null?BigInt(X):void 0,rows:[]})}}async*streamQuery($,f){let{sql:W,parameters:J,query:Z}=$,X=this.#$.prepare(W);if(Y0.is(Z)){let z=X.iterate(J);for(let w of z)yield{rows:[w]}}else throw new Error("Sqlite driver only supports streaming of select queries")}}class WF{#$;#f;async lock(){while(this.#$)await this.#$;this.#$=new Promise(($)=>{this.#f=$})}unlock(){let $=this.#f;this.#$=void 0,this.#f=void 0,$?.()}}var $M=K(()=>{q4();D8();I()});var qp,v8;var fM=K(()=>{f5();qp=/"/g;v8=class v8 extends F2{getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}sanitizeIdentifier($){return $.replace(qp,'""')}visitDefaultInsertValue($){this.append("null")}}});class WM{transformQuery($){return $.node}async transformResult($){return $.result}}class XF{#$;constructor($){this.#$=H($)}async getMigrations(){let $=await this.#H(this.#J)?await this.#$.db.withPlugin(this.#z).selectFrom(this.#J).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#q()).map(({name:W,...J})=>{let Z=$.find((X)=>X.name===W);return{name:W,migration:J,executedAt:Z?new Date(Z.timestamp):void 0}})}async migrateToLatest(){return this.#f(()=>({direction:"Up",step:1/0}))}async migrateTo($){return this.#f(({migrations:f,executedMigrations:W,pendingMigrations:J})=>{if($===ZF)return{direction:"Down",step:1/0};if(!f.find((z)=>z.name===$))throw new Error(`migration "${$}" doesn't exist`);let Z=W.indexOf($),X=J.findIndex((z)=>z.name===$);if(Z!==-1)return{direction:"Down",step:W.length-Z-1};else if(X!==-1)return{direction:"Up",step:X+1};else throw new Error(`migration "${$}" isn't executed or pending`)})}async migrateUp(){return this.#f(()=>({direction:"Up",step:1}))}async migrateDown(){return this.#f(()=>({direction:"Down",step:1}))}async#f($){try{return await this.#w(),await this.#V($)}catch(f){if(f instanceof Xw)return f.resultSet;return{error:f}}}get#W(){return this.#$.migrationTableSchema}get#J(){return this.#$.migrationTableName??S$}get#Z(){return this.#$.migrationLockTableName??l$}get#X(){return this.#$.allowUnorderedMigrations??JF}get#z(){if(this.#W)return new i$(this.#W);return new WM}async#w(){await this.#G(),await this.#Y(),await this.#K(),await this.#U()}async#G(){if(!this.#W)return;if(!await this.#L())try{await this.#R(this.#$.db.schema.createSchema(this.#W))}catch($){if(!await this.#L())throw $}}async#Y(){if(!await this.#H(this.#J))try{if(this.#W)await this.#R(this.#$.db.schema.createSchema(this.#W));await this.#R(this.#$.db.schema.withPlugin(this.#z).createTable(this.#J).addColumn("name","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("timestamp","varchar(255)",($)=>$.notNull()))}catch($){if(!await this.#H(this.#J))throw $}}async#K(){if(!await this.#H(this.#Z))try{await this.#R(this.#$.db.schema.withPlugin(this.#z).createTable(this.#Z).addColumn("id","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("is_locked","integer",($)=>$.notNull().defaultTo(0)))}catch($){if(!await this.#H(this.#Z))throw $}}async#U(){if(!await this.#M())try{await this.#$.db.withPlugin(this.#z).insertInto(this.#Z).values({id:Zw,is_locked:0}).execute()}catch($){if(!await this.#M())throw $}}async#L(){return(await this.#$.db.introspection.getSchemas()).some((f)=>f.name===this.#W)}async#H($){let f=this.#W;return(await this.#$.db.introspection.getTables({withInternalKyselyTables:!0})).some((J)=>J.name===$&&(!f||J.schema===f))}async#M(){return!!await this.#$.db.withPlugin(this.#z).selectFrom(this.#Z).where("id","=",Zw).select("id").executeTakeFirst()}async#V($){let f=this.#$.db.getExecutor().adapter,W=H({lockTable:this.#$.migrationLockTableName??l$,lockRowId:Zw,lockTableSchema:this.#$.migrationTableSchema}),J=async(Z)=>{try{await f.acquireMigrationLock(Z,W);let X=await this.#Q(Z);if(X.migrations.length===0)return{results:[]};let{direction:z,step:w}=$(X);if(w<=0)return{results:[]};if(z==="Down")return await this.#_(Z,X,w);else if(z==="Up")return await this.#N(Z,X,w);return{results:[]}}finally{await f.releaseMigrationLock(Z,W)}};if(f.supportsTransactionalDdl)return this.#$.db.transaction().execute(J);else return this.#$.db.connection().execute(J)}async#Q($){let f=await this.#q(),W=await this.#O($);if(this.#A(f,W),!this.#X)this.#x(f,W);let J=this.#I(f,W);return H({migrations:f,executedMigrations:W,lastMigration:nN(W),pendingMigrations:J})}#I($,f){return $.filter((W)=>{return!f.includes(W.name)})}async#q(){let $=await this.#$.provider.getMigrations();return Object.keys($).sort().map((f)=>({...$[f],name:f}))}async#O($){let f=await $.withPlugin(this.#z).selectFrom(this.#J).select(["name","timestamp"]).$narrowType().execute(),W=this.#$.nameComparator||((J,Z)=>J.localeCompare(Z));return f.sort((J,Z)=>{if(J.timestamp===Z.timestamp)return W(J.name,Z.name);return new Date(J.timestamp).getTime()-new Date(Z.timestamp).getTime()}).map((J)=>J.name)}#A($,f){for(let W of f)if(!$.some((J)=>J.name===W))throw new Error(`corrupted migrations: previously executed migration ${W} is missing`)}#x($,f){for(let W=0;W<f.length;++W)if($[W].name!==f[W])throw new Error(`corrupted migrations: expected previously executed migration ${f[W]} to be at index ${W} but ${$[W].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#_($,f,W){let J=f.executedMigrations.slice().reverse().slice(0,W).map((X)=>{return f.migrations.find((z)=>z.name===X)}),Z=J.map((X)=>{return{migrationName:X.name,direction:"Down",status:"NotExecuted"}});for(let X=0;X<Z.length;++X){let z=J[X];try{if(z.down)await z.down($),await $.withPlugin(this.#z).deleteFrom(this.#J).where("name","=",z.name).execute(),Z[X]={migrationName:z.name,direction:"Down",status:"Success"}}catch(w){throw Z[X]={migrationName:z.name,direction:"Down",status:"Error"},new Xw({error:w,results:Z})}}return{results:Z}}async#N($,f,W){let Z=f.pendingMigrations.slice(0,W).map((X)=>{return{migrationName:X.name,direction:"Up",status:"NotExecuted"}});for(let X=0;X<Z.length;X++){let z=f.pendingMigrations[X];try{await z.up($),await $.withPlugin(this.#z).insertInto(this.#J).values({name:z.name,timestamp:new Date().toISOString()}).execute(),Z[X]={migrationName:z.name,direction:"Up",status:"Success"}}catch(w){throw Z[X]={migrationName:z.name,direction:"Up",status:"Error"},new Xw({error:w,results:Z})}}return{results:Z}}async#R($){if(this.#$.db.getExecutor().adapter.supportsCreateIfNotExists)$=$.ifNotExists();await $.execute()}}var S$="kysely_migration",l$="kysely_migration_lock",JF=!1,Zw="migration_lock",ZF,Xw;var W5=K(()=>{k6();I();ZF=H({__noMigrations__:!0});Xw=class Xw extends Error{#$;constructor($){super();this.#$=$}get resultSet(){return this.#$}}});class m8{#$;constructor($){this.#$=$}async getSchemas(){return[]}async getTables($={withInternalKyselyTables:!1}){return await this.#W($)}async getMetadata($){return{tables:await this.getTables($)}}#f($,f){let W=$.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");if(!f.withInternalKyselyTables)W=W.where("name","!=",S$).where("name","!=",l$);return W}async#W($){let f=await this.#f(this.#$,$).execute(),W=await this.#$.with("table_list",(Z)=>this.#f(Z,$)).selectFrom(["table_list as tl",J0`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy(["tl.name","p.cid"]).execute(),J={};for(let Z of W)J[Z.table]??=[],J[Z.table].push(Z);return f.map(({name:Z,sql:X,type:z})=>{let w=X?.split(/[\(\),]/)?.find((Y)=>Y.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),G=J[Z]??[];if(!w){let Y=G.filter((L)=>L.pk>0);if(Y.length===1&&Y[0].type.toLowerCase()==="integer")w=Y[0].name}return{name:Z,isView:z==="view",columns:G.map((Y)=>({name:Y.name,dataType:Y.type,isNullable:!Y.notnull,isAutoIncrementing:Y.name===w,hasDefaultValue:Y.dflt_value!=null,comment:void 0}))}})}}var JM=K(()=>{W5();B9()});var k8;var ZM=K(()=>{k8=class k8 extends B2{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock($,f){}async releaseMigrationLock($,f){}}});class zF{#$;constructor($){this.#$=H({...$})}createDriver(){return new Jw(this.#$)}createQueryCompiler(){return new v8}createAdapter(){return new k8}createIntrospector($){return new m8($)}}var wF=K(()=>{$M();fM();JM();ZM();I()});var GF=()=>{};var Vp,zw;var XM=K(()=>{f5();Vp=/"/g;zw=class zw extends F2{sanitizeIdentifier($){return $.replace(Vp,'""')}}});class ww{#$;constructor($){this.#$=$}async getSchemas(){return(await this.#$.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map((f)=>({name:f.nspname}))}async getTables($={withInternalKyselyTables:!1}){let f=this.#$.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",J0`col_description(a.attrelid, a.attnum)`.as("column_description"),this.#$.selectFrom("pg_class").select(J0`true`.as("auto_incrementing")).whereRef("relnamespace","=","c.relnamespace").where("relkind","=","S").where("relname","=",J0`c.relname || '_' || a.attname || '_seq'`).as("auto_incrementing")]).where((J)=>J.or([J("c.relkind","=","r"),J("c.relkind","=","v"),J("c.relkind","=","p")])).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!$.withInternalKyselyTables)f=f.where("c.relname","!=",S$).where("c.relname","!=",l$);let W=await f.execute();return this.#f(W)}async getMetadata($){return{tables:await this.getTables($)}}#f($){return $.reduce((f,W)=>{let J=f.find((Z)=>Z.name===W.table&&Z.schema===W.schema);if(!J)J=H({name:W.table,isView:W.table_type==="v",schema:W.schema,columns:[]}),f.push(J);return J.columns.push(H({name:W.column,dataType:W.type,dataTypeSchema:W.type_schema,isNullable:!W.not_null,isAutoIncrementing:!!W.auto_incrementing,hasDefaultValue:W.has_default,comment:W.column_description??void 0})),f},[])}}var zM=K(()=>{W5();I();B9()});var Qp,Gw;var wM=K(()=>{B9();Qp=BigInt("3853314791062309107");Gw=class Gw extends B2{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock($,f){await J0`select pg_advisory_xact_lock(${J0.lit(Qp)})`.execute($)}async releaseMigrationLock($,f){}}});function y8($,f){if(Ip($)&&f.stack){let W=f.stack.split(`
`).slice(1).join(`
`);return $.stack+=`
${W}`,$}return $}function Ip($){return t0($)&&q0($.stack)}var Yw=K(()=>{I()});class Lw{#$;#f=new WeakMap;#W;constructor($){this.#$=H({...$})}async init(){this.#W=V0(this.#$.pool)?await this.#$.pool():this.#$.pool}async acquireConnection(){let $=await this.#J(),f=this.#f.get($);if(!f){if(f=new LF($),this.#f.set($,f),this.#$?.onCreateConnection)await this.#$.onCreateConnection(f)}if(this.#$?.onReserveConnection)await this.#$.onReserveConnection(f);return f}async#J(){return new Promise(($,f)=>{this.#W.getConnection(async(W,J)=>{if(W)f(W);else $(J)})})}async beginTransaction($,f){if(f.isolationLevel)await $.executeQuery(G1.raw(`set transaction isolation level ${f.isolationLevel}`));await $.executeQuery(G1.raw("begin"))}async commitTransaction($){await $.executeQuery(G1.raw("commit"))}async rollbackTransaction($){await $.executeQuery(G1.raw("rollback"))}async releaseConnection($){$[YF]()}async destroy(){return new Promise(($,f)=>{this.#W.end((W)=>{if(W)f(W);else $()})})}}function Op($){return t0($)&&"insertId"in $&&"affectedRows"in $}var YF,LF;var GM=K(()=>{D8();I();Yw();YF=Symbol();LF=class LF{#$;constructor($){this.#$=$}async executeQuery($){try{let f=await this.#f($);if(Op(f)){let{insertId:W,affectedRows:J,changedRows:Z}=f,X=J!==void 0&&J!==null?BigInt(J):void 0,z=Z!==void 0&&Z!==null?BigInt(Z):void 0;return{insertId:W!==void 0&&W!==null&&W.toString()!=="0"?BigInt(W):void 0,numUpdatedOrDeletedRows:X,numAffectedRows:X,numChangedRows:z,rows:[]}}else if(Array.isArray(f))return{rows:f};return{rows:[]}}catch(f){throw y8(f,new Error)}}#f($){return new Promise((f,W)=>{this.#$.query($.sql,$.parameters,(J,Z)=>{if(J)W(J);else f(Z)})})}async*streamQuery($,f){let W=this.#$.query($.sql,$.parameters).stream({objectMode:!0});try{for await(let J of W)yield{rows:[J]}}catch(J){if(J&&typeof J==="object"&&"code"in J&&J.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw J}}[YF](){this.#$.release()}}});var Ap,Kw;var YM=K(()=>{f5();Ap=/`/g;Kw=class Kw extends F2{getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getExplainOptionAssignment(){return"="}getExplainOptionsDelimiter(){return" "}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return"`"}getRightIdentifierWrapper(){return"`"}sanitizeIdentifier($){return $.replace(Ap,"``")}visitCreateIndex($){if(this.append("create "),$.unique)this.append("unique ");if(this.append("index "),$.ifNotExists)this.append("if not exists ");if(this.visitNode($.name),$.using)this.append(" using "),this.visitNode($.using);if($.table)this.append(" on "),this.visitNode($.table);if($.columns)this.append(" ("),this.compileList($.columns),this.append(")");if($.where)this.append(" "),this.visitNode($.where)}}});class Hw{#$;constructor($){this.#$=$}async getSchemas(){return(await this.#$.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute()).map((f)=>({name:f.SCHEMA_NAME}))}async getTables($={withInternalKyselyTables:!1}){let f=this.#$.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables",(J)=>J.onRef("columns.TABLE_CATALOG","=","tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA","=","tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME","=","tables.TABLE_NAME")).select(["columns.COLUMN_NAME","columns.COLUMN_DEFAULT","columns.TABLE_NAME","columns.TABLE_SCHEMA","tables.TABLE_TYPE","columns.IS_NULLABLE","columns.DATA_TYPE","columns.EXTRA","columns.COLUMN_COMMENT"]).where("columns.TABLE_SCHEMA","=",J0`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo();if(!$.withInternalKyselyTables)f=f.where("columns.TABLE_NAME","!=",S$).where("columns.TABLE_NAME","!=",l$);let W=await f.execute();return this.#f(W)}async getMetadata($){return{tables:await this.getTables($)}}#f($){return $.reduce((f,W)=>{let J=f.find((Z)=>Z.name===W.TABLE_NAME);if(!J)J=H({name:W.TABLE_NAME,isView:W.TABLE_TYPE==="VIEW",schema:W.TABLE_SCHEMA,columns:[]}),f.push(J);return J.columns.push(H({name:W.COLUMN_NAME,dataType:W.DATA_TYPE,isNullable:W.IS_NULLABLE==="YES",isAutoIncrementing:W.EXTRA.toLowerCase().includes("auto_increment"),hasDefaultValue:W.COLUMN_DEFAULT!==null,comment:W.COLUMN_COMMENT===""?void 0:W.COLUMN_COMMENT})),f},[])}}var LM=K(()=>{W5();I();B9()});var KF="ea586330-2c93-47c8-908d-981d9d270f9d",xp=3600,Uw;var KM=K(()=>{B9();Uw=class Uw extends B2{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}async acquireMigrationLock($,f){await J0`select get_lock(${J0.lit(KF)}, ${J0.lit(xp)})`.execute($)}async releaseMigrationLock($,f){await J0`select release_lock(${J0.lit(KF)})`.execute($)}}});class HF{#$;constructor($){this.#$=$}createDriver(){return new Lw(this.#$)}createQueryCompiler(){return new Kw}createAdapter(){return new Uw}createIntrospector($){return new Hw($)}}var UF=K(()=>{GM();YM();LM();KM()});var RF=()=>{};class Rw{#$;#f=new WeakMap;#W;constructor($){this.#$=H({...$})}async init(){this.#W=V0(this.#$.pool)?await this.#$.pool():this.#$.pool}async acquireConnection(){let $=await this.#W.connect(),f=this.#f.get($);if(!f){if(f=new qF($,{cursor:this.#$.cursor??null}),this.#f.set($,f),this.#$.onCreateConnection)await this.#$.onCreateConnection(f)}if(this.#$.onReserveConnection)await this.#$.onReserveConnection(f);return f}async beginTransaction($,f){if(f.isolationLevel)await $.executeQuery(G1.raw(`start transaction isolation level ${f.isolationLevel}`));else await $.executeQuery(G1.raw("begin"))}async commitTransaction($){await $.executeQuery(G1.raw("commit"))}async rollbackTransaction($){await $.executeQuery(G1.raw("rollback"))}async releaseConnection($){$[MF]()}async destroy(){if(this.#W){let $=this.#W;this.#W=void 0,await $.end()}}}var MF,qF;var HM=K(()=>{D8();I();Yw();MF=Symbol();qF=class qF{#$;#f;constructor($,f){this.#$=$,this.#f=f}async executeQuery($){try{let f=await this.#$.query($.sql,[...$.parameters]);if(f.command==="INSERT"||f.command==="UPDATE"||f.command==="DELETE"||f.command==="MERGE"){let W=BigInt(f.rowCount);return{numUpdatedOrDeletedRows:W,numAffectedRows:W,rows:f.rows??[]}}return{rows:f.rows??[]}}catch(f){throw y8(f,new Error)}}async*streamQuery($,f){if(!this.#f.cursor)throw new Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.");if(!Number.isInteger(f)||f<=0)throw new Error("chunkSize must be a positive integer");let W=this.#$.query(new this.#f.cursor($.sql,$.parameters.slice()));try{while(!0){let J=await W.read(f);if(J.length===0)break;yield{rows:J}}}finally{await W.close()}}[MF](){this.#$.release()}}});var VF=()=>{};class QF{#$;constructor($){this.#$=$}createDriver(){return new Rw(this.#$)}createQueryCompiler(){return new zw}createAdapter(){return new Gw}createIntrospector($){return new ww($)}}var IF=K(()=>{HM();zM();XM();wM()});var Mw;var UM=K(()=>{W5();B9();Mw=class Mw extends B2{get supportsCreateIfNotExists(){return!1}get supportsTransactionalDdl(){return!0}get supportsOutput(){return!0}async acquireMigrationLock($){await J0`exec sp_getapplock @DbPrincipal = ${J0.lit("dbo")}, @Resource = ${J0.lit(S$)}, @LockMode = ${J0.lit("Exclusive")}`.execute($)}async releaseMigrationLock(){}}});var OF=()=>{};class Vw{#$;#f;constructor($){this.#$=H({...$});let{tarn:f,tedious:W}=this.#$,{validateConnections:J,...Z}=f.options;this.#f=new f.Pool({...Z,create:async()=>{let X=await W.connectionFactory();return await new _F(X,W).connect()},destroy:async(X)=>{await X[xF]()},validate:J===!1?void 0:(X)=>X.validate()})}async init(){}async acquireConnection(){return await this.#f.acquire().promise}async beginTransaction($,f){await $.beginTransaction(f)}async commitTransaction($){await $.commitTransaction()}async rollbackTransaction($){await $.rollbackTransaction()}async releaseConnection($){await $[AF](),this.#f.release($)}async destroy(){await this.#f.destroy()}}class qw{#$;#f;#W;#J;#Z;#X;#z;constructor($){let{compiledQuery:f,onDone:W,streamChunkSize:J,tedious:Z}=$;if(this.#f=[],this.#W=J,this.#J={},this.#Z=Z,W)this.#J.onDone=(z,w)=>{if(z==="chunkReady")return;if(delete this.#J.onDone,z==="error")W.reject(w);else W.resolve({rowCount:this.#z,rows:this.#f})};this.#$=new this.#Z.Request(f.sql,(X,z)=>{if(X)Object.values(this.#J).forEach((w)=>w("error",X instanceof AggregateError?X.errors:X));else this.#z=z}),this.#w(f.parameters),this.#G()}get request(){return this.#$}readChunk(){let $=this.readChunk.name;return new Promise((f,W)=>{this.#J[$]=(J,Z)=>{if(delete this.#J[$],J==="error")W(Z);else f(this.#f.splice(0,this.#W))},this.#$.resume()})}#w($){for(let f=0;f<$.length;f++){let W=$[f];this.#$.addParameter(String(f+1),this.#Y(W),W)}}#G(){let $=this.#W?()=>{if(this.#W<=this.#f.length)this.#$.pause(),Object.values(this.#J).forEach((W)=>W("chunkReady"))}:()=>{},f=(W)=>{let J={};for(let Z of W)J[Z.metadata.colName]=Z.value;this.#f.push(J),$()};this.#$.on("row",f),this.#$.once("requestCompleted",()=>{Object.values(this.#J).forEach((W)=>W("completed")),this.#$.off("row",f)})}#Y($){if(K4($)||H$($)||q0($))return this.#Z.TYPES.NVarChar;if(H4($)||Df($)&&$%1===0)if($<-2147483648||$>2147483647)return this.#Z.TYPES.BigInt;else return this.#Z.TYPES.Int;if(Df($))return this.#Z.TYPES.Float;if(K9($))return this.#Z.TYPES.Bit;if(W8($))return this.#Z.TYPES.DateTime;if(uz($))return this.#Z.TYPES.VarBinary;return this.#Z.TYPES.NVarChar}}var AF,xF,_F;var RM=K(()=>{I();D8();Yw();kU();AF=Symbol(),xF=Symbol();_F=class _F{#$;#f;constructor($,f){this.#$=$,this.#f=f,this.#$.on("error",console.error),this.#$.once("end",()=>{this.#$.off("error",console.error)})}async beginTransaction($){let{isolationLevel:f}=$;await new Promise((W,J)=>this.#$.beginTransaction((Z)=>{if(Z)J(Z);else W(void 0)},f?N3(8):void 0,f?this.#W(f):void 0))}async commitTransaction(){await new Promise(($,f)=>this.#$.commitTransaction((W)=>{if(W)f(W);else $(void 0)}))}async connect(){return await new Promise(($,f)=>{this.#$.connect((W)=>{if(W)console.error(W),f(W);else $(void 0)})}),this}async executeQuery($){try{let f=new y6,W=new qw({compiledQuery:$,tedious:this.#f,onDone:f});this.#$.execSql(W.request);let{rowCount:J,rows:Z}=await f.promise;return{numAffectedRows:J!==void 0?BigInt(J):void 0,rows:Z}}catch(f){throw y8(f,new Error)}}async rollbackTransaction(){await new Promise(($,f)=>this.#$.rollbackTransaction((W)=>{if(W)f(W);else $(void 0)}))}async*streamQuery($,f){if(!Number.isInteger(f)||f<=0)throw new Error("chunkSize must be a positive integer");let W=new qw({compiledQuery:$,streamChunkSize:f,tedious:this.#f});this.#$.execSql(W.request);try{while(!0){let J=await W.readChunk();if(J.length===0)break;if(yield{rows:J},J.length<f)break}}finally{await this.#J(W)}}async validate(){try{let $=new y6,f=new qw({compiledQuery:G1.raw("select 1"),onDone:$,tedious:this.#f});return this.#$.execSql(f.request),await $.promise,!0}catch{return!1}}#W($){let{ISOLATION_LEVEL:f}=this.#f,J={"read committed":f.READ_COMMITTED,"read uncommitted":f.READ_UNCOMMITTED,"repeatable read":f.REPEATABLE_READ,serializable:f.SERIALIZABLE,snapshot:f.SNAPSHOT}[$];if(J===void 0)throw new Error(`Unknown isolation level: ${$}`);return J}#J($){return new Promise((f)=>{if($.request.once("requestCompleted",f),!this.#$.cancel())$.request.off("requestCompleted",f),f(void 0)})}async[AF](){if(this.#f.resetConnectionOnRelease!==!1)await new Promise(($,f)=>{this.#$.reset((W)=>{if(W)f(W);else $(void 0)})})}[xF](){return new Promise(($)=>{this.#$.once("end",()=>{$(void 0)}),this.#$.close()})}}});class Qw{#$;constructor($){this.#$=$}async getSchemas(){return await this.#$.selectFrom("sys.schemas").select("name").execute()}async getTables($={withInternalKyselyTables:!1}){let f=await this.#$.selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas","table_schemas.schema_id","tables.schema_id").innerJoin("sys.columns as columns","columns.object_id","tables.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",(J)=>J.onRef("comments.major_id","=","tables.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).$if(!$.withInternalKyselyTables,(J)=>J.where("tables.name","!=",S$).where("tables.name","!=",l$)).select(["tables.name as table_name",(J)=>J.ref("tables.type").$castTo().as("table_type"),"table_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"]).unionAll(this.#$.selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas","view_schemas.schema_id","views.schema_id").innerJoin("sys.columns as columns","columns.object_id","views.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",(J)=>J.onRef("comments.major_id","=","views.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).select(["views.name as table_name","views.type as table_type","view_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(),W={};for(let J of f){let Z=`${J.table_schema_name}.${J.table_name}`;(W[Z]=W[Z]||H({columns:[],isView:J.table_type==="V ",name:J.table_name,schema:J.table_schema_name??void 0})).columns.push(H({dataType:J.type_name,dataTypeSchema:J.type_schema_name??void 0,hasDefaultValue:J.column_default_object_id>0||J.column_generated_always_type!=="NOT_APPLICABLE"||J.column_is_identity||J.column_is_computed||J.column_is_rowguidcol,isAutoIncrementing:J.column_is_identity,isNullable:J.column_is_nullable&&J.type_is_nullable,name:J.column_name,comment:J.column_comment??void 0}))}return Object.values(W)}async getMetadata($){return{tables:await this.getTables($)}}}var MM=K(()=>{W5();I()});var Iw;var qM=K(()=>{f5();Iw=class Iw extends F2{getCurrentParameterPlaceholder(){return`@${this.numParameters}`}visitOffset($){super.visitOffset($),this.append(" rows")}compileColumnAlterations($){let f={};for(let J of $){if(!f[J.kind])f[J.kind]=[];f[J.kind].push(J)}let W=!0;if(f.AddColumnNode)this.append("add "),this.compileList(f.AddColumnNode),W=!1;if(f.AlterColumnNode){if(!W)this.append(", ");this.compileList(f.AlterColumnNode)}if(f.DropColumnNode){if(!W)this.append(", ");this.append("drop column "),this.compileList(f.DropColumnNode)}if(f.ModifyColumnNode){if(!W)this.append(", ");this.compileList(f.ModifyColumnNode)}if(f.RenameColumnNode){if(!W)this.append(", ");this.compileList(f.RenameColumnNode)}}visitAddColumn($){this.visitNode($.column)}visitDropColumn($){this.visitNode($.column)}visitMergeQuery($){super.visitMergeQuery($),this.append(";")}announcesNewColumnDataType(){return!1}}});class NF{#$;constructor($){this.#$=$}createDriver(){return new Vw(this.#$)}createQueryCompiler(){return new Iw}createAdapter(){return new Mw}createIntrospector($){return new Qw($)}}var SF=K(()=>{UM();RM();MM();qM()});var FF=()=>{};class TF{#$;constructor($){this.#$=$}async getMigrations(){let $={},f=await this.#$.fs.readdir(this.#$.migrationFolder);for(let W of f)if(W.endsWith(".js")||W.endsWith(".ts")&&!W.endsWith(".d.ts")||W.endsWith(".mjs")||W.endsWith(".mts")&&!W.endsWith(".d.mts")){let J=await import(this.#$.path.join(this.#$.migrationFolder,W)),Z=W.substring(0,W.lastIndexOf("."));if(BF(J?.default))$[Z]=J.default;else if(BF(J))$[Z]=J}return $}}function BF($){return t0($)&&V0($.up)}var PF=K(()=>{I()});var CF=()=>{};var VM;var EF=K(()=>{I8();VM=class VM extends _2{#$;constructor($){super();this.#$=$}transformIdentifier($){return $=super.transformIdentifier($),{...$,name:this.#$($.name)}}}});function DF({upperCase:$=!1,underscoreBeforeDigits:f=!1,underscoreBetweenUppercaseLetters:W=!1}={}){return mF((J)=>{if(J.length===0)return J;let Z=J.toUpperCase(),X=J.toLowerCase(),z=X[0];for(let w=1,G=J.length;w<G;++w){let Y=J[w],L=J[w-1],U=Z[w],M=Z[w-1],q=X[w],V=X[w-1];if(f&&hF(Y)&&!hF(L)&&!z.endsWith("_")){z+="_"+Y;continue}if(Y===U&&U!==q)if(W||!(L===M&&M!==V))z+="_"+q;else z+=q;else z+=Y}if($)return z.toUpperCase();else return z})}function vF({upperCase:$=!1}={}){return mF((f)=>{if(f.length===0)return f;if($&&_p(f))f=f.toLowerCase();let W=f[0];for(let J=1,Z=f.length;J<Z;++J){let X=f[J],z=f[J-1];if(X!=="_")if(z==="_")W+=X.toUpperCase();else W+=X}return W})}function _p($){for(let f=1,W=$.length;f<W;++f){let J=$[f];if(J!=="_"&&J!==J.toUpperCase())return!1}return!0}function hF($){return $>="0"&&$<="9"}function mF($){let f=new Map;return(W)=>{let J=f.get(W);if(!J)J=$(W),f.set(W,J);return J}}class yF{opt;#$;#f;#W;constructor($={}){this.opt=$,this.#$=vF($),this.#f=DF($),this.#W=new VM(this.snakeCase.bind(this))}transformQuery($){return this.#W.transformNode($.node)}async transformResult($){if($.result.rows&&Array.isArray($.result.rows))return{...$.result,rows:$.result.rows.map((f)=>this.mapRow(f))};return $.result}mapRow($){return Object.keys($).reduce((f,W)=>{let J=$[W];if(Array.isArray(J))J=J.map((Z)=>kF(Z,this.opt)?this.mapRow(Z):Z);else if(kF(J,this.opt))J=this.mapRow(J);return f[this.camelCase(W)]=J,f},{})}snakeCase($){return this.#f($)}camelCase($){return this.#$($)}}function kF($,f){return cz($)&&!f?.maintainNestedObjectKeys}var jF=K(()=>{I();EF()});var QM;var gF=K(()=>{I8();I();QM=class QM extends _2{transformSelectQuery($){return this.#$(super.transformSelectQuery($))}transformUpdateQuery($){return this.#$(super.transformUpdateQuery($))}transformDeleteQuery($){return this.#$(super.transformDeleteQuery($))}#$($){if(!$.joins||$.joins.length===0)return $;return H({...$,joins:this.#f($.joins)})}#f($){let f=[];for(let W=0;W<$.length;++W){let J=!1;for(let Z=0;Z<f.length;++Z)if(dz($[W],f[Z])){J=!0;break}if(!J)f.push($[W])}return H(f)}}});class bF{#$=new QM;transformQuery($){return this.#$.transformNode($.node)}transformResult($){return Promise.resolve($.result)}}var uF=K(()=>{gF()});class j8{opt;#$;constructor($={}){this.opt=$,this.#$=$.objectStrategy||"in-place"}transformQuery($){return $.node}async transformResult($){return{...$.result,rows:cF($.result.rows,this.#$)}}}function cF($,f){let W=f==="create"?new Array($.length):$;for(let J=0;J<$.length;++J)W[J]=IM($[J],f);return W}function IM($,f){if(q0($))return Np($);if(Array.isArray($))return cF($,f);if(cz($))return Fp($,f);return $}function Np($){if(Sp($))try{return IM(JSON.parse($),"in-place")}catch(f){}return $}function Sp($){return $.match(/^[\[\{]/)!=null}function Fp($,f){let W=f==="create"?{}:$;for(let J in $)W[J]=IM($[J],f);return W}var dF=K(()=>{I()});var iF=()=>{};var Bp;var rF=K(()=>{I();Bp=H({is($){return $.kind==="ListNode"},create($){return H({kind:"ListNode",items:H($)})}})});var lF=()=>{};var pF=()=>{};var nF=()=>{};var sF=()=>{};var tF=()=>{};var aF=()=>{};var oF={};V1(oF,{sql:()=>J0,logOnce:()=>S3,isOperator:()=>gl,isOperationNodeSource:()=>y0,isNoResultErrorConstructor:()=>bf,isKyselyProps:()=>jS,isJSONOperator:()=>tz,isExpression:()=>iH,isCompilable:()=>sR,isComparisonOperator:()=>ul,isColumnDataType:()=>LR,isBinaryOperator:()=>bl,isArithmeticOperator:()=>cl,isAliasedExpression:()=>rH,expressionBuilder:()=>d$,createSelectQueryBuilder:()=>g6,createRawBuilder:()=>S2,createFunctionModule:()=>HZ,WithSchemaPlugin:()=>i$,WithNode:()=>Q8,WhereNode:()=>E1,WheneableMergeQueryBuilder:()=>A$,WhenNode:()=>A2,ValuesNode:()=>MU,ValueNode:()=>U1,ValueListNode:()=>T6,UsingNode:()=>L3,UpdateResult:()=>I3,UpdateQueryNode:()=>jf,UpdateQueryBuilder:()=>N0,UniqueConstraintNode:()=>r6,UnaryOperationNode:()=>fR,UNARY_OPERATORS:()=>tN,UNARY_FILTER_OPERATORS:()=>sN,TupleNode:()=>y3,TraversedJSONPathBuilder:()=>_8,TransactionBuilder:()=>BZ,Transaction:()=>$5,TopNode:()=>PU,TableNode:()=>t1,TRANSACTION_ISOLATION_LEVELS:()=>lR,SqliteQueryCompiler:()=>v8,SqliteIntrospector:()=>m8,SqliteDriver:()=>Jw,SqliteDialect:()=>zF,SqliteAdapter:()=>k8,SingleConnectionProvider:()=>FZ,SetOperationNode:()=>GZ,SelectionNode:()=>P6,SelectQueryNode:()=>Y0,SelectModifierNode:()=>mf,SelectAllNode:()=>F6,SchemableIdentifierNode:()=>U$,SchemaModule:()=>e6,ReturningNode:()=>K3,RenameColumnNode:()=>b3,ReferencesNode:()=>d6,ReferenceNode:()=>V2,RawNode:()=>E0,QueryNode:()=>T,QueryCreator:()=>cf,PrimitiveValueListNode:()=>tJ,PrimaryConstraintNode:()=>OZ,PostgresQueryCompiler:()=>zw,PostgresIntrospector:()=>ww,PostgresDriver:()=>Rw,PostgresDialect:()=>QF,PostgresAdapter:()=>Gw,PartitionByNode:()=>Z3,PartitionByItemNode:()=>HU,ParseJSONResultsPlugin:()=>j8,ParensNode:()=>yf,OverNode:()=>K8,OutputNode:()=>H3,OrderByNode:()=>c$,OrderByItemNode:()=>pJ,OrWrapper:()=>YZ,OrNode:()=>zf,OperatorNode:()=>I$,OperationNodeVisitor:()=>Ww,OperationNodeTransformer:()=>_2,OnNode:()=>dJ,OnDuplicateKeyNode:()=>FU,OnConflictUpdateBuilder:()=>h6,OnConflictNode:()=>e1,OnConflictDoNothingBuilder:()=>V3,OnConflictBuilder:()=>Gf,OffsetNode:()=>rU,OPERATORS:()=>sz,ON_MODIFY_FOREIGN_ACTIONS:()=>VR,ON_COMMIT_ACTIONS:()=>dH,NotMatchedThenableMergeQueryBuilder:()=>B3,NoopQueryExecutor:()=>j6,NoResultError:()=>wf,NO_MIGRATIONS:()=>ZF,NOOP_QUERY_EXECUTOR:()=>O9,MysqlQueryCompiler:()=>Kw,MysqlIntrospector:()=>Hw,MysqlDriver:()=>Lw,MysqlDialect:()=>HF,MysqlAdapter:()=>Uw,MssqlQueryCompiler:()=>Iw,MssqlIntrospector:()=>Qw,MssqlDriver:()=>Vw,MssqlDialect:()=>NF,MssqlAdapter:()=>Mw,ModifyColumnNode:()=>d3,Migrator:()=>XF,MergeResult:()=>F3,MergeQueryNode:()=>A1,MergeQueryBuilder:()=>A9,MatchedThenableMergeQueryBuilder:()=>zZ,MatchedNode:()=>jU,MIGRATION_LOCK_ID:()=>Zw,Log:()=>$w,ListNode:()=>Bp,LimitNode:()=>D6,LOG_LEVELS:()=>Kp,Kysely:()=>N2,JoinNode:()=>U9,JoinBuilder:()=>V4,JSON_OPERATORS:()=>aH,JSONReferenceNode:()=>B6,JSONPathNode:()=>V9,JSONPathLegNode:()=>k3,JSONPathBuilder:()=>N8,JSONOperatorChainNode:()=>nJ,InsertResult:()=>M3,InsertQueryNode:()=>O1,InsertQueryBuilder:()=>j0,IdentifierNode:()=>p,HavingNode:()=>w3,GroupByNode:()=>z3,GroupByItemNode:()=>pU,GeneratedNode:()=>S8,FunctionNode:()=>h3,FromNode:()=>M4,ForeignKeyConstraintNode:()=>A4,ForeignKeyConstraintBuilder:()=>x9,FileMigrationProvider:()=>TF,FetchNode:()=>sU,ExpressionWrapper:()=>H0,ExplainNode:()=>xU,DynamicModule:()=>o3,DummyDriver:()=>tS,DropViewNode:()=>o6,DropViewBuilder:()=>N4,DropTypeNode:()=>SZ,DropTypeBuilder:()=>E8,DropTableNode:()=>X8,DropTableBuilder:()=>a6,DropSchemaNode:()=>Z8,DropSchemaBuilder:()=>t6,DropIndexNode:()=>H9,DropIndexBuilder:()=>_4,DropConstraintNode:()=>l6,DropColumnNode:()=>g3,DialectAdapterBase:()=>B2,DeleteResult:()=>Q3,DeleteQueryNode:()=>gf,DeleteQueryBuilder:()=>_0,DefaultValueNode:()=>OR,DefaultQueryExecutor:()=>F9,DefaultQueryCompiler:()=>F2,DefaultInsertValueNode:()=>VU,DefaultConnectionProvider:()=>e3,DeduplicateJoinsPlugin:()=>bF,DataTypeNode:()=>YR,DEFAULT_MIGRATION_TABLE:()=>S$,DEFAULT_MIGRATION_LOCK_TABLE:()=>l$,DEFAULT_ALLOW_UNORDERED_MIGRATIONS:()=>JF,CreateViewNode:()=>Yf,CreateViewBuilder:()=>lf,CreateTypeNode:()=>NZ,CreateTypeBuilder:()=>C8,CreateTableNode:()=>b1,CreateTableBuilder:()=>$$,CreateSchemaNode:()=>uJ,CreateSchemaBuilder:()=>P8,CreateIndexNode:()=>Xf,CreateIndexBuilder:()=>N$,ConnectionBuilder:()=>fw,CompiledQuery:()=>G1,CommonTableExpressionNode:()=>v6,CommonTableExpressionNameNode:()=>A3,ColumnUpdateNode:()=>U3,ColumnNode:()=>z0,ColumnDefinitionNode:()=>D0,ColumnDefinitionBuilder:()=>P0,CheckConstraintNode:()=>c6,CastNode:()=>HR,CaseWhenBuilder:()=>JR,CaseThenBuilder:()=>v3,CaseNode:()=>_$,CaseEndBuilder:()=>ZR,CaseBuilder:()=>x8,CamelCasePlugin:()=>yF,COMPARISON_OPERATORS:()=>sH,BinaryOperationNode:()=>R9,BINARY_OPERATORS:()=>oH,AndWrapper:()=>LZ,AndNode:()=>R$,AlteredColumnBuilder:()=>x4,AlterTableNode:()=>U0,AlterTableColumnAlteringBuilder:()=>r$,AlterTableBuilder:()=>AZ,AlterColumnNode:()=>p6,AlterColumnBuilder:()=>B8,AliasedJSONPathBuilder:()=>zR,AliasedExpressionWrapper:()=>KZ,AliasedAggregateFunctionBuilder:()=>eU,AliasNode:()=>I1,AggregateFunctionNode:()=>df,AggregateFunctionBuilder:()=>x$,AddIndexNode:()=>N9,AddConstraintNode:()=>i6,AddColumnNode:()=>j3,ARITHMETIC_OPERATORS:()=>tH});var T2=K(()=>{gS();T3();lH();I4();u6();bS();uS();cS();dS();wZ();EU();O3();hU();E6();KU();D3();TU();$R();m3();wR();dU();oR();B9();rS();dR();A8();lS();f5();D8();uR();ER();jR();vR();gR();PR();hR();CR();DR();c3();i3();BR();kR();yR();SR();cR();pR();nS();sS();oS();eS();$F();wF();GF();$M();XM();zM();wM();UF();RF();GM();YM();LM();KM();HM();VF();IF();fM();JM();ZM();UM();OF();SF();RM();MM();qM();f5();FF();W5();PF();CF();jF();uF();k6();dF();RR();r3();n3();E3();vf();NR();x6();R4();nz();UZ();UR();qZ();MZ();u1();SU();DU();x3();iF();iz();rz();J8();t3();_Z();KR();QU();AR();$Z();MR();l3();cJ();lz();pz();a3();s3();_U();tU();QZ();eJ();oU();IR();nU();YU();LU();i0();C6();iJ();$3();XR();sJ();ez();JZ();rF();gU();M8();_R();lU();q3();BU();nH();g$();I8();eR();lF();S6();N6();fU();L8();NU();X3();G8();UU();GU();p3();f3();I9();M9();lJ();VZ();qR();AU();U4();rJ();pH();q4();RU();P3();pF();_6();CU();GR();WR();IZ();U8();OU();aJ();I2();qU();R8();fZ();mU();nF();tR();sF();tF();nR();aF();uU()});class TZ{plugins;constructor($=[]){this.plugins=new Set($)}async transformResultRows($){let f=$;for(let W of this.plugins)f=(await W.transformResult({queryId:"1",result:{rows:f}})).rows;return f}}class F${fn;plugins;initialized=!1;pluginRunner;supported={batching:!1,softscans:!0};kysely;client;constructor($,f={},W=[]){this.fn=f;this.plugins=W;this.kysely=$,this[$B]=!0,this.pluginRunner=new TZ(W)}async init(){this.initialized=!0}static isConnection($){if(!$)return!1;return $[$B]===!0}getIntrospector(){return this.kysely.introspection}supports($){return this.supported[$]??!1}async ping(){return(await J0`SELECT 1`.execute(this.kysely)).rows.length>0}async transformResultRows($){return await this.pluginRunner.transformResultRows($)}async executeQueries(...$){return Promise.all($.map(async(f)=>await this.kysely.executeQuery(f)))}async executeQuery($){return(await this.executeQueries($))[0]}getCompiled(...$){return $.map((f)=>{if("compile"in f)return f.compile();return f})}async withTransformedRows($,f){return await Promise.all($.map(async(W)=>{let J=f??"rows",{[J]:Z,...X}=W;return{...X,rows:await this.transformResultRows(Z)}}))}validateFieldSpecType($){if(!eF.includes($))throw new Error(`Invalid field type "${$}". Allowed types are: ${eF.join(", ")}`);return!0}toDriver($,f){return $}fromDriver($,f){return $}async close(){}}function Ow($,f,W={}){return{create(...J){return new class extends ${createIntrospector(Z){return new f(Z,W)}}(...J)}}}var eF,$B;var J5=K(()=>{T2();eF=["text","integer","real","blob","date","datetime","timestamp","boolean","json"],$B=Symbol.for("bknd:connection")});var OM,Lf,AM,f1,xM,_M,Tp;var B$=K(()=>{Y9();OM=class OM extends w1{name="UnableToConnectException";code=500};Lf=class Lf extends w1{name="InvalidSearchParamsException";code=422};AM=class AM extends w1{name="TransformRetrieveFailedException";code=422};f1=class f1 extends w1{name="TransformPersistFailedException";code=422;static invalidType($,f,W){let J=typeof W==="object"?JSON.stringify(W):W,Z=`Property "${$}" must be of type "${f}", "${J}" of type "${typeof W}" given.`;return new f1(Z)}static required($){return new f1(`Property "${$}" is required`)}};xM=class xM extends w1{given;name="InvalidFieldConfigException";code=400;constructor($,f,W){console.error("InvalidFieldConfigException",{given:f,error:W.first()});super(`Invalid Field config given for field "${$.name}": ${W.firstToString()}`);this.given=f}};_M=class _M extends w1{name="EntityNotDefinedException";code=400;constructor($){if(!$)super("Cannot find an entity that is undefined");else super(`Entity "${typeof $!=="string"?$.name:$}" not defined`)}};Tp=class Tp extends w1{name="EntityNotFoundException";code=404;constructor($,f){super(`Entity "${typeof $!=="string"?$.name:$}" with id "${f}" not found`)}}});var fB,WB,JB,ZB,XB,zB,T9,wB,GB,YB,LB,g8;var PZ=K(()=>{_();M2();fB=class fB extends s0{static slug="mutator-insert-before";validate($){let{entity:f}=this.params;if(!f.isValidData($,"create"))throw A.warn("MutatorInsertBefore.validate: invalid",{entity:f.name,data:$}),new L9("EntityData","invalid");return this.clone({entity:f,data:$})}};WB=class WB extends s0{static slug="mutator-insert-after"};JB=class JB extends s0{static slug="mutator-update-before";validate($){let{entity:f,entityId:W}=this.params;if(!f.isValidData($,"update"))throw A.warn("MutatorUpdateBefore.validate: invalid",{entity:f.name,entityId:W,data:$}),new L9("EntityData","invalid");return this.clone({entityId:W,entity:f,data:$})}};ZB=class ZB extends s0{static slug="mutator-update-after"};XB=class XB extends s0{static slug="mutator-delete-before"};zB=class zB extends s0{static slug="mutator-delete-after"};T9={MutatorInsertBefore:fB,MutatorInsertAfter:WB,MutatorUpdateBefore:JB,MutatorUpdateAfter:ZB,MutatorDeleteBefore:XB,MutatorDeleteAfter:zB};wB=class wB extends s0{static slug="repository-find-one-before"};GB=class GB extends s0{static slug="repository-find-one-after"};YB=class YB extends s0{static slug="repository-find-many-before";static another="one"};LB=class LB extends s0{static slug="repository-find-many-after"};g8={RepositoryFindOneBefore:wB,RepositoryFindOneAfter:GB,RepositoryFindManyBefore:YB,RepositoryFindManyAfter:LB}});class NM{_relations=[];constructor($){this._relations=$}get all(){return this._relations}exists($){return this._relations.some((f)=>f.source.entity.name===$.source.entity.name&&f.target.entity.name===$.target.entity.name&&f.type===$.type)}relationsOf($){return this._relations.filter((f)=>{return f.visibleFrom("source")&&f.source.entity.name===$.name||f.visibleFrom("target")&&f.target.entity.name===$.name})}sourceRelationsOf($){return this._relations.filter((f)=>{return f.source.entity.name===$.name})}targetRelationsOf($){return this._relations.filter((f)=>{return f.visibleFrom("target")&&f.target.entity.name===$.name})}listableRelationsOf($){return this.relationsOf($).filter((f)=>f.isListableFor($))}relationOf($,f){return this.relationsOf($).find((W)=>{return W.target.entity.name===$.name&&W.source.reference===f||W.source.entity.name===$.name&&W.target.reference===f})}hasRelations($){return this.relationsOf($).length>0}relatedEntitiesOf($){return this.relationsOf($).map((f)=>f.other($).entity)}relationReferencesOf($){return this.relationsOf($).map((f)=>f.other($).reference)}}class a0{_required;_type;name;type="field";config;constructor($,f){this.name=$,this._type,this._required;try{this.config=F0(this.getSchema(),f||{})}catch(W){if(W instanceof G9)throw new xM(this,f,W);throw W}}getType(){return this.type}schema(){return Object.freeze({name:this.name,type:"text",nullable:!0,dflt:void 0})}hasDefault(){return this.config.default_value!==void 0}getDefault(){return this.config?.default_value}isFillable($){if(Array.isArray(this.config.fillable))return $?this.config.fillable.includes($):KB;return this.config.fillable??KB}isHidden($){if(Array.isArray(this.config.hidden))return $?this.config.hidden.includes($):HB;return this.config.hidden??HB}isRequired(){return this.config?.required??!1}isVirtual(){return this.config.virtual??!1}getLabel($){return this.config.label?this.config.label:$?.fallback!==!1?G4(this.name):void 0}getDescription(){return this.config.description}getValue($,f){return $}getHtmlConfig(){return{element:"input",props:{type:"text"}}}isValid($,f){if(typeof $!=="undefined")return this.isFillable(f);else if(f==="create")return!this.isRequired();return!0}transformRetrieve($){return $}async transformPersist($,f,W){if(this.nullish($)){if(this.isRequired()&&!this.hasDefault())throw f1.required(this.name);return this.getDefault()}return $}toSchemaWrapIfRequired($){return this.isRequired()?$:$.optional()}nullish($){return $===null||$===void 0}toJsonSchema(){return this.toSchemaWrapIfRequired(R.any())}toType(){return{required:this.isRequired(),comment:this.getDescription(),type:"any"}}toJSON(){return{type:this.type,config:this.config}}}var Pp,Cp,KB=!0,HB=!1,X1;var p$=K(()=>{B$();_();Pp=["create","read","update","delete"],Cp=["create","read","update","delete","form","table","submit"],X1=R.strictObject({label:R.string(),description:R.string(),required:R.boolean({default:!1}),fillable:R.anyOf([R.boolean({title:"Boolean"}),R.array(R.string({enum:Pp}),{title:"Context",uniqueItems:!0})]),hidden:R.anyOf([R.boolean({title:"Boolean"}),R.array(R.string({enum:Cp}),{title:"Context",uniqueItems:!0})]),virtual:R.boolean(),default_value:R.any()}).partial()});var SM,CZ;var UB=K(()=>{_();B$();p$();_();SM=R.strictObject({default_value:R.boolean(),...s1(X1.properties,["default_value"])}).partial();CZ=class CZ extends a0{type="boolean";getSchema(){return SM}getValue($,f){switch(f){case"table":return $?"Yes":"No";default:return $}}schema(){return Object.freeze({...super.schema(),type:"boolean"})}getHtmlConfig(){return{...super.getHtmlConfig(),element:"boolean"}}transformRetrieve($){if(typeof $==="undefined"||$===null){if(this.isRequired())return!1;if(this.hasDefault())return this.getDefault();return null}if(typeof $==="string")return $==="1";return!!$}async transformPersist($,f,W){let J=await super.transformPersist($,f,W);if(this.nullish(J))return this.isRequired()?Boolean(this.config.default_value):void 0;if(typeof J==="number")return J!==0;if(typeof J!=="boolean")throw f1.invalidType(this.name,"boolean",J);return J}toJsonSchema(){return this.toSchemaWrapIfRequired(R.boolean({default:this.getDefault()}))}toType(){return{...super.toType(),type:"boolean"}}}});var FM,b8;var RB=K(()=>{_();p$();_();_();FM=R.strictObject({type:R.string({enum:["date","datetime","week"],default:"date"}),timezone:R.string(),min_date:R.string(),max_date:R.string(),...X1.properties}).partial();b8=class b8 extends a0{type="date";getSchema(){return FM}schema(){return Object.freeze({...super.schema(),type:this.config.type==="datetime"?"datetime":"date"})}getHtmlConfig(){let $=this.config.type==="datetime"?"datetime-local":this.config.type;return{...super.getHtmlConfig(),element:"date",props:{type:$}}}parseDateFromString($){if(this.config.type==="week"&&$.includes("-W")){let[f,W]=$.split("-W").map((J)=>Number.parseInt(J,10));return s5.default().year(f).week(W).toDate()}return new Date($)}getValue($,f){if($===null||!$)return;let W=this.parseDateFromString($);if(f==="submit")try{return W.toISOString()}catch(J){return}if(this.config.type==="week")try{return`${W.getFullYear()}-W${s5.default(W).week()}`}catch(J){A.warn("DateField.getValue:week error",$,String(J));return}try{let Z=new Date().getTimezoneOffset(),X=new Date(W.getTime()-Z*60000);return this.formatDate(X)}catch(J){A.warn("DateField.getValue error",this.config.type,$,String(J));return}}formatDate($){switch(this.config.type){case"datetime":return $.toISOString().split(".")[0].replace("T"," ");default:return $.toISOString().split("T")[0]}}transformRetrieve($){let f=super.transformRetrieve($);if(f===null)return null;try{return new Date(f)}catch(W){return null}}async transformPersist($,f,W){let J=await super.transformPersist($,f,W);if(this.nullish(J))return J;switch(this.config.type){case"date":case"week":return new Date(J).toISOString().split("T")[0];default:return new Date(J).toISOString()}}toJsonSchema(){return this.toSchemaWrapIfRequired(R.string({default:this.getDefault()}))}toType(){return{...super.toType(),type:"Date | string"}}}});var BM,EZ;var MB=K(()=>{_();B$();p$();_();BM=R.strictObject({default_value:R.string(),options:R.anyOf([R.object({type:R.literal("strings"),values:R.array(R.string())}),R.object({type:R.literal("objects"),values:R.array(R.object({label:R.string(),value:R.string()}))})]),...s1(X1.properties,["default_value"])}).partial();EZ=class EZ extends a0{type="enum";constructor($,f){super($,f);if(this.config.default_value&&!this.isValidValue(this.config.default_value))throw new Error(`Default value "${this.config.default_value}" is not a valid option`)}getSchema(){return BM}getOptions(){let $=this.config?.options??{type:"strings",values:[]};if($.type==="strings")return $.values?.map((f)=>({label:f,value:f}));return $?.values}isValidValue($){return this.getOptions().map((W)=>W.value).includes($)}getValue($,f){if(!this.isValidValue($))return this.hasDefault()?this.getDefault():null;switch(f){case"table":return this.getOptions().find((W)=>W.value===$)?.label??$}return $}transformRetrieve($){let f=super.transformRetrieve($);if(f===null&&this.hasDefault())return this.getDefault();if(!this.isValidValue(f))return this.hasDefault()?this.getDefault():null;return f}async transformPersist($,f,W){let J=await super.transformPersist($,f,W);if(this.nullish(J))return J;if(!this.isValidValue(J))throw new f1(`Field "${this.name}" must be one of the following values: ${this.getOptions().map((Z)=>Z.value).join(", ")}`);return J}toJsonSchema(){let f=(this.config?.options??{type:"strings",values:[]}).values?.map((W)=>typeof W==="string"?W:W.value)??[];return this.toSchemaWrapIfRequired(R.string({enum:f,default:this.getDefault()}))}toType(){let $=this.getOptions().map(({value:f})=>typeof f==="string"?`"${f}"`:f);return{...super.toType(),type:$.length>0?$.join(" | "):"string"}}}});var TM,hZ;var qB=K(()=>{_();B$();p$();_();TM=R.strictObject({default_value:R.any(),...s1(X1.properties,["default_value"])}).partial();hZ=class hZ extends a0{type="json";getSchema(){return TM}transformRetrieve($){let f=super.transformRetrieve($);if(f===null&&this.hasDefault())return this.getDefault();if(this.isSerialized(f))return JSON.parse(f);return f}isSerializable($){try{let f=JSON.stringify($);if(f===JSON.stringify(JSON.parse(f)))return!0}catch(f){}return!1}isSerialized($){try{if(typeof $==="string")return $===JSON.stringify(JSON.parse($))}catch(f){}return!1}getValue($,f){switch(f){case"form":if($===null)return"";return JSON.stringify($,null,2);case"table":if($===null)return null;return JSON.stringify($);case"submit":if(typeof $==="string"&&$.length===0)return null;return JSON.parse($)}return $}async transformPersist($,f,W){let J=await super.transformPersist($,f,W);if(this.nullish(J))return J;if(!this.isSerializable(J))throw new f1(`Field "${this.name}" must be serializable to JSON.`);if(this.isSerialized(J))return J;return JSON.stringify(J)}toType(){return{...super.toType(),type:"any"}}}});function u8($,f){let W=typeof $;if(W!==typeof f)return!1;if(Array.isArray($)){if(!Array.isArray(f))return!1;let J=$.length;if(J!==f.length)return!1;for(let Z=0;Z<J;Z++)if(!u8($[Z],f[Z]))return!1;return!0}if(W==="object"){if(!$||!f)return $===f;let J=Object.keys($),Z=Object.keys(f);if(J.length!==Z.length)return!1;for(let z of J)if(!u8($[z],f[z]))return!1;return!0}return $===f}function n$($){return encodeURI(Ep($))}function Ep($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}function P9($,f=Object.create(null),W=mp,J=""){if($&&typeof $==="object"&&!Array.isArray($)){let X=$.$id||$.id;if(X){let z=new URL(X,W.href);if(z.hash.length>1)f[z.href]=$;else if(z.hash="",J==="")W=z;else P9($,f,W)}}else if($!==!0&&$!==!1)return f;let Z=W.href+(J?"#"+J:"");if(f[Z]!==void 0)throw new Error(`Duplicate schema URI "${Z}".`);if(f[Z]=$,$===!0||$===!1)return f;if($.__absolute_uri__===void 0)Object.defineProperty($,"__absolute_uri__",{enumerable:!1,value:Z});if($.$ref&&$.__absolute_ref__===void 0){let X=new URL($.$ref,W.href);X.hash=X.hash,Object.defineProperty($,"__absolute_ref__",{enumerable:!1,value:X.href})}if($.$recursiveRef&&$.__absolute_recursive_ref__===void 0){let X=new URL($.$recursiveRef,W.href);X.hash=X.hash,Object.defineProperty($,"__absolute_recursive_ref__",{enumerable:!1,value:X.href})}if($.$anchor){let X=new URL("#"+$.$anchor,W.href);f[X.href]=$}for(let X in $){if(vp[X])continue;let z=`${J}/${n$(X)}`,w=$[X];if(Array.isArray(w)){if(hp[X]){let G=w.length;for(let Y=0;Y<G;Y++)P9(w[Y],f,W,`${z}/${Y}`)}}else if(Dp[X])for(let G in w)P9(w[G],f,W,`${z}/${n$(G)}`);else P9(w,f,W,z)}return f}var hp,Dp,vp,mp;var Aw=K(()=>{hp={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Dp={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},vp={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},mp=typeof self!=="undefined"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")});function P2($){return $.test.bind($)}function ap($){return $%4===0&&($%100!==0||$%400===0)}function VB($){let f=$.match(kp);if(!f)return!1;let W=+f[1],J=+f[2],Z=+f[3];return J>=1&&J<=12&&Z>=1&&Z<=(J==2&&ap(W)?29:yp[J])}function QB($,f){let W=f.match(jp);if(!W)return!1;let J=+W[1],Z=+W[2],X=+W[3],z=!!W[5];return(J<=23&&Z<=59&&X<=59||J==23&&Z==59&&X==60)&&(!$||z)}function ep($){let f=$.split(op);return f.length==2&&VB(f[0])&&QB(!0,f[1])}function Wn($){return $n.test($)&&fn.test($)}function Zn($){if(Jn.test($))return!1;try{return new RegExp($,"u"),!0}catch(f){return!1}}var kp,yp,jp,gp,bp,up,cp,dp,ip,rp,lp,pp=($)=>{if($[0]==='"')return!1;let[f,W,...J]=$.split("@");if(!f||!W||J.length!==0||f.length>64||W.length>253)return!1;if(f[0]==="."||f.endsWith(".")||f.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(W)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(f))return!1;return W.split(".").every((Z)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(Z))},np,sp,tp=($)=>$.length>1&&$.length<80&&(/^P\d+([.,]\d+)?W$/.test($)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test($)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test($)),PM,op,$n,fn,Jn;var CM=K(()=>{kp=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,yp=[0,31,28,31,30,31,30,31,31,30,31,30,31],jp=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,gp=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,bp=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,up=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,cp=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,dp=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,ip=/^(?:\/(?:[^~/]|~0|~1)*)*$/,rp=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,lp=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,np=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,sp=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i;PM={date:VB,time:QB.bind(void 0,!1),"date-time":ep,duration:tp,uri:Wn,"uri-reference":P2(bp),"uri-template":P2(up),url:P2(cp),email:pp,hostname:P2(gp),ipv4:P2(np),ipv6:P2(sp),regex:Zn,uuid:P2(dp),"json-pointer":P2(ip),"json-pointer-uri-fragment":P2(rp),"relative-json-pointer":P2(lp)};op=/t|\s/i;$n=/\/|:/,fn=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;Jn=/[^\\]\\Z/});var IB;var OB=K(()=>{(function($){$[$.Flag=1]="Flag",$[$.Basic=2]="Basic",$[$.Detailed=4]="Detailed"})(IB||(IB={}))});function AB($){let f=0,W=$.length,J=0,Z;while(J<W)if(f++,Z=$.charCodeAt(J++),Z>=55296&&Z<=56319&&J<W){if(Z=$.charCodeAt(J),(Z&64512)==56320)J++}return f}function o0($,f,W="2019-09",J=P9(f),Z=!0,X=null,z="#",w="#",G=Object.create(null)){if(f===!0)return{valid:!0,errors:[]};if(f===!1)return{valid:!1,errors:[{instanceLocation:z,keyword:"false",keywordLocation:z,error:"False boolean schema."}]};let Y=typeof $,L;switch(Y){case"boolean":case"number":case"string":L=Y;break;case"object":if($===null)L="null";else if(Array.isArray($))L="array";else L="object";break;default:throw new Error(`Instances of "${Y}" type are not supported.`)}let{$ref:U,$recursiveRef:M,$recursiveAnchor:q,type:V,const:Q,enum:O,required:x,not:y,anyOf:F,allOf:B,oneOf:i,if:w0,then:L0,else:K0,format:j,properties:y1,patternProperties:L2,additionalProperties:n,unevaluatedProperties:D,minProperties:P,maxProperties:c,propertyNames:h,dependentRequired:e,dependentSchemas:$0,dependencies:x0,prefixItems:d0,items:p0,additionalItems:M1,unevaluatedItems:G$,contains:$9,minContains:j1,maxContains:K2,minItems:Pf,maxItems:B1,uniqueItems:H2,minimum:k$,maximum:Zf,exclusiveMinimum:NJ,exclusiveMaximum:SJ,multipleOf:lX,minLength:pX,maxLength:nX,pattern:mx,__absolute_ref__:sX,__absolute_recursive_ref__:Hd}=f,v=[];if(q===!0&&X===null)X=f;if(M==="#"){let t=X===null?J[Hd]:X,r=`${w}/$recursiveRef`,f0=o0($,X===null?f:X,W,J,Z,t,z,r,G);if(!f0.valid)v.push({instanceLocation:z,keyword:"$recursiveRef",keywordLocation:r,error:"A subschema had errors."},...f0.errors)}if(U!==void 0){let r=J[sX||U];if(r===void 0){let C=`Unresolved $ref "${U}".`;if(sX&&sX!==U)C+=` Absolute URI "${sX}".`;throw C+=`
Known schemas:
- ${Object.keys(J).join(`
- `)}`,new Error(C)}let f0=`${w}/$ref`,m=o0($,r,W,J,Z,X,z,f0,G);if(!m.valid)v.push({instanceLocation:z,keyword:"$ref",keywordLocation:f0,error:"A subschema had errors."},...m.errors);if(W==="4"||W==="7")return{valid:v.length===0,errors:v}}if(Array.isArray(V)){let t=V.length,r=!1;for(let f0=0;f0<t;f0++)if(L===V[f0]||V[f0]==="integer"&&L==="number"&&$%1===0&&$===$){r=!0;break}if(!r)v.push({instanceLocation:z,keyword:"type",keywordLocation:`${w}/type`,error:`Instance type "${L}" is invalid. Expected "${V.join('", "')}".`})}else if(V==="integer"){if(L!=="number"||$%1||$!==$)v.push({instanceLocation:z,keyword:"type",keywordLocation:`${w}/type`,error:`Instance type "${L}" is invalid. Expected "${V}".`})}else if(V!==void 0&&L!==V)v.push({instanceLocation:z,keyword:"type",keywordLocation:`${w}/type`,error:`Instance type "${L}" is invalid. Expected "${V}".`});if(Q!==void 0){if(L==="object"||L==="array"){if(!u8($,Q))v.push({instanceLocation:z,keyword:"const",keywordLocation:`${w}/const`,error:`Instance does not match ${JSON.stringify(Q)}.`})}else if($!==Q)v.push({instanceLocation:z,keyword:"const",keywordLocation:`${w}/const`,error:`Instance does not match ${JSON.stringify(Q)}.`})}if(O!==void 0){if(L==="object"||L==="array"){if(!O.some((t)=>u8($,t)))v.push({instanceLocation:z,keyword:"enum",keywordLocation:`${w}/enum`,error:`Instance does not match any of ${JSON.stringify(O)}.`})}else if(!O.some((t)=>$===t))v.push({instanceLocation:z,keyword:"enum",keywordLocation:`${w}/enum`,error:`Instance does not match any of ${JSON.stringify(O)}.`})}if(y!==void 0){let t=`${w}/not`;if(o0($,y,W,J,Z,X,z,t).valid)v.push({instanceLocation:z,keyword:"not",keywordLocation:t,error:'Instance matched "not" schema.'})}let tX=[];if(F!==void 0){let t=`${w}/anyOf`,r=v.length,f0=!1;for(let m=0;m<F.length;m++){let C=F[m],o=Object.create(G),a=o0($,C,W,J,Z,q===!0?X:null,z,`${t}/${m}`,o);if(v.push(...a.errors),f0=f0||a.valid,a.valid)tX.push(o)}if(f0)v.length=r;else v.splice(r,0,{instanceLocation:z,keyword:"anyOf",keywordLocation:t,error:"Instance does not match any subschemas."})}if(B!==void 0){let t=`${w}/allOf`,r=v.length,f0=!0;for(let m=0;m<B.length;m++){let C=B[m],o=Object.create(G),a=o0($,C,W,J,Z,q===!0?X:null,z,`${t}/${m}`,o);if(v.push(...a.errors),f0=f0&&a.valid,a.valid)tX.push(o)}if(f0)v.length=r;else v.splice(r,0,{instanceLocation:z,keyword:"allOf",keywordLocation:t,error:"Instance does not match every subschema."})}if(i!==void 0){let t=`${w}/oneOf`,r=v.length,f0=i.filter((m,C)=>{let o=Object.create(G),a=o0($,m,W,J,Z,q===!0?X:null,z,`${t}/${C}`,o);if(v.push(...a.errors),a.valid)tX.push(o);return a.valid}).length;if(f0===1)v.length=r;else v.splice(r,0,{instanceLocation:z,keyword:"oneOf",keywordLocation:t,error:`Instance does not match exactly one subschema (${f0} matches).`})}if(L==="object"||L==="array")Object.assign(G,...tX);if(w0!==void 0){let t=`${w}/if`;if(o0($,w0,W,J,Z,X,z,t,G).valid){if(L0!==void 0){let f0=o0($,L0,W,J,Z,X,z,`${w}/then`,G);if(!f0.valid)v.push({instanceLocation:z,keyword:"if",keywordLocation:t,error:'Instance does not match "then" schema.'},...f0.errors)}}else if(K0!==void 0){let f0=o0($,K0,W,J,Z,X,z,`${w}/else`,G);if(!f0.valid)v.push({instanceLocation:z,keyword:"if",keywordLocation:t,error:'Instance does not match "else" schema.'},...f0.errors)}}if(L==="object"){if(x!==void 0){for(let m of x)if(!(m in $))v.push({instanceLocation:z,keyword:"required",keywordLocation:`${w}/required`,error:`Instance does not have required property "${m}".`})}let t=Object.keys($);if(P!==void 0&&t.length<P)v.push({instanceLocation:z,keyword:"minProperties",keywordLocation:`${w}/minProperties`,error:`Instance does not have at least ${P} properties.`});if(c!==void 0&&t.length>c)v.push({instanceLocation:z,keyword:"maxProperties",keywordLocation:`${w}/maxProperties`,error:`Instance does not have at least ${c} properties.`});if(h!==void 0){let m=`${w}/propertyNames`;for(let C in $){let o=`${z}/${n$(C)}`,a=o0(C,h,W,J,Z,X,o,m);if(!a.valid)v.push({instanceLocation:z,keyword:"propertyNames",keywordLocation:m,error:`Property name "${C}" does not match schema.`},...a.errors)}}if(e!==void 0){let m=`${w}/dependantRequired`;for(let C in e)if(C in $){let o=e[C];for(let a of o)if(!(a in $))v.push({instanceLocation:z,keyword:"dependentRequired",keywordLocation:m,error:`Instance has "${C}" but does not have "${a}".`})}}if($0!==void 0)for(let m in $0){let C=`${w}/dependentSchemas`;if(m in $){let o=o0($,$0[m],W,J,Z,X,z,`${C}/${n$(m)}`,G);if(!o.valid)v.push({instanceLocation:z,keyword:"dependentSchemas",keywordLocation:C,error:`Instance has "${m}" but does not match dependant schema.`},...o.errors)}}if(x0!==void 0){let m=`${w}/dependencies`;for(let C in x0)if(C in $){let o=x0[C];if(Array.isArray(o)){for(let a of o)if(!(a in $))v.push({instanceLocation:z,keyword:"dependencies",keywordLocation:m,error:`Instance has "${C}" but does not have "${a}".`})}else{let a=o0($,o,W,J,Z,X,z,`${m}/${n$(C)}`);if(!a.valid)v.push({instanceLocation:z,keyword:"dependencies",keywordLocation:m,error:`Instance has "${C}" but does not match dependant schema.`},...a.errors)}}}let r=Object.create(null),f0=!1;if(y1!==void 0){let m=`${w}/properties`;for(let C in y1){if(!(C in $))continue;let o=`${z}/${n$(C)}`,a=o0($[C],y1[C],W,J,Z,X,o,`${m}/${n$(C)}`);if(a.valid)G[C]=r[C]=!0;else if(f0=Z,v.push({instanceLocation:z,keyword:"properties",keywordLocation:m,error:`Property "${C}" does not match schema.`},...a.errors),f0)break}}if(!f0&&L2!==void 0){let m=`${w}/patternProperties`;for(let C in L2){let o=new RegExp(C,"u"),a=L2[C];for(let q$ in $){if(!o.test(q$))continue;let kx=`${z}/${n$(q$)}`,yx=o0($[q$],a,W,J,Z,X,kx,`${m}/${n$(C)}`);if(yx.valid)G[q$]=r[q$]=!0;else f0=Z,v.push({instanceLocation:z,keyword:"patternProperties",keywordLocation:m,error:`Property "${q$}" matches pattern "${C}" but does not match associated schema.`},...yx.errors)}}}if(!f0&&n!==void 0){let m=`${w}/additionalProperties`;for(let C in $){if(r[C])continue;let o=`${z}/${n$(C)}`,a=o0($[C],n,W,J,Z,X,o,m);if(a.valid)G[C]=!0;else f0=Z,v.push({instanceLocation:z,keyword:"additionalProperties",keywordLocation:m,error:`Property "${C}" does not match additional properties schema.`},...a.errors)}}else if(!f0&&D!==void 0){let m=`${w}/unevaluatedProperties`;for(let C in $)if(!G[C]){let o=`${z}/${n$(C)}`,a=o0($[C],D,W,J,Z,X,o,m);if(a.valid)G[C]=!0;else v.push({instanceLocation:z,keyword:"unevaluatedProperties",keywordLocation:m,error:`Property "${C}" does not match unevaluated properties schema.`},...a.errors)}}}else if(L==="array"){if(B1!==void 0&&$.length>B1)v.push({instanceLocation:z,keyword:"maxItems",keywordLocation:`${w}/maxItems`,error:`Array has too many items (${$.length} > ${B1}).`});if(Pf!==void 0&&$.length<Pf)v.push({instanceLocation:z,keyword:"minItems",keywordLocation:`${w}/minItems`,error:`Array has too few items (${$.length} < ${Pf}).`});let t=$.length,r=0,f0=!1;if(d0!==void 0){let m=`${w}/prefixItems`,C=Math.min(d0.length,t);for(;r<C;r++){let o=o0($[r],d0[r],W,J,Z,X,`${z}/${r}`,`${m}/${r}`);if(G[r]=!0,!o.valid){if(f0=Z,v.push({instanceLocation:z,keyword:"prefixItems",keywordLocation:m,error:"Items did not match schema."},...o.errors),f0)break}}}if(p0!==void 0){let m=`${w}/items`;if(Array.isArray(p0)){let C=Math.min(p0.length,t);for(;r<C;r++){let o=o0($[r],p0[r],W,J,Z,X,`${z}/${r}`,`${m}/${r}`);if(G[r]=!0,!o.valid){if(f0=Z,v.push({instanceLocation:z,keyword:"items",keywordLocation:m,error:"Items did not match schema."},...o.errors),f0)break}}}else for(;r<t;r++){let C=o0($[r],p0,W,J,Z,X,`${z}/${r}`,m);if(G[r]=!0,!C.valid){if(f0=Z,v.push({instanceLocation:z,keyword:"items",keywordLocation:m,error:"Items did not match schema."},...C.errors),f0)break}}if(!f0&&M1!==void 0){let C=`${w}/additionalItems`;for(;r<t;r++){let o=o0($[r],M1,W,J,Z,X,`${z}/${r}`,C);if(G[r]=!0,!o.valid)f0=Z,v.push({instanceLocation:z,keyword:"additionalItems",keywordLocation:C,error:"Items did not match additional items schema."},...o.errors)}}}if($9!==void 0)if(t===0&&j1===void 0)v.push({instanceLocation:z,keyword:"contains",keywordLocation:`${w}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(j1!==void 0&&t<j1)v.push({instanceLocation:z,keyword:"minContains",keywordLocation:`${w}/minContains`,error:`Array has less items (${t}) than minContains (${j1}).`});else{let m=`${w}/contains`,C=v.length,o=0;for(let a=0;a<t;a++){let q$=o0($[a],$9,W,J,Z,X,`${z}/${a}`,m);if(q$.valid)G[a]=!0,o++;else v.push(...q$.errors)}if(o>=(j1||0))v.length=C;if(j1===void 0&&K2===void 0&&o===0)v.splice(C,0,{instanceLocation:z,keyword:"contains",keywordLocation:m,error:"Array does not contain item matching schema."});else if(j1!==void 0&&o<j1)v.push({instanceLocation:z,keyword:"minContains",keywordLocation:`${w}/minContains`,error:`Array must contain at least ${j1} items matching schema. Only ${o} items were found.`});else if(K2!==void 0&&o>K2)v.push({instanceLocation:z,keyword:"maxContains",keywordLocation:`${w}/maxContains`,error:`Array may contain at most ${K2} items matching schema. ${o} items were found.`})}if(!f0&&G$!==void 0){let m=`${w}/unevaluatedItems`;for(r;r<t;r++){if(G[r])continue;let C=o0($[r],G$,W,J,Z,X,`${z}/${r}`,m);if(G[r]=!0,!C.valid)v.push({instanceLocation:z,keyword:"unevaluatedItems",keywordLocation:m,error:"Items did not match unevaluated items schema."},...C.errors)}}if(H2)for(let m=0;m<t;m++){let C=$[m],o=typeof C==="object"&&C!==null;for(let a=0;a<t;a++){if(m===a)continue;let q$=$[a];if(C===q$||o&&(typeof q$==="object"&&q$!==null)&&u8(C,q$))v.push({instanceLocation:z,keyword:"uniqueItems",keywordLocation:`${w}/uniqueItems`,error:`Duplicate items at indexes ${m} and ${a}.`}),m=Number.MAX_SAFE_INTEGER,a=Number.MAX_SAFE_INTEGER}}}else if(L==="number"){if(W==="4"){if(k$!==void 0&&(NJ===!0&&$<=k$||$<k$))v.push({instanceLocation:z,keyword:"minimum",keywordLocation:`${w}/minimum`,error:`${$} is less than ${NJ?"or equal to ":""} ${k$}.`});if(Zf!==void 0&&(SJ===!0&&$>=Zf||$>Zf))v.push({instanceLocation:z,keyword:"maximum",keywordLocation:`${w}/maximum`,error:`${$} is greater than ${SJ?"or equal to ":""} ${Zf}.`})}else{if(k$!==void 0&&$<k$)v.push({instanceLocation:z,keyword:"minimum",keywordLocation:`${w}/minimum`,error:`${$} is less than ${k$}.`});if(Zf!==void 0&&$>Zf)v.push({instanceLocation:z,keyword:"maximum",keywordLocation:`${w}/maximum`,error:`${$} is greater than ${Zf}.`});if(NJ!==void 0&&$<=NJ)v.push({instanceLocation:z,keyword:"exclusiveMinimum",keywordLocation:`${w}/exclusiveMinimum`,error:`${$} is less than ${NJ}.`});if(SJ!==void 0&&$>=SJ)v.push({instanceLocation:z,keyword:"exclusiveMaximum",keywordLocation:`${w}/exclusiveMaximum`,error:`${$} is greater than or equal to ${SJ}.`})}if(lX!==void 0){let t=$%lX;if(Math.abs(0-t)>=0.00000011920929&&Math.abs(lX-t)>=0.00000011920929)v.push({instanceLocation:z,keyword:"multipleOf",keywordLocation:`${w}/multipleOf`,error:`${$} is not a multiple of ${lX}.`})}}else if(L==="string"){let t=pX===void 0&&nX===void 0?0:AB($);if(pX!==void 0&&t<pX)v.push({instanceLocation:z,keyword:"minLength",keywordLocation:`${w}/minLength`,error:`String is too short (${t} < ${pX}).`});if(nX!==void 0&&t>nX)v.push({instanceLocation:z,keyword:"maxLength",keywordLocation:`${w}/maxLength`,error:`String is too long (${t} > ${nX}).`});if(mx!==void 0&&!new RegExp(mx,"u").test($))v.push({instanceLocation:z,keyword:"pattern",keywordLocation:`${w}/pattern`,error:"String does not match pattern."});if(j!==void 0&&PM[j]&&!PM[j]($))v.push({instanceLocation:z,keyword:"format",keywordLocation:`${w}/format`,error:`String does not match format "${j}".`})}return{valid:v.length===0,errors:v}}var EM=K(()=>{Aw();CM()});class hM{schema;draft;shortCircuit;lookup;constructor($,f="2019-09",W=!0){this.schema=$,this.draft=f,this.shortCircuit=W,this.lookup=P9($)}validate($){return o0($,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema($,f){if(f)$={...$,$id:f};P9($,this.lookup)}}var xB=K(()=>{Aw();EM()});var _B=K(()=>{Aw();CM();OB();EM();xB()});var DM,DZ;var NB=K(()=>{_B();_();B$();p$();_();DM=R.strictObject({schema:R.any({type:"object"}),ui_schema:R.any({type:"object"}),default_from_schema:R.boolean(),...X1.properties}).partial();DZ=class DZ extends a0{type="jsonschema";validator;constructor($,f){super($,f);this.validator=new hM({...this.getJsonSchema()})}getSchema(){return DM}getJsonSchema(){return this.config?.schema}getJsonUiSchema(){return this.config.ui_schema??{}}isValid($,f="update"){if(super.isValid($,f)){if(!this.isRequired()&&(!$||typeof $!=="object"))return!0;return this.validator.validate($).valid}return!1}getValue($,f){switch(f){case"form":if($===null)return"";return $;case"table":if($===null)return null;return JSON.stringify($);case"submit":break}return $}transformRetrieve($){let f=super.transformRetrieve($);if(f===null){if(this.config.default_from_schema)try{return R.fromSchema(this.getJsonSchema()).template()}catch(W){return null}else if(this.hasDefault())return this.getDefault()}return f}async transformPersist($,f,W){let J=await super.transformPersist($,f,W);if(this.nullish(J))return J;if(!this.isValid(J))throw new f1(this.name,J);if(!J||typeof J!=="object")return this.getDefault();return JSON.stringify(J)}toJsonSchema(){let $=this.getJsonSchema()??{type:"object"};return this.toSchemaWrapIfRequired(R.fromSchema({default:this.getDefault(),...$}))}toType(){return{...super.toType(),import:[{package:"json-schema-to-ts",name:"FromSchema"}],type:`FromSchema<${Gz(this.getJsonSchema(),2,1)}>`}}}});var vM,Z5;var SB=K(()=>{B$();p$();_();_();vM=R.strictObject({default_value:R.number(),minimum:R.number(),maximum:R.number(),exclusiveMinimum:R.number(),exclusiveMaximum:R.number(),multipleOf:R.number(),...s1(X1.properties,["default_value"])}).partial();Z5=class Z5 extends a0{type="number";getSchema(){return vM}getHtmlConfig(){return{element:"input",props:{type:"number",pattern:"d*",inputMode:"numeric"}}}schema(){return Object.freeze({...super.schema(),type:"integer"})}getValue($,f){if(typeof $==="undefined"||$===null)return null;switch(f){case"submit":return Number.parseInt($)}return $}async transformPersist($,f,W){let J=await super.transformPersist($,f,W);if(!this.nullish(J)&&typeof J!=="number")throw f1.invalidType(this.name,"number",J);if(this.config.maximum&&J>this.config.maximum)throw new f1(`Field "${this.name}" cannot be greater than ${this.config.maximum}`);if(this.config.minimum&&J<this.config.minimum)throw new f1(`Field "${this.name}" cannot be less than ${this.config.minimum}`);return J}toJsonSchema(){return this.toSchemaWrapIfRequired(R.number({default:this.getDefault(),minimum:this.config?.minimum,maximum:this.config?.maximum,exclusiveMinimum:this.config?.exclusiveMinimum,exclusiveMaximum:this.config?.exclusiveMaximum,multipleOf:this.config?.multipleOf}))}toType(){return{...super.toType(),type:"number"}}}});var pf;var vZ=K(()=>{pf={server:{default_port:1337,assets_path:"/"},data:{default_primary_field:"id"}}});var mZ,mM,C2;var kM=K(()=>{vZ();_();p$();mZ=["integer","uuid"],mM=R.strictObject({format:R.string({enum:mZ,default:"integer"}),required:R.boolean({default:!1}),...s1(X1.properties,["required"])}).partial();C2=class C2 extends a0{type="primary";constructor($=pf.data.default_primary_field,f){super($,{...f,fillable:!1,required:!1})}isRequired(){return!1}getSchema(){return mM}get format(){return this.config.format??"integer"}get fieldType(){return this.format==="integer"?"integer":"text"}schema(){return Object.freeze({type:this.fieldType,name:this.name,primary:!0,nullable:!1})}getNewValue(){if(this.format==="uuid")return $N();return}async transformPersist($){throw new Error("PrimaryField: This function should not be called")}toJsonSchema(){return this.toSchemaWrapIfRequired(this.format==="integer"?R.number({writeOnly:void 0}):R.string({writeOnly:void 0}))}toType(){let $=this.format==="integer"?"number":"string";return{...super.toType(),required:!0,import:[{package:"kysely",name:"Generated"}],type:`Generated<${$}>`}}}});var yM,X5;var FB=K(()=>{_();B$();p$();_();yM=R.strictObject({default_value:R.string(),minLength:R.number(),maxLength:R.number(),pattern:R.string(),html_config:R.partialObject({element:R.string(),props:R.record(R.anyOf([R.string({title:"String"}),R.number({title:"Number"})]))}),...s1(X1.properties,["default_value"])}).partial();X5=class X5 extends a0{type="text";getSchema(){return yM}getHtmlConfig(){if(this.config.html_config)return this.config.html_config;return super.getHtmlConfig()}transformRetrieve($){let f=super.transformRetrieve($);if(this.config.maxLength)return f.substring(0,this.config.maxLength);if(this.isRequired())return f?f.toString():"";return f}async transformPersist($,f,W){let J=await super.transformPersist($,f,W);if(this.nullish(J))return J;if(J!==null&&typeof J!=="string")J=String(J);if(this.config.maxLength&&J?.length>this.config.maxLength)throw new f1(`Field "${this.name}" must be at most ${this.config.maxLength} character(s)`);if(this.config.minLength&&J?.length<this.config.minLength)throw new f1(`Field "${this.name}" must be at least ${this.config.minLength} character(s)`);if(this.config.pattern&&J&&!new RegExp(this.config.pattern).test(J))throw new f1(`Field "${this.name}" must match the pattern ${this.config.pattern}`);return J}toJsonSchema(){return this.toSchemaWrapIfRequired(R.string({default:this.getDefault(),minLength:this.config?.minLength,maxLength:this.config?.maxLength,pattern:this.config?.pattern}))}toType(){return{...super.toType(),type:"string"}}}});var aS0;var BB=K(()=>{p$();_();aS0=R.strictObject({...X1.properties}).partial()});class kZ{entity;fields;unique;name;constructor($,f,W=!1,J){this.entity=$;this.fields=f;this.unique=W;this.name=J;if(f.length===0)throw new Error("Indices must contain at least one field");if(f.some((Z)=>!(Z instanceof a0)))throw new Error("All fields must be instances of Field");if(W){if(!f[0]?.isRequired())throw new Error(`Unique indices must have first field as required: ${f.map((X)=>X.name).join(", ")}`)}if(!J)this.name=[W?"idx_unique":"idx",$.name,...f.map((Z)=>Z.name)].join("_")}toJSON(){return{entity:this.entity.name,fields:this.fields.map(($)=>$.name),unique:this.unique}}}var TB=K(()=>{p$()});var Xn,xw;var jM=K(()=>{Xn=typeof global=="object"&&global&&global.Object===Object&&global,xw=Xn});var zn,wn,R1;var nf=K(()=>{jM();zn=typeof self=="object"&&self&&self.Object===Object&&self,wn=xw||zn||Function("return this")(),R1=wn});var Gn,h1;var z5=K(()=>{nf();Gn=R1.Symbol,h1=Gn});function Kn($){var f=Yn.call($,yZ),W=$[yZ];try{$[yZ]=void 0;var J=!0}catch(X){}var Z=Ln.call($);if(J)if(f)$[yZ]=W;else delete $[yZ];return Z}var PB,Yn,Ln,yZ,CB;var EB=K(()=>{z5();PB=Object.prototype,Yn=PB.hasOwnProperty,Ln=PB.toString,yZ=h1?h1.toStringTag:void 0;CB=Kn});function Rn($){return Un.call($)}var Hn,Un,hB;var DB=K(()=>{Hn=Object.prototype,Un=Hn.toString;hB=Rn});function Vn($){if($==null)return $===void 0?qn:Mn;return vB&&vB in Object($)?CB($):hB($)}var Mn="[object Null]",qn="[object Undefined]",vB,s$;var w5=K(()=>{z5();EB();DB();vB=h1?h1.toStringTag:void 0;s$=Vn});function Qn($){return $!=null&&typeof $=="object"}var _1;var E2=K(()=>{_1=Qn});function On($){return typeof $=="symbol"||_1($)&&s$($)==In}var In="[object Symbol]",c8;var _w=K(()=>{w5();E2();c8=On});function An($,f){var W=-1,J=$==null?0:$.length,Z=Array(J);while(++W<J)Z[W]=f($[W],W,$);return Z}var Nw;var gM=K(()=>{Nw=An});var xn,g0;var t$=K(()=>{xn=Array.isArray,g0=xn});function yB($){if(typeof $=="string")return $;if(g0($))return Nw($,yB)+"";if(c8($))return kB?kB.call($):"";var f=$+"";return f=="0"&&1/$==-_n?"-0":f}var _n=1/0,mB,kB,jB;var gB=K(()=>{z5();gM();t$();_w();mB=h1?h1.prototype:void 0,kB=mB?mB.toString:void 0;jB=yB});function Nn($){var f=typeof $;return $!=null&&(f=="object"||f=="function")}var W1;var Kf=K(()=>{W1=Nn});function Sn($){return $}var d8;var Sw=K(()=>{d8=Sn});function Cn($){if(!W1($))return!1;var f=s$($);return f==Bn||f==Tn||f==Fn||f==Pn}var Fn="[object AsyncFunction]",Bn="[object Function]",Tn="[object GeneratorFunction]",Pn="[object Proxy]",S4;var jZ=K(()=>{w5();Kf();S4=Cn});var En,Fw;var bB=K(()=>{nf();En=R1["__core-js_shared__"],Fw=En});function hn($){return!!uB&&uB in $}var uB,cB;var dB=K(()=>{bB();uB=function(){var $=/[^.]+$/.exec(Fw&&Fw.keys&&Fw.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}();cB=hn});function mn($){if($!=null){try{return vn.call($)}catch(f){}try{return $+""}catch(f){}}return""}var Dn,vn,C9;var bM=K(()=>{Dn=Function.prototype,vn=Dn.toString;C9=mn});function dn($){if(!W1($)||cB($))return!1;var f=S4($)?cn:yn;return f.test(C9($))}var kn,yn,jn,gn,bn,un,cn,iB;var rB=K(()=>{jZ();dB();Kf();bM();kn=/[\\^$.*+?()[\]{}|]/g,yn=/^\[object .+?Constructor\]$/,jn=Function.prototype,gn=Object.prototype,bn=jn.toString,un=gn.hasOwnProperty,cn=RegExp("^"+bn.call(un).replace(kn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");iB=dn});function rn($,f){return $==null?void 0:$[f]}var lB;var pB=K(()=>{lB=rn});function ln($,f){var W=lB($,f);return iB(W)?W:void 0}var T$;var F4=K(()=>{rB();pB();T$=ln});var pn,Bw;var nB=K(()=>{F4();nf();pn=T$(R1,"WeakMap"),Bw=pn});var sB,nn,Tw;var uM=K(()=>{Kf();sB=Object.create,nn=function(){function $(){}return function(f){if(!W1(f))return{};if(sB)return sB(f);$.prototype=f;var W=new $;return $.prototype=void 0,W}}(),Tw=nn});function sn($,f,W){switch(W.length){case 0:return $.call(f);case 1:return $.call(f,W[0]);case 2:return $.call(f,W[0],W[1]);case 3:return $.call(f,W[0],W[1],W[2])}return $.apply(f,W)}var tB;var aB=K(()=>{tB=sn});function tn($,f){var W=-1,J=$.length;f||(f=Array(J));while(++W<J)f[W]=$[W];return f}var Pw;var cM=K(()=>{Pw=tn});function $s($){var f=0,W=0;return function(){var J=en(),Z=on-(J-W);if(W=J,Z>0){if(++f>=an)return arguments[0]}else f=0;return $.apply(void 0,arguments)}}var an=800,on=16,en,oB;var eB=K(()=>{en=Date.now;oB=$s});function fs($){return function(){return $}}var $T;var fT=K(()=>{$T=fs});var Ws,i8;var dM=K(()=>{F4();Ws=function(){try{var $=T$(Object,"defineProperty");return $({},"",{}),$}catch(f){}}(),i8=Ws});var Js,WT;var JT=K(()=>{fT();dM();Sw();Js=!i8?d8:function($,f){return i8($,"toString",{configurable:!0,enumerable:!1,value:$T(f),writable:!0})},WT=Js});var Zs,Cw;var iM=K(()=>{JT();eB();Zs=oB(WT),Cw=Zs});function Xs($,f){var W=-1,J=$==null?0:$.length;while(++W<J)if(f($[W],W,$)===!1)break;return $}var Ew;var rM=K(()=>{Ew=Xs});function Gs($,f){var W=typeof $;return f=f==null?zs:f,!!f&&(W=="number"||W!="symbol"&&ws.test($))&&($>-1&&$%1==0&&$<f)}var zs=9007199254740991,ws,B4;var gZ=K(()=>{ws=/^(?:0|[1-9]\d*)$/;B4=Gs});function Ys($,f,W){if(f=="__proto__"&&i8)i8($,f,{configurable:!0,enumerable:!0,value:W,writable:!0});else $[f]=W}var r8;var hw=K(()=>{dM();r8=Ys});function Ls($,f){return $===f||$!==$&&f!==f}var h2;var l8=K(()=>{h2=Ls});function Us($,f,W){var J=$[f];if(!(Hs.call($,f)&&h2(J,W))||W===void 0&&!(f in $))r8($,f,W)}var Ks,Hs,p8;var Dw=K(()=>{hw();l8();Ks=Object.prototype,Hs=Ks.hasOwnProperty;p8=Us});function Rs($,f,W,J){var Z=!W;W||(W={});var X=-1,z=f.length;while(++X<z){var w=f[X],G=J?J(W[w],$[w],w,W,$):void 0;if(G===void 0)G=$[w];if(Z)r8(W,w,G);else p8(W,w,G)}return W}var Hf;var G5=K(()=>{Dw();hw();Hf=Rs});function Ms($,f,W){return f=ZT(f===void 0?$.length-1:f,0),function(){var J=arguments,Z=-1,X=ZT(J.length-f,0),z=Array(X);while(++Z<X)z[Z]=J[f+Z];Z=-1;var w=Array(f+1);while(++Z<f)w[Z]=J[Z];return w[f]=W(z),tB($,this,w)}}var ZT,vw;var lM=K(()=>{aB();ZT=Math.max;vw=Ms});function qs($,f){return Cw(vw($,f,d8),$+"")}var XT;var zT=K(()=>{Sw();lM();iM();XT=qs});function Qs($){return typeof $=="number"&&$>-1&&$%1==0&&$<=Vs}var Vs=9007199254740991,n8;var mw=K(()=>{n8=Qs});function Is($){return $!=null&&n8($.length)&&!S4($)}var T4;var bZ=K(()=>{jZ();mw();T4=Is});function Os($,f,W){if(!W1(W))return!1;var J=typeof f;if(J=="number"?T4(W)&&B4(f,W.length):J=="string"&&(f in W))return h2(W[f],$);return!1}var wT;var GT=K(()=>{l8();bZ();gZ();Kf();wT=Os});function As($){return XT(function(f,W){var J=-1,Z=W.length,X=Z>1?W[Z-1]:void 0,z=Z>2?W[2]:void 0;if(X=$.length>3&&typeof X=="function"?(Z--,X):void 0,z&&wT(W[0],W[1],z))X=Z<3?void 0:X,Z=1;f=Object(f);while(++J<Z){var w=W[J];if(w)$(f,w,J,X)}return f})}var YT;var LT=K(()=>{zT();GT();YT=As});function _s($){var f=$&&$.constructor,W=typeof f=="function"&&f.prototype||xs;return $===W}var xs,s8;var kw=K(()=>{xs=Object.prototype;s8=_s});function Ns($,f){var W=-1,J=Array($);while(++W<$)J[W]=f(W);return J}var KT;var HT=K(()=>{KT=Ns});function Fs($){return _1($)&&s$($)==Ss}var Ss="[object Arguments]",pM;var UT=K(()=>{w5();E2();pM=Fs});var RT,Bs,Ts,Ps,E9;var uZ=K(()=>{UT();E2();RT=Object.prototype,Bs=RT.hasOwnProperty,Ts=RT.propertyIsEnumerable,Ps=pM(function(){return arguments}())?pM:function($){return _1($)&&Bs.call($,"callee")&&!Ts.call($,"callee")},E9=Ps});function Cs(){return!1}var MT;var qT=K(()=>{MT=Cs});var jw={};V1(jw,{default:()=>Uf});var IT,VT,Es,QT,hs,Ds,Uf;var t8=K(()=>{nf();qT();IT=typeof jw=="object"&&jw&&!jw.nodeType&&jw,VT=IT&&typeof yw=="object"&&yw&&!yw.nodeType&&yw,Es=VT&&VT.exports===IT,QT=Es?R1.Buffer:void 0,hs=QT?QT.isBuffer:void 0,Ds=hs||MT,Uf=Ds});function Zt($){return _1($)&&n8($.length)&&!!r0[s$($)]}var vs="[object Arguments]",ms="[object Array]",ks="[object Boolean]",ys="[object Date]",js="[object Error]",gs="[object Function]",bs="[object Map]",us="[object Number]",cs="[object Object]",ds="[object RegExp]",is="[object Set]",rs="[object String]",ls="[object WeakMap]",ps="[object ArrayBuffer]",ns="[object DataView]",ss="[object Float32Array]",ts="[object Float64Array]",as="[object Int8Array]",os="[object Int16Array]",es="[object Int32Array]",$t="[object Uint8Array]",ft="[object Uint8ClampedArray]",Wt="[object Uint16Array]",Jt="[object Uint32Array]",r0,OT;var AT=K(()=>{w5();mw();E2();r0={};r0[ss]=r0[ts]=r0[as]=r0[os]=r0[es]=r0[$t]=r0[ft]=r0[Wt]=r0[Jt]=!0;r0[vs]=r0[ms]=r0[ps]=r0[ks]=r0[ns]=r0[ys]=r0[js]=r0[gs]=r0[bs]=r0[us]=r0[cs]=r0[ds]=r0[is]=r0[rs]=r0[ls]=!1;OT=Zt});function Xt($){return function(f){return $(f)}}var a8;var gw=K(()=>{a8=Xt});var uw={};V1(uw,{default:()=>D2});var xT,cZ,zt,nM,wt,D2;var cw=K(()=>{jM();xT=typeof uw=="object"&&uw&&!uw.nodeType&&uw,cZ=xT&&typeof bw=="object"&&bw&&!bw.nodeType&&bw,zt=cZ&&cZ.exports===xT,nM=zt&&xw.process,wt=function(){try{var $=cZ&&cZ.require&&cZ.require("util").types;if($)return $;return nM&&nM.binding&&nM.binding("util")}catch(f){}}(),D2=wt});var _T,Gt,P4;var dZ=K(()=>{AT();gw();cw();_T=D2&&D2.isTypedArray,Gt=_T?a8(_T):OT,P4=Gt});function Kt($,f){var W=g0($),J=!W&&E9($),Z=!W&&!J&&Uf($),X=!W&&!J&&!Z&&P4($),z=W||J||Z||X,w=z?KT($.length,String):[],G=w.length;for(var Y in $)if((f||Lt.call($,Y))&&!(z&&(Y=="length"||Z&&(Y=="offset"||Y=="parent")||X&&(Y=="buffer"||Y=="byteLength"||Y=="byteOffset")||B4(Y,G))))w.push(Y);return w}var Yt,Lt,dw;var sM=K(()=>{HT();uZ();t$();t8();gZ();dZ();Yt=Object.prototype,Lt=Yt.hasOwnProperty;dw=Kt});function Ht($,f){return function(W){return $(f(W))}}var iw;var tM=K(()=>{iw=Ht});var Ut,NT;var ST=K(()=>{tM();Ut=iw(Object.keys,Object),NT=Ut});function qt($){if(!s8($))return NT($);var f=[];for(var W in Object($))if(Mt.call($,W)&&W!="constructor")f.push(W);return f}var Rt,Mt,FT;var BT=K(()=>{kw();ST();Rt=Object.prototype,Mt=Rt.hasOwnProperty;FT=qt});function Vt($){return T4($)?dw($):FT($)}var v2;var o8=K(()=>{sM();BT();bZ();v2=Vt});function Qt($){var f=[];if($!=null)for(var W in Object($))f.push(W);return f}var TT;var PT=K(()=>{TT=Qt});function At($){if(!W1($))return TT($);var f=s8($),W=[];for(var J in $)if(!(J=="constructor"&&(f||!Ot.call($,J))))W.push(J);return W}var It,Ot,CT;var ET=K(()=>{Kf();kw();PT();It=Object.prototype,Ot=It.hasOwnProperty;CT=At});function xt($){return T4($)?dw($,!0):CT($)}var m2;var e8=K(()=>{sM();ET();bZ();m2=xt});function St($,f){if(g0($))return!1;var W=typeof $;if(W=="number"||W=="symbol"||W=="boolean"||$==null||c8($))return!0;return Nt.test($)||!_t.test($)||f!=null&&$ in Object(f)}var _t,Nt,$W;var rw=K(()=>{t$();_w();_t=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Nt=/^\w*$/;$W=St});var Ft,h9;var iZ=K(()=>{F4();Ft=T$(Object,"create"),h9=Ft});function Bt(){this.__data__=h9?h9(null):{},this.size=0}var hT;var DT=K(()=>{iZ();hT=Bt});function Tt($){var f=this.has($)&&delete this.__data__[$];return this.size-=f?1:0,f}var vT;var mT=K(()=>{vT=Tt});function ht($){var f=this.__data__;if(h9){var W=f[$];return W===Pt?void 0:W}return Et.call(f,$)?f[$]:void 0}var Pt="__lodash_hash_undefined__",Ct,Et,kT;var yT=K(()=>{iZ();Ct=Object.prototype,Et=Ct.hasOwnProperty;kT=ht});function mt($){var f=this.__data__;return h9?f[$]!==void 0:vt.call(f,$)}var Dt,vt,jT;var gT=K(()=>{iZ();Dt=Object.prototype,vt=Dt.hasOwnProperty;jT=mt});function yt($,f){var W=this.__data__;return this.size+=this.has($)?0:1,W[$]=h9&&f===void 0?kt:f,this}var kt="__lodash_hash_undefined__",bT;var uT=K(()=>{iZ();bT=yt});function fW($){var f=-1,W=$==null?0:$.length;this.clear();while(++f<W){var J=$[f];this.set(J[0],J[1])}}var aM;var cT=K(()=>{DT();mT();yT();gT();uT();fW.prototype.clear=hT;fW.prototype.delete=vT;fW.prototype.get=kT;fW.prototype.has=jT;fW.prototype.set=bT;aM=fW});function jt(){this.__data__=[],this.size=0}var dT;var iT=K(()=>{dT=jt});function gt($,f){var W=$.length;while(W--)if(h2($[W][0],f))return W;return-1}var C4;var rZ=K(()=>{l8();C4=gt});function ct($){var f=this.__data__,W=C4(f,$);if(W<0)return!1;var J=f.length-1;if(W==J)f.pop();else ut.call(f,W,1);return--this.size,!0}var bt,ut,rT;var lT=K(()=>{rZ();bt=Array.prototype,ut=bt.splice;rT=ct});function dt($){var f=this.__data__,W=C4(f,$);return W<0?void 0:f[W][1]}var pT;var nT=K(()=>{rZ();pT=dt});function it($){return C4(this.__data__,$)>-1}var sT;var tT=K(()=>{rZ();sT=it});function rt($,f){var W=this.__data__,J=C4(W,$);if(J<0)++this.size,W.push([$,f]);else W[J][1]=f;return this}var aT;var oT=K(()=>{rZ();aT=rt});function WW($){var f=-1,W=$==null?0:$.length;this.clear();while(++f<W){var J=$[f];this.set(J[0],J[1])}}var E4;var lZ=K(()=>{iT();lT();nT();tT();oT();WW.prototype.clear=dT;WW.prototype.delete=rT;WW.prototype.get=pT;WW.prototype.has=sT;WW.prototype.set=aT;E4=WW});var lt,h4;var lw=K(()=>{F4();nf();lt=T$(R1,"Map"),h4=lt});function pt(){this.size=0,this.__data__={hash:new aM,map:new(h4||E4),string:new aM}}var eT;var $P=K(()=>{cT();lZ();lw();eT=pt});function nt($){var f=typeof $;return f=="string"||f=="number"||f=="symbol"||f=="boolean"?$!=="__proto__":$===null}var fP;var WP=K(()=>{fP=nt});function st($,f){var W=$.__data__;return fP(f)?W[typeof f=="string"?"string":"hash"]:W.map}var D4;var pZ=K(()=>{WP();D4=st});function tt($){var f=D4(this,$).delete($);return this.size-=f?1:0,f}var JP;var ZP=K(()=>{pZ();JP=tt});function at($){return D4(this,$).get($)}var XP;var zP=K(()=>{pZ();XP=at});function ot($){return D4(this,$).has($)}var wP;var GP=K(()=>{pZ();wP=ot});function et($,f){var W=D4(this,$),J=W.size;return W.set($,f),this.size+=W.size==J?0:1,this}var YP;var LP=K(()=>{pZ();YP=et});function JW($){var f=-1,W=$==null?0:$.length;this.clear();while(++f<W){var J=$[f];this.set(J[0],J[1])}}var Y5;var pw=K(()=>{$P();ZP();zP();GP();LP();JW.prototype.clear=eT;JW.prototype.delete=JP;JW.prototype.get=XP;JW.prototype.has=wP;JW.prototype.set=YP;Y5=JW});function oM($,f){if(typeof $!="function"||f!=null&&typeof f!="function")throw new TypeError($a);var W=function(){var J=arguments,Z=f?f.apply(this,J):J[0],X=W.cache;if(X.has(Z))return X.get(Z);var z=$.apply(this,J);return W.cache=X.set(Z,z)||X,z};return W.cache=new(oM.Cache||Y5),W}var $a="Expected a function",KP;var HP=K(()=>{pw();oM.Cache=Y5;KP=oM});function Wa($){var f=KP($,function(J){if(W.size===fa)W.clear();return J}),W=f.cache;return f}var fa=500,UP;var RP=K(()=>{HP();UP=Wa});var Ja,Za,Xa,MP;var qP=K(()=>{RP();Ja=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Za=/\\(\\)?/g,Xa=UP(function($){var f=[];if($.charCodeAt(0)===46)f.push("");return $.replace(Ja,function(W,J,Z,X){f.push(Z?X.replace(Za,"$1"):J||W)}),f}),MP=Xa});function za($){return $==null?"":jB($)}var VP;var QP=K(()=>{gB();VP=za});function wa($,f){if(g0($))return $;return $W($,f)?[$]:MP(VP($))}var Rf;var L5=K(()=>{t$();rw();qP();QP();Rf=wa});function Ya($){if(typeof $=="string"||c8($))return $;var f=$+"";return f=="0"&&1/$==-Ga?"-0":f}var Ga=1/0,Mf;var K5=K(()=>{_w();Mf=Ya});function La($,f){f=Rf(f,$);var W=0,J=f.length;while($!=null&&W<J)$=$[Mf(f[W++])];return W&&W==J?$:void 0}var v4;var nZ=K(()=>{L5();K5();v4=La});function Ka($,f,W){var J=$==null?void 0:v4($,f);return J===void 0?W:J}var k2;var eM=K(()=>{nZ();k2=Ka});function Ha($,f){var W=-1,J=f.length,Z=$.length;while(++W<J)$[Z+W]=f[W];return $}var ZW;var nw=K(()=>{ZW=Ha});function Ua($){return g0($)||E9($)||!!(IP&&$&&$[IP])}var IP,OP;var AP=K(()=>{z5();uZ();t$();IP=h1?h1.isConcatSpreadable:void 0;OP=Ua});function xP($,f,W,J,Z){var X=-1,z=$.length;W||(W=OP),Z||(Z=[]);while(++X<z){var w=$[X];if(f>0&&W(w))if(f>1)xP(w,f-1,W,J,Z);else ZW(Z,w);else if(!J)Z[Z.length]=w}return Z}var _P;var NP=K(()=>{nw();AP();_P=xP});function Ra($){var f=$==null?0:$.length;return f?_P($,1):[]}var SP;var FP=K(()=>{NP();SP=Ra});function Ma($){return Cw(vw($,void 0,SP),$+"")}var sw;var $q=K(()=>{FP();lM();iM();sw=Ma});var qa,m4;var sZ=K(()=>{tM();qa=iw(Object.getPrototypeOf,Object),m4=qa});function xa($){if(!_1($)||s$($)!=Va)return!1;var f=m4($);if(f===null)return!0;var W=Oa.call(f,"constructor")&&f.constructor;return typeof W=="function"&&W instanceof W&&BP.call(W)==Aa}var Va="[object Object]",Qa,Ia,BP,Oa,Aa,tw;var fq=K(()=>{w5();sZ();E2();Qa=Function.prototype,Ia=Object.prototype,BP=Qa.toString,Oa=Ia.hasOwnProperty,Aa=BP.call(Object);tw=xa});function _a($,f,W){var J=-1,Z=$.length;if(f<0)f=-f>Z?0:Z+f;if(W=W>Z?Z:W,W<0)W+=Z;Z=f>W?0:W-f>>>0,f>>>=0;var X=Array(Z);while(++J<Z)X[J]=$[J+f];return X}var TP;var PP=K(()=>{TP=_a});function Na(){this.__data__=new E4,this.size=0}var CP;var EP=K(()=>{lZ();CP=Na});function Sa($){var f=this.__data__,W=f.delete($);return this.size=f.size,W}var hP;var DP=K(()=>{hP=Sa});function Fa($){return this.__data__.get($)}var vP;var mP=K(()=>{vP=Fa});function Ba($){return this.__data__.has($)}var kP;var yP=K(()=>{kP=Ba});function Pa($,f){var W=this.__data__;if(W instanceof E4){var J=W.__data__;if(!h4||J.length<Ta-1)return J.push([$,f]),this.size=++W.size,this;W=this.__data__=new Y5(J)}return W.set($,f),this.size=W.size,this}var Ta=200,jP;var gP=K(()=>{lZ();lw();pw();jP=Pa});function XW($){var f=this.__data__=new E4($);this.size=f.size}var y2;var tZ=K(()=>{lZ();EP();DP();mP();yP();gP();XW.prototype.clear=CP;XW.prototype.delete=hP;XW.prototype.get=vP;XW.prototype.has=kP;XW.prototype.set=jP;y2=XW});function Ca($,f){return $&&Hf(f,v2(f),$)}var bP;var uP=K(()=>{G5();o8();bP=Ca});function Ea($,f){return $&&Hf(f,m2(f),$)}var cP;var dP=K(()=>{G5();e8();cP=Ea});var ow={};V1(ow,{default:()=>aZ});function Da($,f){if(f)return $.slice();var W=$.length,J=lP?lP(W):new $.constructor(W);return $.copy(J),J}var pP,iP,ha,rP,lP,aZ;var Wq=K(()=>{nf();pP=typeof ow=="object"&&ow&&!ow.nodeType&&ow,iP=pP&&typeof aw=="object"&&aw&&!aw.nodeType&&aw,ha=iP&&iP.exports===pP,rP=ha?R1.Buffer:void 0,lP=rP?rP.allocUnsafe:void 0;aZ=Da});function va($,f){var W=-1,J=$==null?0:$.length,Z=0,X=[];while(++W<J){var z=$[W];if(f(z,W,$))X[Z++]=z}return X}var nP;var sP=K(()=>{nP=va});function ma(){return[]}var ew;var Jq=K(()=>{ew=ma});var ka,ya,tP,ja,zW;var $G=K(()=>{sP();Jq();ka=Object.prototype,ya=ka.propertyIsEnumerable,tP=Object.getOwnPropertySymbols,ja=!tP?ew:function($){if($==null)return[];return $=Object($),nP(tP($),function(f){return ya.call($,f)})},zW=ja});function ga($,f){return Hf($,zW($),f)}var aP;var oP=K(()=>{G5();$G();aP=ga});var ba,ua,fG;var Zq=K(()=>{nw();sZ();$G();Jq();ba=Object.getOwnPropertySymbols,ua=!ba?ew:function($){var f=[];while($)ZW(f,zW($)),$=m4($);return f},fG=ua});function ca($,f){return Hf($,fG($),f)}var eP;var $C=K(()=>{G5();Zq();eP=ca});function da($,f,W){var J=f($);return g0($)?J:ZW(J,W($))}var WG;var Xq=K(()=>{nw();t$();WG=da});function ia($){return WG($,v2,zW)}var oZ;var zq=K(()=>{Xq();$G();o8();oZ=ia});function ra($){return WG($,m2,fG)}var JG;var wq=K(()=>{Xq();Zq();e8();JG=ra});var la,ZG;var fC=K(()=>{F4();nf();la=T$(R1,"DataView"),ZG=la});var pa,XG;var WC=K(()=>{F4();nf();pa=T$(R1,"Promise"),XG=pa});var na,zG;var JC=K(()=>{F4();nf();na=T$(R1,"Set"),zG=na});var ZC="[object Map]",sa="[object Object]",XC="[object Promise]",zC="[object Set]",wC="[object WeakMap]",GC="[object DataView]",ta,aa,oa,ea,$o,H5,D9;var eZ=K(()=>{fC();lw();WC();JC();nB();w5();bM();ta=C9(ZG),aa=C9(h4),oa=C9(XG),ea=C9(zG),$o=C9(Bw),H5=s$;if(ZG&&H5(new ZG(new ArrayBuffer(1)))!=GC||h4&&H5(new h4)!=ZC||XG&&H5(XG.resolve())!=XC||zG&&H5(new zG)!=zC||Bw&&H5(new Bw)!=wC)H5=function($){var f=s$($),W=f==sa?$.constructor:void 0,J=W?C9(W):"";if(J)switch(J){case ta:return GC;case aa:return ZC;case oa:return XC;case ea:return zC;case $o:return wC}return f};D9=H5});function Jo($){var f=$.length,W=new $.constructor(f);if(f&&typeof $[0]=="string"&&Wo.call($,"index"))W.index=$.index,W.input=$.input;return W}var fo,Wo,YC;var LC=K(()=>{fo=Object.prototype,Wo=fo.hasOwnProperty;YC=Jo});var Zo,wW;var Gq=K(()=>{nf();Zo=R1.Uint8Array,wW=Zo});function Xo($){var f=new $.constructor($.byteLength);return new wW(f).set(new wW($)),f}var GW;var wG=K(()=>{Gq();GW=Xo});function zo($,f){var W=f?GW($.buffer):$.buffer;return new $.constructor(W,$.byteOffset,$.byteLength)}var KC;var HC=K(()=>{wG();KC=zo});function Go($){var f=new $.constructor($.source,wo.exec($));return f.lastIndex=$.lastIndex,f}var wo,UC;var RC=K(()=>{wo=/\w*$/;UC=Go});function Yo($){return qC?Object(qC.call($)):{}}var MC,qC,VC;var QC=K(()=>{z5();MC=h1?h1.prototype:void 0,qC=MC?MC.valueOf:void 0;VC=Yo});function Lo($,f){var W=f?GW($.buffer):$.buffer;return new $.constructor(W,$.byteOffset,$.length)}var GG;var Yq=K(()=>{wG();GG=Lo});function Co($,f,W){var J=$.constructor;switch(f){case Io:return GW($);case Ko:case Ho:return new J(+$);case Oo:return KC($,W);case Ao:case xo:case _o:case No:case So:case Fo:case Bo:case To:case Po:return GG($,W);case Uo:return new J;case Ro:case Vo:return new J($);case Mo:return UC($);case qo:return new J;case Qo:return VC($)}}var Ko="[object Boolean]",Ho="[object Date]",Uo="[object Map]",Ro="[object Number]",Mo="[object RegExp]",qo="[object Set]",Vo="[object String]",Qo="[object Symbol]",Io="[object ArrayBuffer]",Oo="[object DataView]",Ao="[object Float32Array]",xo="[object Float64Array]",_o="[object Int8Array]",No="[object Int16Array]",So="[object Int32Array]",Fo="[object Uint8Array]",Bo="[object Uint8ClampedArray]",To="[object Uint16Array]",Po="[object Uint32Array]",IC;var OC=K(()=>{wG();HC();RC();QC();Yq();IC=Co});function Eo($){return typeof $.constructor=="function"&&!s8($)?Tw(m4($)):{}}var YG;var Lq=K(()=>{uM();sZ();kw();YG=Eo});function Do($){return _1($)&&D9($)==ho}var ho="[object Map]",AC;var xC=K(()=>{eZ();E2();AC=Do});var _C,vo,NC;var SC=K(()=>{xC();gw();cw();_C=D2&&D2.isMap,vo=_C?a8(_C):AC,NC=vo});function ko($){return _1($)&&D9($)==mo}var mo="[object Set]",FC;var BC=K(()=>{eZ();E2();FC=ko});var TC,yo,PC;var CC=K(()=>{BC();gw();cw();TC=D2&&D2.isSet,yo=TC?a8(TC):FC,PC=yo});function LG($,f,W,J,Z,X){var z,w=f&jo,G=f&go,Y=f&bo;if(W)z=Z?W($,J,Z,X):W($);if(z!==void 0)return z;if(!W1($))return $;var L=g0($);if(L){if(z=YC($),!w)return Pw($,z)}else{var U=D9($),M=U==hC||U==lo;if(Uf($))return aZ($,w);if(U==DC||U==EC||M&&!Z){if(z=G||M?{}:YG($),!w)return G?eP($,cP(z,$)):aP($,bP(z,$))}else{if(!b0[U])return Z?$:{};z=IC($,U,w)}}X||(X=new y2);var q=X.get($);if(q)return q;if(X.set($,z),PC($))$.forEach(function(O){z.add(LG(O,f,W,O,$,X))});else if(NC($))$.forEach(function(O,x){z.set(x,LG(O,f,W,x,$,X))});var V=Y?G?JG:oZ:G?m2:v2,Q=L?void 0:V($);return Ew(Q||$,function(O,x){if(Q)x=O,O=$[x];p8(z,x,LG(O,f,W,x,$,X))}),z}var jo=1,go=2,bo=4,EC="[object Arguments]",uo="[object Array]",co="[object Boolean]",io="[object Date]",ro="[object Error]",hC="[object Function]",lo="[object GeneratorFunction]",po="[object Map]",no="[object Number]",DC="[object Object]",so="[object RegExp]",to="[object Set]",ao="[object String]",oo="[object Symbol]",eo="[object WeakMap]",$e="[object ArrayBuffer]",fe="[object DataView]",We="[object Float32Array]",Je="[object Float64Array]",Ze="[object Int8Array]",Xe="[object Int16Array]",ze="[object Int32Array]",we="[object Uint8Array]",Ge="[object Uint8ClampedArray]",Ye="[object Uint16Array]",Le="[object Uint32Array]",b0,vC;var mC=K(()=>{tZ();rM();Dw();uP();dP();Wq();cM();oP();$C();zq();wq();eZ();LC();OC();Lq();t$();t8();SC();Kf();CC();o8();e8();b0={};b0[EC]=b0[uo]=b0[$e]=b0[fe]=b0[co]=b0[io]=b0[We]=b0[Je]=b0[Ze]=b0[Xe]=b0[ze]=b0[po]=b0[no]=b0[DC]=b0[so]=b0[to]=b0[ao]=b0[oo]=b0[we]=b0[Ge]=b0[Ye]=b0[Le]=!0;b0[ro]=b0[hC]=b0[eo]=!1;vC=LG});function He($){return this.__data__.set($,Ke),this}var Ke="__lodash_hash_undefined__",kC;var yC=K(()=>{kC=He});function Ue($){return this.__data__.has($)}var jC;var gC=K(()=>{jC=Ue});function KG($){var f=-1,W=$==null?0:$.length;this.__data__=new Y5;while(++f<W)this.add($[f])}var bC;var uC=K(()=>{pw();yC();gC();KG.prototype.add=KG.prototype.push=kC;KG.prototype.has=jC;bC=KG});function Re($,f){var W=-1,J=$==null?0:$.length;while(++W<J)if(f($[W],W,$))return!0;return!1}var cC;var dC=K(()=>{cC=Re});function Me($,f){return $.has(f)}var iC;var rC=K(()=>{iC=Me});function Qe($,f,W,J,Z,X){var z=W&qe,w=$.length,G=f.length;if(w!=G&&!(z&&G>w))return!1;var Y=X.get($),L=X.get(f);if(Y&&L)return Y==f&&L==$;var U=-1,M=!0,q=W&Ve?new bC:void 0;X.set($,f),X.set(f,$);while(++U<w){var V=$[U],Q=f[U];if(J)var O=z?J(Q,V,U,f,$,X):J(V,Q,U,$,f,X);if(O!==void 0){if(O)continue;M=!1;break}if(q){if(!cC(f,function(x,y){if(!iC(q,y)&&(V===x||Z(V,x,W,J,X)))return q.push(y)})){M=!1;break}}else if(!(V===Q||Z(V,Q,W,J,X))){M=!1;break}}return X.delete($),X.delete(f),M}var qe=1,Ve=2,HG;var Kq=K(()=>{uC();dC();rC();HG=Qe});function Ie($){var f=-1,W=Array($.size);return $.forEach(function(J,Z){W[++f]=[Z,J]}),W}var lC;var pC=K(()=>{lC=Ie});function Oe($){var f=-1,W=Array($.size);return $.forEach(function(J){W[++f]=J}),W}var nC;var sC=K(()=>{nC=Oe});function ve($,f,W,J,Z,X,z){switch(W){case De:if($.byteLength!=f.byteLength||$.byteOffset!=f.byteOffset)return!1;$=$.buffer,f=f.buffer;case he:if($.byteLength!=f.byteLength||!X(new wW($),new wW(f)))return!1;return!0;case _e:case Ne:case Be:return h2(+$,+f);case Se:return $.name==f.name&&$.message==f.message;case Te:case Ce:return $==f+"";case Fe:var w=lC;case Pe:var G=J&Ae;if(w||(w=nC),$.size!=f.size&&!G)return!1;var Y=z.get($);if(Y)return Y==f;J|=xe,z.set($,f);var L=HG(w($),w(f),J,Z,X,z);return z.delete($),L;case Ee:if(Hq)return Hq.call($)==Hq.call(f)}return!1}var Ae=1,xe=2,_e="[object Boolean]",Ne="[object Date]",Se="[object Error]",Fe="[object Map]",Be="[object Number]",Te="[object RegExp]",Pe="[object Set]",Ce="[object String]",Ee="[object Symbol]",he="[object ArrayBuffer]",De="[object DataView]",tC,Hq,aC;var oC=K(()=>{z5();Gq();l8();Kq();pC();sC();tC=h1?h1.prototype:void 0,Hq=tC?tC.valueOf:void 0;aC=ve});function je($,f,W,J,Z,X){var z=W&me,w=oZ($),G=w.length,Y=oZ(f),L=Y.length;if(G!=L&&!z)return!1;var U=G;while(U--){var M=w[U];if(!(z?M in f:ye.call(f,M)))return!1}var q=X.get($),V=X.get(f);if(q&&V)return q==f&&V==$;var Q=!0;X.set($,f),X.set(f,$);var O=z;while(++U<G){M=w[U];var x=$[M],y=f[M];if(J)var F=z?J(y,x,M,f,$,X):J(x,y,M,$,f,X);if(!(F===void 0?x===y||Z(x,y,W,J,X):F)){Q=!1;break}O||(O=M=="constructor")}if(Q&&!O){var B=$.constructor,i=f.constructor;if(B!=i&&(("constructor"in $)&&("constructor"in f))&&!(typeof B=="function"&&B instanceof B&&typeof i=="function"&&i instanceof i))Q=!1}return X.delete($),X.delete(f),Q}var me=1,ke,ye,eC;var $E=K(()=>{zq();ke=Object.prototype,ye=ke.hasOwnProperty;eC=je});function ue($,f,W,J,Z,X){var z=g0($),w=g0(f),G=z?WE:D9($),Y=w?WE:D9(f);G=G==fE?UG:G,Y=Y==fE?UG:Y;var L=G==UG,U=Y==UG,M=G==Y;if(M&&Uf($)){if(!Uf(f))return!1;z=!0,L=!1}if(M&&!L)return X||(X=new y2),z||P4($)?HG($,f,W,J,Z,X):aC($,f,G,W,J,Z,X);if(!(W&ge)){var q=L&&JE.call($,"__wrapped__"),V=U&&JE.call(f,"__wrapped__");if(q||V){var Q=q?$.value():$,O=V?f.value():f;return X||(X=new y2),Z(Q,O,W,J,X)}}if(!M)return!1;return X||(X=new y2),eC($,f,W,J,Z,X)}var ge=1,fE="[object Arguments]",WE="[object Array]",UG="[object Object]",be,JE,ZE;var XE=K(()=>{tZ();Kq();oC();$E();eZ();t$();t8();dZ();be=Object.prototype,JE=be.hasOwnProperty;ZE=ue});function zE($,f,W,J,Z){if($===f)return!0;if($==null||f==null||!_1($)&&!_1(f))return $!==$&&f!==f;return ZE($,f,W,J,zE,Z)}var YW;var RG=K(()=>{XE();E2();YW=zE});function ie($,f,W,J){var Z=W.length,X=Z,z=!J;if($==null)return!X;$=Object($);while(Z--){var w=W[Z];if(z&&w[2]?w[1]!==$[w[0]]:!(w[0]in $))return!1}while(++Z<X){w=W[Z];var G=w[0],Y=$[G],L=w[1];if(z&&w[2]){if(Y===void 0&&!(G in $))return!1}else{var U=new y2;if(J)var M=J(Y,L,G,$,f,U);if(!(M===void 0?YW(L,Y,ce|de,J,U):M))return!1}}return!0}var ce=1,de=2,wE;var GE=K(()=>{tZ();RG();wE=ie});function re($){return $===$&&!W1($)}var MG;var Uq=K(()=>{Kf();MG=re});function le($){var f=v2($),W=f.length;while(W--){var J=f[W],Z=$[J];f[W]=[J,Z,MG(Z)]}return f}var YE;var LE=K(()=>{Uq();o8();YE=le});function pe($,f){return function(W){if(W==null)return!1;return W[$]===f&&(f!==void 0||($ in Object(W)))}}var qG;var Rq=K(()=>{qG=pe});function ne($){var f=YE($);if(f.length==1&&f[0][2])return qG(f[0][0],f[0][1]);return function(W){return W===$||wE(W,$,f)}}var KE;var HE=K(()=>{GE();LE();Rq();KE=ne});function se($,f){return $!=null&&f in Object($)}var UE;var RE=K(()=>{UE=se});function te($,f,W){f=Rf(f,$);var J=-1,Z=f.length,X=!1;while(++J<Z){var z=Mf(f[J]);if(!(X=$!=null&&W($,z)))break;$=$[z]}if(X||++J!=Z)return X;return Z=$==null?0:$.length,!!Z&&n8(Z)&&B4(z,Z)&&(g0($)||E9($))}var VG;var Mq=K(()=>{L5();uZ();t$();gZ();mw();K5();VG=te});function ae($,f){return $!=null&&VG($,f,UE)}var QG;var qq=K(()=>{RE();Mq();QG=ae});function $00($,f){if($W($)&&MG(f))return qG(Mf($),f);return function(W){var J=k2(W,$);return J===void 0&&J===f?QG(W,$):YW(f,J,oe|ee)}}var oe=1,ee=2,ME;var qE=K(()=>{RG();eM();qq();rw();Uq();Rq();K5();ME=$00});function f00($){return function(f){return f==null?void 0:f[$]}}var VE;var QE=K(()=>{VE=f00});function W00($){return function(f){return v4(f,$)}}var IE;var OE=K(()=>{nZ();IE=W00});function J00($){return $W($)?VE(Mf($)):IE($)}var AE;var xE=K(()=>{QE();OE();rw();K5();AE=J00});function Z00($){if(typeof $=="function")return $;if($==null)return d8;if(typeof $=="object")return g0($)?ME($[0],$[1]):KE($);return AE($)}var _E;var NE=K(()=>{HE();qE();Sw();t$();xE();_E=Z00});function X00($){return function(f,W,J){var Z=-1,X=Object(f),z=J(f),w=z.length;while(w--){var G=z[$?w:++Z];if(W(X[G],G,X)===!1)break}return f}}var SE;var FE=K(()=>{SE=X00});var z00,IG;var Vq=K(()=>{FE();z00=SE(),IG=z00});function w00($,f){return $&&IG($,f,v2)}var BE;var TE=K(()=>{Vq();o8();BE=w00});function G00($,f,W){if(W!==void 0&&!h2($[f],W)||W===void 0&&!(f in $))r8($,f,W)}var $7;var Qq=K(()=>{hw();l8();$7=G00});function Y00($){return _1($)&&T4($)}var PE;var CE=K(()=>{bZ();E2();PE=Y00});function L00($,f){if(f==="constructor"&&typeof $[f]==="function")return;if(f=="__proto__")return;return $[f]}var f7;var Iq=K(()=>{f7=L00});function K00($){return Hf($,m2($))}var EE;var hE=K(()=>{G5();e8();EE=K00});function H00($,f,W,J,Z,X,z){var w=f7($,W),G=f7(f,W),Y=z.get(G);if(Y){$7($,W,Y);return}var L=X?X(w,G,W+"",$,f,z):void 0,U=L===void 0;if(U){var M=g0(G),q=!M&&Uf(G),V=!M&&!q&&P4(G);if(L=G,M||q||V)if(g0(w))L=w;else if(PE(w))L=Pw(w);else if(q)U=!1,L=aZ(G,!0);else if(V)U=!1,L=GG(G,!0);else L=[];else if(tw(G)||E9(G)){if(L=w,E9(w))L=EE(w);else if(!W1(w)||S4(w))L=YG(G)}else U=!1}if(U)z.set(G,L),Z(L,G,J,X,z),z.delete(G);$7($,W,L)}var DE;var vE=K(()=>{Qq();Wq();Yq();cM();Lq();uZ();t$();CE();t8();jZ();Kf();fq();dZ();Iq();hE();DE=H00});function mE($,f,W,J,Z){if($===f)return;IG(f,function(X,z){if(Z||(Z=new y2),W1(X))DE($,f,z,W,mE,J,Z);else{var w=J?J(f7($,z),X,z+"",$,f,Z):void 0;if(w===void 0)w=X;$7($,z,w)}},m2)}var kE;var yE=K(()=>{tZ();Qq();Vq();vE();Kf();e8();Iq();kE=mE});var U00,Oq;var jE=K(()=>{yE();LT();U00=YT(function($,f,W,J){kE($,f,W,J)}),Oq=U00});function R00($){var f=$==null?0:$.length;return f?$[f-1]:void 0}var gE;var bE=K(()=>{gE=R00});function V00($,f){return $!=null&&q00.call($,f)}var M00,q00,uE;var cE=K(()=>{M00=Object.prototype,q00=M00.hasOwnProperty;uE=V00});function Q00($,f){return $!=null&&VG($,f,uE)}var W7;var dE=K(()=>{cE();Mq();W7=Q00});function I00($,f){return f.length<2?$:v4($,TP(f,0,-1))}var iE;var rE=K(()=>{nZ();PP();iE=I00});function O00($,f){return YW($,f)}var Aq;var lE=K(()=>{RG();Aq=O00});function A00($,f){return f=Rf(f,$),$=iE($,f),$==null||delete $[Mf(gE(f))]}var pE;var nE=K(()=>{L5();bE();rE();K5();pE=A00});function x00($){return tw($)?void 0:$}var sE;var tE=K(()=>{fq();sE=x00});var _00=1,N00=2,S00=4,F00,xq;var aE=K(()=>{gM();mC();nE();L5();G5();tE();$q();wq();F00=sw(function($,f){var W={};if($==null)return W;var J=!1;if(f=Nw(f,function(X){return X=Rf(X,$),J||(J=X.length>1),X}),Hf($,JG($),W),J)W=vC(W,_00|N00|S00,sE);var Z=f.length;while(Z--)pE(W,f[Z]);return W}),xq=F00});function B00($,f,W,J){if(!W1($))return $;f=Rf(f,$);var Z=-1,X=f.length,z=X-1,w=$;while(w!=null&&++Z<X){var G=Mf(f[Z]),Y=W;if(G==="__proto__"||G==="constructor"||G==="prototype")return $;if(Z!=z){var L=w[G];if(Y=J?J(L,G,w):void 0,Y===void 0)Y=W1(L)?L:B4(f[Z+1])?[]:{}}p8(w,G,Y),w=w[G]}return $}var OG;var _q=K(()=>{Dw();L5();gZ();Kf();K5();OG=B00});function T00($,f,W){var J=-1,Z=f.length,X={};while(++J<Z){var z=f[J],w=v4($,z);if(W(w,z))OG(X,Rf(z,$),w)}return X}var oE;var eE=K(()=>{nZ();_q();L5();oE=T00});function P00($,f){return oE($,f,function(W,J){return QG($,J)})}var $h;var fh=K(()=>{eE();qq();$h=P00});var C00,LW;var Wh=K(()=>{fh();$q();C00=sw(function($,f){return $==null?{}:$h($,f)}),LW=C00});function E00($,f,W){return $==null?$:OG($,f,W)}var k4;var Jh=K(()=>{_q();k4=E00});function h00($,f,W){var J=g0($),Z=J||Uf($)||P4($);if(f=_E(f,4),W==null){var X=$&&$.constructor;if(Z)W=J?new X:[];else if(W1($))W=S4(X)?Tw(m4($)):{};else W={}}return(Z?Ew:BE)($,function(z,w,G){return f(W,z,w,G)}),W}var Nq;var Zh=K(()=>{rM();uM();TE();NE();sZ();t$();t8();jZ();Kf();dZ();Nq=h00});var j2=K(()=>{eM();dE();lE();jE();aE();Wh();Jh();Zh()});var Xh;var sf=K(()=>{UB();RB();MB();qB();NB();SB();kM();FB();p$();kM();BB();TB();Xh={primary:{schema:mM,field:C2},text:{schema:yM,field:X5},number:{schema:vM,field:Z5},boolean:{schema:SM,field:CZ},date:{schema:FM,field:b8},enum:{schema:BM,field:EZ},json:{schema:TM,field:hZ},jsonschema:{schema:DM,field:DZ}}});var AG;var zh=K(()=>{sf();_();AG=class AG{em;static EXCLUDE_TABLES=["libsql_wasm_func_table","sqlite_sequence","_cf_KV"];constructor($){this.em=$}getIntrospector(){return this.em.connection.getIntrospector()}async introspect(){let $=await this.getIntrospector().getTables({withInternalKyselyTables:!1}),f=await this.getIntrospector().getIndices(),W=[];for(let J of $){if(AG.EXCLUDE_TABLES.includes(J.name))continue;W.push({...J,indices:f.filter((Z)=>Z.table===J.name)})}return W}getIntrospectionFromEntity($){let f=$.getFields(!1),W=this.em.getIndicesOf($);return{name:$.name,isView:!1,columns:f.map((J)=>({name:J.name,dataType:"TEXT",isNullable:!0,isAutoIncrementing:J instanceof C2,hasDefaultValue:!1,comment:void 0})),indices:W.map((J)=>({name:J.name,table:$.name,isUnique:J.unique,columns:J.fields.map((Z)=>({name:Z.name,order:0}))}))}}async getDiff(){let $=await this.introspect(),f=this.em.entities.map((Z)=>this.getIntrospectionFromEntity(Z)),W=[],J=(Z)=>Z.name;$.filter((Z)=>{if(/bknd/.test(Z.name)||Z.isView)return!1;return!f.map((X)=>X.name).includes(Z.name)}).forEach((Z)=>{W.push({name:Z.name,isDrop:!0,isNew:!1,columns:{add:[],drop:[],change:[]},indices:{add:[],drop:[]}})});for(let Z of f){let X=$.find((z)=>z.name===Z.name);if(!X)W.push({name:Z.name,isNew:!0,columns:{add:Z.columns.map(J),drop:[],change:[]},indices:{add:Z.indices.map(J),drop:[]}});else{let z=Z.columns.filter((M)=>!X.columns.map(J).includes(M.name)),w=X.columns.filter((M)=>!Z.columns.map(J).includes(M.name)),G=[];for(let M of Z.columns){let q=X.columns.find((Q)=>Q.name===M.name),V=[];for(let[Q,O]of Object.entries(M))if(q&&q[Q]!==O)V.push({attribute:Q,prev:q[Q],next:O});if(Object.keys(V).length>0)G.push({name:M.name,changes:V})}let Y=Z.indices.filter((M)=>!X.indices.map((q)=>q.name).includes(M.name)),L=X.indices.filter((M)=>!Z.indices.map((q)=>q.name).includes(M.name));if([z,w,Y,L].some((M)=>M.length>0))W.push({name:Z.name,isNew:!1,columns:{add:z.map(J),drop:w.map(J),change:[]},indices:{add:Y.map(J),drop:L.map(J)}})}}return W}collectFieldSchemas($,f){let W=[];if(f.length===0)return W;for(let J of f){let X=this.em.entity($).getField(J).schema();if(X)W.push(this.em.connection.getFieldSchema(X))}return W}async sync($={force:!1,drop:!1}){let f=await this.getDiff(),W=0,J=[],Z=this.em.connection.kysely.schema;for(let X of f){let z=[],w=0,G=this.collectFieldSchemas(X.name,X.columns.add),Y=X.columns.drop,L=X.indices.drop;if(X.isDrop){if(W++,w++,$.drop)z.push(Z.dropTable(X.name))}else if(X.isNew){let U=Z.createTable(X.name);for(let M of G)W++,w++,U=U.addColumn(...M);z.push(U)}else{if(G.length>0)for(let U of G)W++,w++,z.push(Z.alterTable(X.name).addColumn(...U));if($.drop&&Y.length>0)for(let U of Y)W++,w++,z.push(Z.alterTable(X.name).dropColumn(U))}for(let U of X.indices.add){let q=this.em.getIndicesOf(X.name).find((Q)=>Q.name===U),V=Z.createIndex(U).on(X.name).columns(q.fields.map((Q)=>Q.name));if(q.unique)V=V.unique();z.push(V),w++,W++}if($.drop)for(let U of L)z.push(Z.dropIndex(U)),w++,W++;if(w===0)continue;for(let U of z){let{sql:M,parameters:q}=U.compile();if(J.push({sql:M,parameters:q}),$.force)try{A.debug("[SchemaManager]",M),await U.execute()}catch(V){throw new Error(`Failed to execute query: ${M}: ${V.message}`)}}}return J}}});class P${#$;#f;name;fields;config;data;type="regular";constructor($,f,W,J){if(typeof $!=="string"||$.length===0)throw new Error("Entity name must be a non-empty string");this.name=$,this.config=F0(Sq,W||{});let Z=f?.filter((X)=>X instanceof C2).length??0;if(Z>1)throw new Error(`Entity "${$}" has more than one primary field`);if(this.fields=Z===1?[]:[new C2(void 0,{format:this.config.primary_format})],f)f.forEach((X)=>this.addField(X));if(J)this.type=J;this[wh]=!0}static isEntity($){if(!$)return!1;return $[wh]===!0}static create($){return new P$($.name,$.fields,$.config,$.type)}getType(){return this.type}getSelect($,f){return this.getFields().filter((W)=>!W.isHidden(f??"read")).map((W)=>$?`${$}.${W.name} as ${W.name}`:W.name)}getDefaultSort(){return{by:this.config.sort_field??"id",dir:this.config.sort_dir??"asc"}}getAliasedSelectFrom($,f,W){let J=f??this.name;return this.getFields().filter((Z)=>!Z.isVirtual()&&!Z.isHidden(W??"read")&&$.includes(Z.name)).map((Z)=>J?`${J}.${Z.name} as ${Z.name}`:Z.name)}getFillableFields($,f){return this.getFields(f).filter((W)=>W.isFillable($))}getRequiredFields(){return this.getFields().filter(($)=>$.isRequired())}getDefaultObject(){return this.getFields().reduce(($,f)=>{if(f.hasDefault())$[f.name]=f.getDefault();return $},{})}getField($){return this.fields.find((f)=>f.name===$)}__replaceField($,f){let W=this.fields.findIndex((J)=>J.name===$);if(W===-1)throw new Error(`Field "${$}" not found on entity "${this.name}"`);this.fields[W]=f}getPrimaryField(){return this.fields[0]}id(){return this.getPrimaryField()}get label(){return this.config.name??G4(this.name)}field($){return this.getField($)}hasField($){let f=typeof $==="string"?$:$.name;return this.fields.findIndex((W)=>W.name===f)!==-1}getFields($=!1){if($)return this.fields;return this.fields.filter((f)=>!f.isVirtual())}addField($){let f=this.getField($.name);if(f){if(JSON.stringify(f)===JSON.stringify($)){A.warn(`Field "${$.name}" already exists on entity "${this.name}", but it's the same, so skipping.`);return}throw new Error(`Field "${$.name}" already exists on entity "${this.name}"`)}this.fields.push($)}__setData($){this.data=$}isValidData($,f,W){if(typeof $!=="object"){if(W?.explain)throw new Error(`Entity "${this.name}" data must be an object`)}let J=this.getFillableFields(f,!1);if(W?.ignoreUnknown!==!0){let Z=J.map((w)=>w.name),z=Object.keys($).filter((w)=>!Z.includes(w));if(z.length>0){if(W?.explain)throw new Error(`Entity "${this.name}" data must only contain known keys, unknown: "${z}"`)}}for(let Z of J)if(!Z.isValid($?.[Z.name],f)){if(A.warn("invalid data given for",this.name,f,Z.name,$[Z.name]),W?.explain)throw new Error(`Field "${Z.name}" has invalid data: "${$[Z.name]}"`);return!1}return!0}toSchema($){let f;switch($?.context){case"create":case"update":f=this.getFillableFields($.context);break;default:f=this.getFields(!0)}let W=Object.fromEntries(f.map((Z)=>[Z.name,Z])),J={type:"object",additionalProperties:!1,properties:M0(W,(Z)=>{let X=Z.isFillable($?.context);return{title:Z.config.label,$comment:Z.config.description,$field:Z.type,readOnly:!X?!0:void 0,...Z.toJsonSchema()}})};return $?.clean?JSON.parse(JSON.stringify(J)):J}toTypes(){return{name:this.name,type:this.type,comment:this.config.description,fields:Object.fromEntries(this.getFields().map(($)=>[$.name,$.toType()]))}}toJSON(){return{type:this.type,fields:Object.fromEntries(this.fields.map(($)=>[$.name,$.toJSON()])),config:this.config}}}var Sq,KW,wh;var xG=K(()=>{vZ();_();sf();Sq=R.strictObject({name:R.string(),name_singular:R.string(),description:R.string(),sort_field:R.string({default:pf.data.default_primary_field}),sort_dir:R.string({enum:["asc","desc"],default:"asc"}),primary_format:R.string({enum:mZ})}).partial(),KW=["regular","system","generated"],wh=Symbol.for("bknd:entity")});function v9($){return["string","number","boolean"].includes(typeof $)}function Lh($){return[!0,!1,0,1].includes($)}class Kh{key;valid;validate;expect;constructor($,f,W){this.key=$;this.valid=f;this.validate=W}}function qf($,f,W){return new Kh($,f,W)}function Hh($,f){let W=$.find((J)=>J.key===f);if(!W)throw new Error(`Expression does not exist: "${f}"`);return W}function Fq($,f,W=[]){let J=f.map((G)=>G.key),Z=Object.keys($),X=[Gh],z={};if(Z.some((G)=>G.startsWith("$")&&!X.includes(G)))throw new Error(`Invalid key '${Z}'. Keys must not start with '$'.`);if(W.length>0&&Z.some((G)=>X.includes(G)))throw new Error(`Operand ${Gh} can only appear at the top level.`);function w(G,Y,L=[]){if(Hh(f,G).valid(Y)===!1)throw new Error(`Invalid value at "${[...L,G].join(".")}": ${Y}`)}for(let[G,Y]of Object.entries($))if(G==="$or")z.$or=Fq(Y,f,[...W,G]);else if(v9(Y))w("$eq",Y,W),z[G]={$eq:Y};else if(typeof Y==="object"){let L=Object.keys(Y).filter((U)=>!J.includes(U));if(L.length===0){z[G]={};for(let[U,M]of Object.entries(Y))w(U,M,[...W,G]),z[G][U]=M}else throw new Error(`Invalid key(s) at "${G}": ${L.join(", ")}. Expected expressions.`)}return z}function Yh($,f,W){let J=W.convert?Fq($,f):$,Z={$and:[],$or:[],keys:new Set},{$or:X,...z}=J;function w(G,Y,L,U=[]){let M=Hh(f,G);if(!M)throw new Error(`Expression does not exist: "${G}"`);if(!M.valid(Y))throw new Error(`Invalid expected value at "${[...U,G].join(".")}": ${Y}`);return M.validate(Y,L,W.exp_ctx)}for(let[G,Y]of Object.entries(z))for(let[L,U]of Object.entries(Y)){let M=W.value_is_kv?G:W.object[G];Z.$and.push(w(L,U,M,[G])),Z.keys.add(G)}for(let[G,Y]of Object.entries(X??{})){let L=W.value_is_kv?G:W.object[G];for(let[U,M]of Object.entries(Y))Z.$or.push(w(U,M,L,[G])),Z.keys.add(G)}return Z}function D00($){let f={$and:void 0,$or:void 0};return f.$and=$.$and.every((W)=>Boolean(W)),f.$or=$.$or.some((W)=>Boolean(W)),!!f.$and||!!f.$or}function Uh($){return{convert:(f)=>Fq(f,$),build:(f,W)=>Yh(f,$,W),validate:(f,W)=>{let J=Yh(f,$,W);return D00(J)},expressions:$,expressionKeys:$.map((f)=>f.key)}}var Gh="$or";function tf($){if(typeof $!=="string")throw new Error(`Invalid key: ${$}`);return $}class Vf{static addClause($,f){if(Object.keys(f).length===0)return $;return $.where((W)=>{let J=_G.build(f,{value_is_kv:!0,exp_ctx:W,convert:!0});if(J.$or.length>0&&J.$and.length>0)return W.and(J.$and).or(W.and(J.$or));else if(J.$or.length>0)return W.or(J.$or);return W.and(J.$and)})}static convert($){return _G.convert($)}static getPropertyNames($){let{keys:f}=_G.build($,{value_is_kv:!0,exp_ctx:()=>null,convert:!0});return Array.from(f)}}var v00,_G,jk0;var NG=K(()=>{v00=[qf("$eq",($)=>v9($),($,f,W)=>W(tf(f),"=",$)),qf("$ne",($)=>v9($),($,f,W)=>W(tf(f),"!=",$)),qf("$gt",($)=>v9($),($,f,W)=>W(tf(f),">",$)),qf("$gte",($)=>v9($),($,f,W)=>W(tf(f),">=",$)),qf("$lt",($)=>v9($),($,f,W)=>W(tf(f),"<",$)),qf("$lte",($)=>v9($),($,f,W)=>W(tf(f),"<=",$)),qf("$isnull",($)=>Lh($),($,f,W)=>W(tf(f),$?"is":"is not",null)),qf("$in",($)=>Array.isArray($),($,f,W)=>W(tf(f),"in",$)),qf("$notin",($)=>Array.isArray($),($,f,W)=>W(tf(f),"not in",$)),qf("$between",($)=>Array.isArray($)&&$.length===2,($,f,W)=>W.between(tf(f),$[0],$[1])),qf("$like",($)=>v9($),($,f,W)=>W(tf(f),"like",String($).replace(/\*/g,"%")))],_G=Uh(v00),jk0=_G.expressionKeys});var g2;var J7=K(()=>{_();y4();g2=class g2{config;source;target;directions=["source","target"];static schema=R.strictObject({mappedBy:R.string().optional(),inversedBy:R.string().optional(),required:R.boolean().optional()});constructor($,f,W={}){this.source=$,this.target=f;let J=this.constructor.schema;this.config=F0(J,W)}getReferenceQuery($,f,W){return{}}helper($){return new Bq(this,$)}other($){let f=typeof $==="string"?$:$.name;if(this.source.entity.name===this.target.entity.name)return this.source.cardinality===1?this.target:this.source;if(this.source.entity.name===f)return this.target;else if(this.target.entity.name===f)return this.source;throw new Error(`Entity "${f}" is not part of the relation "${this.source.entity.name} <-> ${this.target.entity.name}"`)}self($){return this.other($).entity.name===this.source.entity.name?this.target:this.source}ref($){return this.source.reference===$?this.source:this.target}otherRef($){return this.source.reference===$?this.target:this.source}visibleFrom($){return this.directions.includes($)}hydrate($,f,W){let J=typeof $==="string"?$:$.name,Z=this.ref(J),X=W.hydrate(Z.entity.name,f);if(Z.cardinality===1){if(Array.isArray(X)&&X.length>1)throw new Error(`Failed to hydrate "${Z.entity.name}" with value: ${JSON.stringify(f)} (cardinality: 1)`);return X[0]}if(!X)throw new Error(`Failed to hydrate "${Z.entity.name}" with value: ${JSON.stringify(f)} (cardinality: -)`);return X}isListableFor($){return this.target.entity.name===$.name}get required(){return!!this.config.required}async $set($,f,W){throw new Error("$set is not allowed")}async $create($,f,W){throw new Error("$create is not allowed")}async $attach($,f,W){throw new Error("$attach is not allowed")}async $detach($,f,W){throw new Error("$detach is not allowed")}getName(){return[this.type().replace(":",""),this.source.entity.name,this.target.entity.name,this.config.mappedBy,this.config.inversedBy].filter(Boolean).join("_")}toJSON(){return{type:this.type(),source:this.source.entity.name,target:this.target.entity.name,config:this.config}}}});class b2{entity;cardinality;reference;constructor($,f,W){this.entity=$,this.cardinality=W,this.reference=f}toJSON(){return{entity:this.entity.name,cardinality:this.cardinality,name:this.reference}}}var m00,Tq,r1;var SG=K(()=>{sf();_();m00=["cascade","set null","set default","restrict","no action"],Tq=R.strictObject({reference:R.string(),target:R.string(),target_field:R.string({default:"id"}).optional(),target_field_type:R.string({enum:["text","integer"],default:"integer"}).optional(),on_delete:R.string({enum:m00,default:"set null"}).optional(),...X1.properties});r1=class r1 extends a0{type="relation";getSchema(){return Tq}static create($,f,W){let J=[f.reference??f.entity.name,f.entity.getPrimaryField().name].join("_");return new r1(J,{...W,required:$.required,reference:f.reference,target:f.entity.name,target_field:f.entity.getPrimaryField().name,target_field_type:f.entity.getPrimaryField().fieldType})}reference(){return this.config.reference}target(){return this.config.target}targetField(){return this.config.target_field}schema(){return Object.freeze({...super.schema(),type:this.config.target_field_type??"integer",references:`${this.config.target}.${this.config.target_field}`,onDelete:this.config.on_delete??"set null"})}transformRetrieve($){return $}async transformPersist($,f){throw new Error("RelationField: This function should not be called")}toJsonSchema(){return this.toSchemaWrapIfRequired(R.number({$ref:`${this.config?.target}#/properties/${this.config?.target_field}`}))}toType(){return{...super.toType(),type:"number"}}}});var l1;var HW=K(()=>{l1={OneToOne:"1:1",ManyToOne:"n:1",ManyToMany:"m:n",Polymorphic:"poly"}});var a$;var Rh=K(()=>{j4();sf();J7();SG();HW();_();a$=class a$ extends g2{connectionEntity;additionalFields=[];connectionTableMappedName;em;static schema=R.strictObject({connectionTable:R.string().optional(),connectionTableMappedName:R.string().optional(),...g2.schema.properties});constructor($,f,W,J){let Z=W?.connectionTable||a$.defaultConnectionTable($,f),X=new b2($,$.name),z=new b2(f,f.name);super(X,z,W);this.connectionEntity=new P$(Z,J,void 0,"generated"),this.connectionTableMappedName=W?.connectionTableMappedName||Z,this.additionalFields=J||[]}static defaultConnectionTable($,f){return`${$.name}_${f.name}`}type(){return l1.ManyToMany}isListableFor(){return!0}getField($){let f=this.connectionEntity,W=f.fields.find((J)=>J instanceof r1&&J.target()===$.name);if(!W||!(W instanceof r1))throw new Error(`Connection entity "${f.name}" does not have a relation to "${$.name}"`);return W}getQueryInfo($){let f=this.other($),W=this.connectionEntity,J=this.getField($),Z=this.getField(f.entity),X=`${$.name}.${$.getPrimaryField().name}`,z=`${W.name}.${J.name}`,w=`${W.name}.${Z.name}`,G=[W.name,`${f.entity.name}.${f.entity.getPrimaryField().name}`,w],Y=`${$.name}.${$.getPrimaryField().name}`;return{other:f,join:G,entityRef:X,selfRef:z,otherRef:w,groupBy:Y}}getReferenceQuery($,f){let{other:W,otherRef:J}=this.getQueryInfo($);return{where:{[J]:f},join:[W.reference]}}buildJoin($,f){let{other:W,join:J,entityRef:Z,selfRef:X,groupBy:z}=this.getQueryInfo($);return f.innerJoin(W.entity.name,Z,X).innerJoin(...J).groupBy(z)}buildWith($){if(!this.em)throw new Error("EntityManager not set, can't build");let f=this.em.connection.fn.jsonBuildObject;if(!f)throw new Error("Connection does not support jsonBuildObject");let W=5,{other:J,join:Z,entityRef:X,selfRef:z}=this.getQueryInfo($),w=this.connectionEntity.fields.filter((G)=>!(G instanceof r1||G instanceof C2));return(G)=>G.selectFrom(J.entity.name).select((Y)=>{let L=[];if(w.length>0){let U=this.connectionEntity.name;L.push(f(Object.fromEntries(w.map((M)=>[M.name,Y.ref(`${U}.${M.name}`)]))).as(this.connectionTableMappedName))}return L}).whereRef(X,"=",z).innerJoin(...Z).limit(W)}initialize($){this.em=$;let f=r1.create(this,this.source),W=r1.create(this,this.target);if($.hasEntity(this.connectionEntity)){if(!this.connectionEntity.hasField(f))this.connectionEntity.addField(f);if(!this.connectionEntity.hasField(W))this.connectionEntity.addField(W)}else this.connectionEntity.addField(f),this.connectionEntity.addField(W),$.addEntity(this.connectionEntity)}getName(){return[super.getName(),[this.connectionEntity.name,this.connectionTableMappedName].filter(Boolean)].join("_")}}});var af;var Pq=K(()=>{_();J7();SG();HW();af=class af extends g2{fieldConfig;static DEFAULTS={with_limit:5};static schema=R.strictObject({sourceCardinality:R.number().optional(),with_limit:R.number({default:af.DEFAULTS.with_limit}).optional(),fieldConfig:R.object({label:R.string()}).optional(),...g2.schema.properties});constructor($,f,W={}){let J=W.mappedBy||f.name,Z=W.inversedBy||$.name,X=typeof W.sourceCardinality==="number"&&W.sourceCardinality>0?W.sourceCardinality:void 0,z=new b2($,Z,X),w=new b2(f,J,1);super(z,w,W);this.fieldConfig=W.fieldConfig??{}}type(){return l1.ManyToOne}initialize($){let f=G4(this.target.reference),W=r1.create(this,this.target,{label:f,...this.fieldConfig});if(!this.source.entity.field(W.name))this.source.entity.addField(r1.create(this,this.target,{label:f,...this.fieldConfig}))}getField(){let $=this.target.entity.getPrimaryField().name,f=this.source.entity.getField(`${this.target.reference}_${$}`);if(!(f instanceof r1))throw new Error(`Field "${this.target.reference}_${$}" not found on entity "${this.source.entity.name}"`);return f}queryInfo($,f){let W=this.source.reference===f?"source":"target",J=this[W],Z=this[W==="source"?"target":"source"],X,z,w;if(W==="source")X=this.source.reference,z=`${X}.${this.getField().name}`,w=`${$.name}.${J.entity.getPrimaryField().name}`;else X=this.target.reference,z=`${X}.${$.getPrimaryField().name}`,w=`${$.name}.${this.getField().name}`;let G=`${$.name}.${$.getPrimaryField().name}`;return{other:Z,self:J,relationRef:X,entityRef:z,otherRef:w,groupBy:G}}getReferenceQuery($,f,W){let J=this.source.reference===W?"source":"target",Z=this[J],X=this[J==="source"?"target":"source"];return{where:{[`${X.reference}_${X.entity.getPrimaryField().name}`]:f},join:X.entity.name===Z.entity.name?[]:[X.entity.name]}}buildJoin($,f,W){let{self:J,entityRef:Z,otherRef:X,groupBy:z}=this.queryInfo($,W);return f.innerJoin(J.entity.name,Z,X).groupBy(z)}buildWith($,f){let{self:W,entityRef:J,otherRef:Z,relationRef:X}=this.queryInfo($,f);return(z)=>z.selectFrom(`${W.entity.name} as ${X}`).whereRef(J,"=",Z).$if(W.cardinality===1,(w)=>w.limit(1))}async $set($,f,W){if(typeof W!=="object")throw new Error(`Invalid value for relation field "${f}" given, expected object.`);let J=this.source.entity,X=this.helper(J.name).getMutationInfo();if(!X.$set)throw new Error(`Cannot perform $set for relation "${f}"`);let z=X.local_field,w=this.getField(),G=W[Object.keys(W)[0]];if(!z||!(w instanceof r1))throw new Error(`Cannot perform $set for relation "${f}"`);if(G===null&&!w.isRequired())return[z,null];if(!(await $.repository(w.target()).exists({[w.targetField()]:G})).data.exists){let L=w.targetField();throw new Error(`Cannot connect "${J.name}.${f}" to "${w.target()}.${L}" = "${G}": not found.`)}return[z,G]}}});var UW;var Mh=K(()=>{Pq();HW();UW=class UW extends af{constructor($,f,W){let{mappedBy:J,inversedBy:Z,required:X}=W||{};super($,f,{mappedBy:J,inversedBy:Z,sourceCardinality:1,required:X})}type(){return l1.OneToOne}isListableFor(){return!1}async $set($,f,W){throw new Error("$set is not allowed")}async $create($,f,W){if(W===null||typeof W!=="object")throw new Error(`Invalid value for relation field "${f}" given, expected object.`);let J=this.other(this.source.entity).entity,X=this.helper(this.source.entity.name).getMutationInfo(),z=X.primary,w=X.local_field;if(!X.$create||!z||!w)throw new Error(`Cannot perform $create for relation "${f}"`);try{let{data:G}=await $.mutator(J).insertOne(W),Y=G[z];return[w,Y]}catch(G){throw new Error(`Error performing $create on "${J.name}".`)}}}});var U5;var qh=K(()=>{sf();J7();HW();_();U5=class U5 extends g2{static schema=R.strictObject({targetCardinality:R.number().optional(),...g2.schema.properties});constructor($,f,W={}){let J=W.mappedBy||f.name,Z=W.inversedBy||$.name,X=typeof W.targetCardinality==="number"&&W.targetCardinality>0?W.targetCardinality:void 0,z=new b2($,Z,1),w=new b2(f,J,X);super(z,w,W);this.directions=["source"]}type(){return l1.Polymorphic}queryInfo($){let f=this.other($),W=`${f.entity.name}.${this.getReferenceField().name}`,J=`${$.name}.${this.config.mappedBy}`,Z=`${f.entity.name}.${this.config.mappedBy}`,X=`${$.name}.${$.getPrimaryField().name}`,z=`${f.entity.name}.${this.getEntityIdField().name}`,w=`${$.name}.${$.getPrimaryField().name}`;return{other:f,whereLhs:W,reference:J,reference_other:Z,entityRef:X,otherRef:z,groupBy:w}}buildJoin($,f){let{other:W,whereLhs:J,reference:Z,entityRef:X,otherRef:z,groupBy:w}=this.queryInfo($);return f.innerJoin(W.entity.name,(G)=>G.onRef(X,"=",z).on(J,"=",Z)).groupBy(w)}getReferenceQuery($,f){let W=this.queryInfo($);return{where:{[this.getReferenceField().name]:W.reference_other,[this.getEntityIdField().name]:f}}}buildWith($){let{other:f,whereLhs:W,reference:J,entityRef:Z,otherRef:X}=this.queryInfo($);return(z)=>z.selectFrom(f.entity.name).where(W,"=",J).whereRef(Z,"=",X).$if(f.cardinality===1,(w)=>w.limit(1))}isListableFor($){return this.source.entity.name===$.name&&this.target.cardinality!==1}getReferenceField(){return new X5("reference",{hidden:!0,fillable:["create"]})}getEntityIdField(){return new Z5("entity_id",{hidden:!0,fillable:["create"]})}initialize($){let f=this.getReferenceField(),W=this.getEntityIdField();if(!this.target.entity.field(f.name))this.target.entity.addField(f);if(!this.target.entity.field(W.name))this.target.entity.addField(W)}}});class Bq{relation;access;self;other;constructor($,f){if(this.relation=$,$.source.entity.name===f)this.access="source",this.self=$.source,this.other=$.target;else if($.target.entity.name===f)this.access="target",this.self=$.target,this.other=$.source;else throw new Error(`Entity "${f}" is not part of the relation "${$.source.entity.name} <-> ${$.target.entity.name}"`)}getMutationInfo(){let $={$set:!1,$create:!1,$attach:!1,$detach:!1},f,W;switch(this.relation.type()){case l1.ManyToOne:if(typeof this.self.cardinality==="undefined"&&this.other.cardinality===1)$.$set=!0,f=this.relation.getField()?.name,W=this.other.entity.getPrimaryField().name;break;case l1.OneToOne:if(this.access==="source")$.$create=!0,$.$set=!0,f=this.relation.getField()?.name,W=this.other.entity.getPrimaryField().name;break;case l1.ManyToMany:if(this.access==="source")$.$attach=!0,$.$detach=!0,W=this.other.entity.getPrimaryField().name;break}return{reference:this.other.reference,local_field:f,...$,primary:W,cardinality:this.other.cardinality,relation_type:this.relation.type()}}}var Cq;var Vh=K(()=>{y4();Cq=["$set","$create","$attach","$detach"]});class Eq{entity;em;constructor($,f){this.entity=$;this.em=f}getRelationalKeys(){let $=[];if(this.entity.type==="generated"){if(this.em.relations.all.find((W)=>W instanceof a$&&W.connectionEntity.name===this.entity.name)instanceof a$)$.push(...this.entity.fields.filter((W)=>W.type==="relation").map((W)=>W.name))}return this.em.relationsOf(this.entity.name).map((f)=>{let W=f.helper(this.entity.name).getMutationInfo();$.push(W.reference),W.local_field&&$.push(W.local_field)}),$}async persistRelationField($,f,W){if(W===null&&!$.isRequired())return[f,W];if(typeof W==="object")throw new Error(`Invalid value for relation field "${f}" given, expected primitive.`);if(!(await this.em.repository($.target()).exists({[$.targetField()]:W})).data.exists){let Z=$.targetField();throw new Error(`Cannot connect "${this.entity.name}.${f}" to "${$.target()}.${Z}" = "${W}": not found.`)}return[f,W]}async persistReference($,f,W){if(typeof W!=="object"||W===null||typeof W==="undefined")throw new Error(`Invalid value for relation "${f}" given, expected object to persist reference. Like '{$set: {id: 1}}'.`);let J=Object.keys(W)[0];if(!Cq.includes(J))throw new Error(`Invalid operation "${J}" for relation "${f}". Allowed: ${Cq.join(", ")}`);let Z=W[J];return await $[J](this.em,f,Z)}async persistRelation($,f){let W=this.entity.getField($);if(W instanceof r1)return this.persistRelationField(W,$,f);let J=this.em.relationOf(this.entity.name,$);if(J)return this.persistReference(J,$,f);throw new Error(`Relation "${$}" failed to resolve on entity "${this.entity.name}": Unable to resolve relation origin.`)}}var Qh=K(()=>{y4()});var hq,Ih;var y4=K(()=>{Rh();Pq();Mh();qh();HW();J7();Vh();Qh();SG();hq={[l1.OneToOne]:{schema:UW.schema,cls:UW},[l1.ManyToOne]:{schema:af.schema,cls:af},[l1.ManyToMany]:{schema:a$.schema,cls:a$},[l1.Polymorphic]:{schema:U5.schema,cls:U5}},Ih={relation:{schema:Tq,field:r1}}});class Z7{conn;options;results=[];time=0;constructor($,f={}){this.conn=$;this.options=f}get(){if(!this.results)throw new Error("Result not executed");if(Array.isArray(this.results))return this.results??[];return this.results[0]}first(){let $=this.get();return(Array.isArray($)?$[0]:$)??{}}get sql(){return this.first().sql}get parameters(){return this.first().parameters}get data(){if(this.options.single)return this.first().data?.[0];return this.first().data??[]}async execute($){let f=Array.isArray($)?$:[$];for(let W of f){let J=W.compile();await this.options.beforeExecute?.(J);try{let Z=performance.now(),X=await this.conn.executeQuery(J);this.time=Number.parseFloat((performance.now()-Z).toFixed(2)),this.results.push({...X,data:this.options.hydrator?.(X.rows),items:X.rows.length,time:this.time,sql:J.sql,parameters:[...J.parameters]})}catch(Z){if(this.options.onError)await this.options.onError(Z);else throw Z}}return this}additionalMetaKeys(){return[]}toJSON(){let{rows:$,data:f,...W}=this.first(),J=Z1()?["items","time","sql","parameters"]:["items","time"],Z=V_(W,[...J,...this.additionalMetaKeys()]);return{data:this.data,meta:Z}}}var Dq=K(()=>{V$();_()});var vq;var mq=K(()=>{_();Dq();V$();vq=class vq extends Z7{em;entity;constructor($,f,W){let J=W?.logParams===void 0?Z1():W.logParams;super($.connection,{hydrator:(Z)=>$.hydrate(f.name,Z),beforeExecute:(Z)=>{if(!W?.silent)A.debug(`[Mutation]
${Z.sql}
`,J?Z.parameters:void 0)},onError:(Z)=>{if(!W?.silent)throw A.error("[ERROR] Mutator:",Z.message),Z},...W});this.em=$;this.entity=f}}});var m9;var Oh=K(()=>{M2();NG();B$();PZ();y4();mq();m9=class m9{em;entity;options;static Events=T9;emgr;__unstable_disable_system_entity_creation=!0;__unstable_toggleSystemEntityCreation($){this.__unstable_disable_system_entity_creation=$}constructor($,f,W){this.em=$;this.entity=f;this.options=W;this.emgr=W?.emgr??new Q$(T9)}get conn(){return this.em.connection.kysely}async getValidatedData($,f){let W=this.entity;if(!f)throw new Error("Context must be provided for validation");let J=Object.keys($),Z={},X=new Eq(W,this.em),z=X.getRelationalKeys();for(let w of J){if(z.includes(w)){let Y=await X.persistRelation(w,$[w]);if(Array.isArray(Y)){let[L,U]=Y;Z[L]=U}continue}let G=W.getField(w);if(!G)throw new Error(`Field "${w}" not found on entity "${W.name}". Fields: ${W.getFillableFields().map((Y)=>Y.name).join(", ")}`);if(!G.isFillable(f))throw new Error(`Field "${w}" is not fillable on entity "${W.name}"`);Z[w]=await G.transformPersist($[w],this.em,f),Z[w]=this.em.connection.toDriver(Z[w],G)}if(Object.keys(Z).length===0)throw new Error(`No data left to update "${W.name}"`);return Z}async performQuery($,f){return await new vq(this.em,this.entity,{silent:!1,...f}).execute($)}async insertOne($){let f=this.entity;if(f.type==="system"&&this.__unstable_disable_system_entity_creation)throw new Error(`Creation of system entity "${f.name}" is disabled`);let W=await this.emgr.emit(new m9.Events.MutatorInsertBefore({entity:f,data:$})),J=W.returned?W.params.data:$,Z=await this.getValidatedData({...f.getDefaultObject(),...J},"create"),X=f.getRequiredFields();for(let L of X)if(typeof Z[L.name]==="undefined"||Z[L.name]===null)throw new Error(`Field "${L.name}" is required`);let z=f.getPrimaryField(),w=z.getNewValue();if(w)Z={[z.name]:w,...Z};let G=this.conn.insertInto(f.name).values(Z).returning(f.getSelect()),Y=await this.performQuery(G,{single:!0});return await this.emgr.emit(new m9.Events.MutatorInsertAfter({entity:f,data:Y.data,changed:Z})),Y}async updateOne($,f){let W=this.entity;if(!$)throw new Error("ID must be provided for update");let J=await this.emgr.emit(new m9.Events.MutatorUpdateBefore({entity:W,entityId:$,data:f})),Z=J.returned?J.params.data:f,X=await this.getValidatedData(Z,"update"),z=this.conn.updateTable(W.name).set(X).where(W.id().name,"=",$).returning(W.getSelect()),w=await this.performQuery(z,{single:!0});return await this.emgr.emit(new m9.Events.MutatorUpdateAfter({entity:W,entityId:$,data:w.data,changed:X})),w}async deleteOne($){let f=this.entity;if(!$)throw new Error("ID must be provided for deletion");await this.emgr.emit(new m9.Events.MutatorDeleteBefore({entity:f,entityId:$}));let W=this.conn.deleteFrom(f.name).where(f.id().name,"=",$).returning(f.getSelect()),J=await this.performQuery(W,{single:!0});return await this.emgr.emit(new m9.Events.MutatorDeleteAfter({entity:f,entityId:$,data:J.data})),J}getValidOptions($){let f=this.entity,W={};if($?.where){let J=Vf.getPropertyNames($.where).filter((Z)=>{return typeof f.getField(Z)==="undefined"});if(J.length>0)throw new Lf(`Invalid where field(s): ${J.join(", ")}`);W.where=$.where}return W}appendWhere($,f){let W=this.entity,J=W.name,Z=(X)=>`${J}.${X}`;if(f){let X=Vf.getPropertyNames(f).filter((z)=>{return typeof W.getField(z)==="undefined"});if(X.length>0)throw new Lf(`Invalid where field(s): ${X.join(", ")}`);return Vf.addClause($,f)}return $}async deleteWhere($){let f=this.entity;if(!$||typeof $!=="object"||Object.keys($).length===0)throw new Error("Where clause must be provided for mass deletion");let W=this.appendWhere(this.conn.deleteFrom(f.name),$).returning(f.getSelect());return await this.performQuery(W)}async updateWhere($,f){let W=this.entity,J=await this.getValidatedData($,"update");if(!f||typeof f!=="object"||Object.keys(f).length===0)throw new Error("Where clause must be provided for mass update");let Z=this.appendWhere(this.conn.updateTable(W.name),f).set(J).returning(W.getSelect());return await this.performQuery(Z)}async insertMany($){let f=this.entity;if(f.type==="system"&&this.__unstable_disable_system_entity_creation)throw new Error(`Creation of system entity "${f.name}" is disabled`);let W=[];for(let Z of $){let X={...f.getDefaultObject(),...await this.getValidatedData(Z,"create")},z=f.getRequiredFields();for(let w of z)if(typeof X[w.name]==="undefined"||X[w.name]===null)throw new Error(`Field "${w.name}" is required`);W.push(X)}let J=this.conn.insertInto(f.name).values(W).returning(f.getSelect());return await this.performQuery(J)}}});var BG,Ah,FG,k00,y00,j00,g00=($)=>R.anyOf([BG,R.array(BG),$],{coerce:function(f,W={}){let J=f;if(typeof J==="string")if(J.match(/^\{/)||J.match(/^\[/))J=JSON.parse(J);else if(J.includes(","))J=J.split(",");else J=[J];if(Array.isArray(J))J=J.reduce((Z,X)=>{return Z[X]={},Z},{});if(U6(J))for(let Z in J)J[Z]=$.coerce(J[Z],W);return J}}),Qf,xh=()=>Qf.template({},{withOptional:!0});var kq=K(()=>{_();NG();_();BG=R.string({pattern:"^(?:[a-zA-Z_$][\\w$]*)(?:,[a-zA-Z_$][\\w$]*)*$"}),Ah=R.anyOf([BG,R.array(BG,{uniqueItems:!0})],{default:[],coerce:($)=>{if(Array.isArray($))return $;else if(typeof $==="string"){if($.includes(","))return $.split(",");return[$]}return[]}}),FG={by:"id",dir:"asc"},k00=R.object({by:R.string(),dir:R.string({enum:["asc","desc"]}).optional()}).strict(),y00=R.anyOf([R.string(),k00],{default:FG,coerce:($)=>{if(typeof $==="string"){if(/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test($)){let f=$[0]==="-"?"desc":"asc";return{by:f==="desc"?$.slice(1):$,dir:f}}else if(/^{.*}$/.test($))return{...FG,...JSON.parse($)};return A.warn(`Invalid sort given: '${JSON.stringify($)}'`),FG}else if(U6($))return{...FG,...$};return $}}),j00=R.anyOf([R.string(),R.object({})],{default:{},examples:[{attribute:{$eq:1}}],coerce:($)=>{let f=typeof $==="string"?JSON.parse($):$;return Vf.convert(f)}}),Qf=R.recursive(($)=>R.object({limit:R.number({default:10}),offset:R.number({default:0}),sort:y00,where:j00,select:Ah,join:Ah,with:g00($)}).partial())});class X7{static buildClause($,f,W,J){let Z=$.relationOf(W.name,J);if(!Z)throw new Error(`Relation "${J}" not found`);return Z.buildJoin(W,f,J)}static getJoinedEntityNames($,f,W){return W.flatMap((J)=>{let Z=$.relationOf(f.name,J);if(!Z)throw new Error(`Relation "${J}" not found`);let X=Z.other(f);if(Z instanceof af)return[X.entity.name];else if(Z instanceof a$)return[X.entity.name,Z.connectionEntity.name];return[]})}static addClause($,f,W,J){if(J.length===0)return f;let Z=f;for(let X of J)Z=X7.buildClause($,Z,W,X);return Z}}var _h=K(()=>{y4()});var yq;var jq=K(()=>{Dq();_();yq=class yq extends Z7{em;entity;constructor($,f,W){super($.connection,{hydrator:(J)=>$.hydrate(f.name,J),beforeExecute:(J)=>{if(!W?.silent)A.debug(`Query:
${J.sql}
`,J.parameters)},onError:(J)=>{if(W?.silent!==!0)throw A.error("Repository:",String(J)),J},...W});this.em=$;this.entity=f}shouldIncludeCounts($){if($===void 0)return this.conn.supports("softscans");return $}async execute($,f){if(this.shouldIncludeCounts(f?.includeCounts)){let J=(w="count")=>this.conn.kysely.fn.countAll().as(w),Z=$.clearSelect().select(J()).clearLimit().clearOffset().clearGroupBy().clearOrderBy(),X=this.conn.kysely.selectFrom(this.entity.name).select(J()),z=$.compile();this.options.beforeExecute?.(z);try{let w=performance.now(),[G,Y,L]=await this.em.connection.executeQueries(z,Z,X);this.time=Number.parseFloat((performance.now()-w).toFixed(2)),this.results.push({...G,data:this.options.hydrator?.(G.rows),items:G.rows.length,count:HH(Y.rows[0]?.count??0),total:HH(L.rows[0]?.count??0),time:this.time,sql:z.sql,parameters:[...z.parameters]})}catch(w){if(this.options.onError)await this.options.onError(w);else throw w}return this}return await super.execute($)}get count(){return this.first().count}get total(){return this.first().total}additionalMetaKeys(){return["count","total"]}}});var g4;var Nh=K(()=>{_();M2();T2();B$();PZ();kq();j4();_h();jq();g4=class g4{em;entity;options;static Events=g8;emgr;constructor($,f,W={}){this.em=$;this.entity=f;this.options=W;this.emgr=W?.emgr??new Q$(T9)}cloneFor($,f={}){return new g4(this.em,this.em.entity($),{...this.options,...f,emgr:this.emgr})}get conn(){return this.em.connection.kysely}checkIndex($,f,W){if(!this.em.getIndexedFields($).map((Z)=>Z.name).includes(f)&&this.options?.silent!==!0)A.warn(`Field "${$}.${f}" used in "${W}" is not indexed`)}getValidOptions($){let f=this.entity,W={...structuredClone(xh()),sort:f.getDefaultSort(),select:f.getSelect()};if(!$)return W;if($.sort){if(!W.select.includes($.sort.by))throw new Lf(`Invalid sort field "${$.sort.by}"`);if(!["asc","desc"].includes($.sort.dir))throw new Lf(`Invalid sort direction "${$.sort.dir}"`);this.checkIndex(f.name,$.sort.by,"sort"),W.sort={dir:$.sort.dir??"asc",by:$.sort.by}}if($.select&&$.select.length>0){let J=$.select.filter((Z)=>!W.select.includes(Z));if(J.length>0)throw new Lf(`Invalid select field(s): ${J.join(", ")}`).context({entity:f.name,valid:W.select});W.select=$.select}if($.with){let J=RW.validateWiths(this.em,f.name,$.with);W.with=$.with}if($.join&&$.join.length>0)for(let J of $.join){if(!this.em.relationOf(f.name,J))throw new Lf(`JOIN: "${J}" is not a relation of "${f.name}"`);W.join.push(J)}if($.where){let J=[f.name];if(W.join?.length>0)J.push(...X7.getJoinedEntityNames(this.em,f,W.join));let Z=Vf.getPropertyNames($.where).filter((X)=>{if(X.includes(".")){let[z,w]=X.split(".");if(!J.includes(z))return!0;return this.checkIndex(z,w,"where"),!this.em.entity(z).getField(w)}return this.checkIndex(f.name,X,"where"),typeof f.getField(X)==="undefined"});if(Z.length>0)throw new Lf(`Invalid where field(s): ${Z.join(", ")}`).context({aliases:J,entity:f.name});W.where=$.where}if($.limit)W.limit=$.limit;if($.offset)W.offset=$.offset;return W}async performQuery($,f,W){return await new yq(this.em,this.entity,{silent:this.options.silent,...f}).execute($,{includeCounts:W?.includeCounts??this.options.includeCounts})}async triggerFindBefore($,f){let W=f.limit===1?g4.Events.RepositoryFindOneBefore:g4.Events.RepositoryFindManyBefore;await this.emgr.emit(new W({entity:$,options:f}))}async triggerFindAfter($,f,W){if(f.limit===1)await this.emgr.emit(new g4.Events.RepositoryFindOneAfter({entity:$,options:f,data:W}));else await this.emgr.emit(new g4.Events.RepositoryFindManyAfter({entity:$,options:f,data:W}))}async single($,f){await this.triggerFindBefore(this.entity,f);let W=await this.performQuery($,{single:!0});return await this.triggerFindAfter(this.entity,f,W.data),W}addOptionsToQueryBuilder($,f,W){let J=this.entity,Z=$??this.conn.selectFrom(J.name),X=W?.validate!==!1?this.getValidOptions(f):f;if(!X)return Z;let z=W?.alias??J.name,w=(L)=>`${z}.${L}`,G=W?.ignore??[],Y={limit:10,offset:0,...W?.defaults};if(!G.includes("select")&&X.select)Z=Z.select(J.getAliasedSelectFrom(X.select,z));if(!G.includes("with")&&X.with)Z=RW.addClause(this.em,Z,J,X.with);if(!G.includes("join")&&X.join)Z=X7.addClause(this.em,Z,J,X.join);if(!G.includes("where")&&X.where)Z=Vf.addClause(Z,X.where);if(!G.includes("limit")){if(Z=Z.limit(X.limit??Y.limit),!G.includes("offset"))Z=Z.offset(X.offset??Y.offset)}if(!G.includes("sort"))Z=Z.orderBy(w(X.sort?.by??"id"),X.sort?.dir??"asc");return Z}buildQuery($,f=[]){let W=this.entity,J=this.getValidOptions($);return{qb:this.addOptionsToQueryBuilder(void 0,J,{ignore:f,alias:W.name,validate:!1}),options:J}}async findId($,f){let{qb:W,options:J}=this.buildQuery({...f,where:{[this.entity.getPrimaryField().name]:$},limit:1},["offset","sort"]);return this.single(W,J)}async findOne($,f){let{qb:W,options:J}=this.buildQuery({...f,where:$,limit:1});return await this.single(W,J)}async findMany($){let{qb:f,options:W}=this.buildQuery($);await this.triggerFindBefore(this.entity,W);let J=await this.performQuery(f);return await this.triggerFindAfter(this.entity,W,J.data),J}async findManyByReference($,f,W){let J=this.entity,X=this.em.relations.listableRelationsOf(J).find((Y)=>Y.ref(f).reference===f);if(!X)throw new Error(`Relation "${f}" not found or not listable on entity "${J.name}"`);let z=X.other(J).entity,w=X.getReferenceQuery(z,$,f);if(!("where"in w)||Object.keys(w.where).length===0)throw new Error(`Invalid reference query for "${f}" on entity "${z.name}"`);let G={...W,...w,where:{...w.where,...W?.where??{}}};return this.cloneFor(z).findMany(G)}async count($){let f=this.entity,W=this.getValidOptions({where:$}),J=this.conn.fn.count(J0`*`).as("count"),Z=this.conn.selectFrom(f.name).select(J);if(W.where)Z=Vf.addClause(Z,W.where);return await this.performQuery(Z,{hydrator:(X)=>({count:X[0]?.count??0})},{includeCounts:!1})}async exists($){let f=this.entity,W=this.getValidOptions({where:$}),J=this.conn.fn.count(J0`*`).as("count"),Z=this.conn.selectFrom(f.name).select(J);return Z=Vf.addClause(Z,W.where).limit(1),await this.performQuery(Z,{hydrator:(X)=>({exists:X[0]?.count>0})})}}});class RW{static addClause($,f,W,J){if(!J||!U6(J))return console.warn(`'withs' undefined or invalid, given: ${JSON.stringify(J)}`),f;let Z=$.connection.fn,X=f;for(let[z,w]of Object.entries(J)){let G=$.relationOf(W.name,z);if(!G)throw new Error(`Relation "${W.name}<>${z}" not found`);let Y=G.ref(z).cardinality,L=Y===1?Z.jsonObjectFrom:Z.jsonArrayFrom;if(!L)throw new Error("Connection does not support jsonObjectFrom/jsonArrayFrom");let U=G.other(W);X=X.select((M)=>{let q=G.buildWith(W,z)(M);if(w)q=$.repo(U.entity).addOptionsToQueryBuilder(q,w,{ignore:["with","join",Y===1?"limit":void 0].filter(Boolean)});if(w.with)q=RW.addClause($,q,U.entity,w.with);return L(q).as(U.reference)})}return X}static validateWiths($,f,W){let J=0;if(!W||!U6(W))return W&&console.warn(`'withs' invalid, given: ${JSON.stringify(W)}`),J;let Z=[];for(let[X,z]of Object.entries(W)){if(!$.relationOf(f,X))throw new Lf(`WITH: "${X}" is not a relation of "${f}"`);if(J++,"with"in z)Z.push(RW.validateWiths($,X,z.with))}if(Z.length>0)J+=Math.max(...Z);return J}}var Sh=K(()=>{_();B$()});var j4=K(()=>{xG();TG();Oh();Nh();NG();Sh();jq();mq()});var k9;var TG=K(()=>{_();M2();T2();J5();B$();PZ();zh();xG();j4();k9=class k9{connection;_entities=[];_relations=[];_indices=[];_schema;emgr;static Events={...T9,...g8};constructor($,f,W=[],J=[],Z){if($.forEach((X)=>this.addEntity(X)),W.forEach((X)=>this.addRelation(X)),J.forEach((X)=>this.addIndex(X)),!F$.isConnection(f))throw new OM("");this.connection=f,this.emgr=Z??new Q$,this.emgr.registerEvents(k9.Events)}fork(){return new k9(this._entities,this.connection,this._relations,this._indices)}clear(){return this._entities=[],this._relations=[],this._indices=[],this}get entities(){return this._entities}get relations(){return new NM(this._relations)}get indices(){return this._indices}async ping(){return(await J0`SELECT 1`.execute(this.connection.kysely)).rows.length>0}addEntity($){let f=this.entities.find((W)=>W.name===$.name);if(f){if(JSON.stringify(f)===JSON.stringify($)){A.warn(`Entity "${$.name}" already exists, but it's the same, skipping adding it.`);return}throw new Error(`Entity "${$.name}" already exists`)}this.entities.push($)}__replaceEntity($,f=$.name){let W=this._entities.findIndex((J)=>J.name===f);if(W===-1)throw new Error(`Entity "${f}" not found and cannot be replaced`);this._entities[W]=$}entity($,f){let W=this.entities.find((J)=>P$.isEntity($)?J.name===$.name:J.name===$);if(!W){if(f===!0)return;throw new _M(P$.isEntity($)?$.name:$)}return W}hasEntity($){let f=typeof $==="string"?$:$.name;return this.entities.some((W)=>W.name===f)}hasIndex($){let f=typeof $==="string"?$:$.name;return this.indices.some((W)=>W.name===f)}getIndexedFields($){let f=this.entity($),W=this.getIndicesOf(f),J=f.fields.filter((X)=>X.type==="relation"),Z=W.map((X)=>X.fields[0]);return[f.getPrimaryField(),...J,...Z].filter(Boolean)}addRelation($){if(!this.entity($.source.entity.name)||!this.entity($.target.entity.name))throw new Error("Relation source or target entity not found");if(this._relations.find((W)=>{let J=W.source.entity.name===$.source.entity.name&&W.target.entity.name===$.target.entity.name,Z=W.source.reference===$.source.reference&&W.target.reference===$.target.reference;return J&&Z}))throw new Error(`Relation "${$.type}" between "${$.source.entity.name}" and "${$.target.entity.name}" already exists`);this._relations.push($),$.initialize(this)}relationsOf($){return this.relations.relationsOf(this.entity($))}relationOf($,f){return this.relations.relationOf(this.entity($),f)}hasRelations($){return this.relations.hasRelations(this.entity($))}relatedEntitiesOf($){return this.relations.relatedEntitiesOf(this.entity($))}relationReferencesOf($){return this.relations.relationReferencesOf(this.entity($))}repository($,f={}){return this.repo($,f)}repo($,f={}){return new g4(this,this.entity($),{...f,emgr:this.emgr})}mutator($){return new m9(this,this.entity($),{emgr:this.emgr})}addIndex($,f=!1){if(this.indices.find((W)=>W.name===$.name)){if(f)throw new Error(`Index "${$.name}" already exists`);return}this._indices.push($)}getIndicesOf($){let f=P$.isEntity($)?$:this.entity($);return this.indices.filter((W)=>W.entity.name===f.name)}schema(){if(!this._schema)this._schema=new AG(this);return this._schema}hydrate($,f){let W=this.entity($),J=[];for(let Z of f){for(let[X,z]of Object.entries(Z)){let w=W.getField(X);if(!w||w.isVirtual()){let G=this.relationOf($,X);if(G){if(!z)continue;z=G.hydrate(X,Array.isArray(z)?z:[z],this),Z[X]=z;continue}else if(w?.isVirtual())continue;throw new Error(`Field "${X}" not found on entity "${W.name}"`)}try{if(z===null&&w.hasDefault())Z[X]=w.getDefault();z=this.connection.fromDriver(z,w),Z[X]=w.transformRetrieve(z)}catch(G){throw new AM(`"${w.type}" field "${X}" on entity "${W.name}": ${G.message}`)}}J.push(Z)}return J}toJSON(){return{entities:Object.fromEntries(this.entities.map(($)=>[$.name,$.toJSON()])),relations:Object.fromEntries(this.relations.all.map(($)=>[$.getName(),$.toJSON()])),indices:Object.fromEntries(this.indices.map(($)=>[$.name,$.toJSON()]))}}}});var gq;var Fh=K(()=>{J5();gq=class gq extends F${name="dummy";supported={batching:!0};constructor(){super(void 0)}getFieldSchema($,f){throw new Error("Method not implemented.")}}});var bq,b4;var PG=K(()=>{sf();_();bq=R.strictObject({entity:R.string(),min_items:R.number(),max_items:R.number(),mime_types:R.array(R.string()),...X1.properties}).partial();b4=class b4 extends a0{type="media";constructor($,f){super($,{...f,fillable:["update"],virtual:!0})}getSchema(){return bq}getMaxItems(){return this.config.max_items}getMinItems(){return this.config.min_items}schema(){return}toJsonSchema(){let f=this.config?.min_items,W=this.config?.max_items;if(W===1)return{$ref:"../schema.json#/properties/media"};else return{type:"array",items:{$ref:"../schema.json#/properties/media"},minItems:f,maxItems:W}}}});class of{type;config;is_required;constructor($,f,W){this.type=$;this.config=f;this.is_required=W}required(){return this.is_required=!0,this}getField($){if(!CG[this.type])throw new Error(`Unknown field type: ${this.type}`);try{return CG[this.type]($)}catch(f){throw new Error(`Faild to construct field "${this.type}": ${f}`)}}make($){if(!CG[this.type])throw new Error(`Unknown field type: ${this.type}`);try{return CG[this.type]({entity:{name:"unknown",fields:{}},field_name:$,config:this.config,is_required:this.is_required})}catch(f){throw new Error(`Faild to construct field "${this.type}": ${f}`)}}}function ef($){return new of("text",$,!1)}function z7($){return new of("number",$,!1)}function w7($){return new of("date",{...$,type:"datetime"},!1)}function Bh($){return new of("boolean",$,!1)}function G7($){let W={options:{type:typeof $?.enum?.[0]!=="string"?"objects":"strings",values:$?.enum??[]}};return new of("enumm",W,!1)}function Th($){return new of("json",$,!1)}function Ph($){return new of("jsonSchema",$,!1)}function Ch($,f){if(f instanceof of)return f.make($);throw new Error("Invalid field")}function MW($,f,W,J){let Z=[];for(let[X,z]of Object.entries(f)){let w=z,G={entity:{name:$,fields:f},field_name:X,config:w.config,is_required:w.is_required};Z.push(w.getField(G))}return new P$($,Z,W,J)}function b00($){return{manyToOne:(f,W)=>{return new af($,f,W)},oneToOne:(f,W)=>{return new UW($,f,W)},manyToMany:(f,W,J)=>{let Z=[];if(J){let X=J,z=[],w=W?.connectionTable??a$.defaultConnectionTable($,f);for(let[G,Y]of Object.entries(J)){let L=Y,U={entity:{name:w,fields:X},field_name:G,config:L.config,is_required:L.is_required};z.push(L.getField(U))}Z.push(z)}return new a$($,f,W,Z)},polyToOne:(f,W)=>{return new U5($,f,{...W,targetCardinality:1})},polyToMany:(f,W)=>{return new U5($,f,W)}}}function u00($){return{on:(f,W)=>{let J=f.map((Z)=>{let X=$.field(Z);if(!X)throw new Error(`Field "${String(Z)}" not found on entity "${$.name}"`);return X});return new kZ($,J,W)}}}function EG($,f){let W=[],J=[],Z=(w)=>{return new Proxy(b00(w),{get(G,Y){return(...L)=>{return W.push(G[Y](...L)),Z(w)}}})},X=(w)=>{return new Proxy(u00(w),{get(G,Y){return(...L)=>{return J.push(G[Y](...L)),X(w)}}})};if(f)f({relation:Z,index:X},$);let z=new Eh($,W,J);return{DB:z.__entities,entities:z.__entities,relations:W,indices:J,proto:z,toJSON:()=>z.toJSON()}}var CG,Eh;var R5=K(()=>{Fh();TG();PG();sf();j4();y4();CG={text:($)=>new X5($.field_name,{...$.config,required:$.is_required}),number:($)=>new Z5($.field_name,{...$.config,required:$.is_required}),date:($)=>new b8($.field_name,{...$.config,required:$.is_required}),datetime:($)=>new b8($.field_name,{...$.config,required:$.is_required}),boolean:($)=>new CZ($.field_name,{...$.config,required:$.is_required}),enumm:($)=>new EZ($.field_name,{...$.config,required:$.is_required}),json:($)=>new hZ($.field_name,{...$.config,required:$.is_required}),jsonSchema:($)=>new DZ($.field_name,{...$.config,required:$.is_required}),media:($)=>new b4($.field_name,{...$.config,entity:$.entity.name,required:$.is_required}),medium:($)=>new b4($.field_name,{...$.config,entity:$.entity.name,required:$.is_required})};Eh=class Eh extends k9{__entities;constructor($,f=[],W=[]){super(Object.values($),new gq,f,W);this.__entities=$}withConnection($){return new k9(this.entities,$,this.relations.all,this.indices)}}});var uq=($,f,W)=>{return(J,Z)=>{let X=-1;return z(0);async function z(w){if(w<=X)throw new Error("next() called multiple times");X=w;let G,Y=!1,L;if($[w])L=$[w][0][0],J.req.routeIndex=w;else L=w===$.length&&Z||void 0;if(L)try{G=await L(J,()=>z(w+1))}catch(U){if(U instanceof Error&&f)J.error=U,G=await f(U,J),Y=!0;else throw U}else if(J.finalized===!1&&W)G=await W(J);if(G&&(J.finalized===!1||Y))J.res=G;return J}}};var hh=()=>{};var Dh;var vh=K(()=>{Dh=Symbol()});async function d00($,f){let W=await $.formData();if(W)return i00(W,f);return{}}function i00($,f){let W=Object.create(null);if($.forEach((J,Z)=>{if(!(f.all||Z.endsWith("[]")))W[Z]=J;else r00(W,Z,J)}),f.dot)Object.entries(W).forEach(([J,Z])=>{if(J.includes("."))l00(W,J,Z),delete W[J]});return W}var mh=async($,f=Object.create(null))=>{let{all:W=!1,dot:J=!1}=f,X=($ instanceof hG?$.raw.headers:$.headers).get("Content-Type");if(X?.startsWith("multipart/form-data")||X?.startsWith("application/x-www-form-urlencoded"))return d00($,{all:W,dot:J});return{}},r00=($,f,W)=>{if($[f]!==void 0)if(Array.isArray($[f]))$[f].push(W);else $[f]=[$[f],W];else if(!f.endsWith("[]"))$[f]=W;else $[f]=[W]},l00=($,f,W)=>{let J=$,Z=f.split(".");Z.forEach((X,z)=>{if(z===Z.length-1)J[X]=W;else{if(!J[X]||typeof J[X]!=="object"||Array.isArray(J[X])||J[X]instanceof File)J[X]=Object.create(null);J=J[X]}})};var kh=K(()=>{cq()});var yh=($)=>a5($,kJ),hG;var cq=K(()=>{vh();kh();O6();hG=class{raw;#$;#f;routeIndex=0;path;bodyCache={};constructor($,f="/",W=[[]]){this.raw=$,this.path=f,this.#f=W,this.#$={}}param($){return $?this.#W($):this.#J()}#W($){let f=this.#f[0][this.routeIndex][1][$],W=this.#Z(f);return W?/\%/.test(W)?yh(W):W:void 0}#J(){let $={},f=Object.keys(this.#f[0][this.routeIndex][1]);for(let W of f){let J=this.#Z(this.#f[0][this.routeIndex][1][W]);if(J&&typeof J==="string")$[W]=/\%/.test(J)?yh(J):J}return $}#Z($){return this.#f[1]?this.#f[1][$]:$}query($){return BN(this.url,$)}queries($){return TN(this.url,$)}header($){if($)return this.raw.headers.get($)??void 0;let f={};return this.raw.headers.forEach((W,J)=>{f[J]=W}),f}async parseBody($){return this.bodyCache.parsedBody??=await mh(this,$)}#X=($)=>{let{bodyCache:f,raw:W}=this,J=f[$];if(J)return J;let Z=Object.keys(f)[0];if(Z)return f[Z].then((X)=>{if(Z==="json")X=JSON.stringify(X);return new Response(X)[$]()});return f[$]=W[$]()};json(){return this.#X("json")}text(){return this.#X("text")}arrayBuffer(){return this.#X("arrayBuffer")}blob(){return this.#X("blob")}formData(){return this.#X("formData")}addValidatedData($,f){this.#$[$]=f}valid($){return this.#$[$]}get url(){return this.raw.url}get method(){return this.raw.method}get[Dh](){return this.#f}get matchedRoutes(){return this.#f[0].map(([[,$]])=>$)}get routePath(){return this.#f[0].map(([[,$]])=>$)[this.routeIndex].path}}});var $2,S0=($,f)=>{let W=new String($);return W.isEscaped=!0,W.callbacks=f,W},p00,DG=async($,f)=>{let W="";f||=[];let J=await Promise.all($);for(let Z=J.length-1;;Z--){if(W+=J[Z],Z--,Z<0)break;let X=J[Z];if(typeof X==="object")f.push(...X.callbacks||[]);let z=X.isEscaped;if(X=await(typeof X==="object"?X.toString():X),typeof X==="object")f.push(...X.callbacks||[]);if(X.isEscaped??z)W+=X;else{let w=[W];u2(X,w),W=w[0]}}return S0(W,f)},u2=($,f)=>{let W=$.search(p00);if(W===-1){f[0]+=$;return}let J,Z,X=0;for(Z=W;Z<$.length;Z++){switch($.charCodeAt(Z)){case 34:J=""";break;case 39:J="'";break;case 38:J="&";break;case 60:J="<";break;case 62:J=">";break;default:continue}f[0]+=$.substring(X,Z)+J,X=Z+1}f[0]+=$.substring(X,Z)},vG=($)=>{let f=$.callbacks;if(!f?.length)return $;let W=[$],J={};return f.forEach((Z)=>Z({phase:$2.Stringify,buffer:W,context:J})),W[0]},M5=async($,f,W,J,Z)=>{if(typeof $==="object"&&!($ instanceof String)){if(!($ instanceof Promise))$=$.toString();if($ instanceof Promise)$=await $}let X=$.callbacks;if(!X?.length)return Promise.resolve($);if(Z)Z[0]+=$;else Z=[$];let z=Promise.all(X.map((w)=>w({phase:f,buffer:Z,context:J}))).then((w)=>Promise.all(w.filter(Boolean).map((G)=>M5(G,f,!1,J,Z))).then(()=>Z[0]));if(W)return S0(await z,X);else return z};var qW=K(()=>{$2={Stringify:1,BeforeStream:2,Stream:3},p00=/[&<>'"]/});var n00="text/plain; charset=UTF-8",dq=($,f)=>{return{"Content-Type":$,...f}},jh=class{#$;#f;env={};#W;finalized=!1;error;#J;#Z;#X;#z;#w;#G;#Y;#K;#U;constructor($,f){if(this.#$=$,f)this.#Z=f.executionCtx,this.env=f.env,this.#G=f.notFoundHandler,this.#U=f.path,this.#K=f.matchResult}get req(){return this.#f??=new hG(this.#$,this.#U,this.#K),this.#f}get event(){if(this.#Z&&"respondWith"in this.#Z)return this.#Z;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#Z)return this.#Z;else throw Error("This context has no ExecutionContext")}get res(){return this.#X||=new Response(null,{headers:this.#Y??=new Headers})}set res($){if(this.#X&&$){$=new Response($.body,$);for(let[f,W]of this.#X.headers.entries()){if(f==="content-type")continue;if(f==="set-cookie"){let J=this.#X.headers.getSetCookie();$.headers.delete("set-cookie");for(let Z of J)$.headers.append("set-cookie",Z)}else $.headers.set(f,W)}}this.#X=$,this.finalized=!0}render=(...$)=>{return this.#w??=(f)=>this.html(f),this.#w(...$)};setLayout=($)=>this.#z=$;getLayout=()=>this.#z;setRenderer=($)=>{this.#w=$};header=($,f,W)=>{if(this.finalized)this.#X=new Response(this.#X.body,this.#X);let J=this.#X?this.#X.headers:this.#Y??=new Headers;if(f===void 0)J.delete($);else if(W?.append)J.append($,f);else J.set($,f)};status=($)=>{this.#J=$};set=($,f)=>{this.#W??=new Map,this.#W.set($,f)};get=($)=>{return this.#W?this.#W.get($):void 0};get var(){if(!this.#W)return{};return Object.fromEntries(this.#W)}#L($,f,W){let J=this.#X?new Headers(this.#X.headers):this.#Y??new Headers;if(typeof f==="object"&&"headers"in f){let X=f.headers instanceof Headers?f.headers:new Headers(f.headers);for(let[z,w]of X)if(z.toLowerCase()==="set-cookie")J.append(z,w);else J.set(z,w)}if(W)for(let[X,z]of Object.entries(W))if(typeof z==="string")J.set(X,z);else{J.delete(X);for(let w of z)J.append(X,w)}let Z=typeof f==="number"?f:f?.status??this.#J;return new Response($,{status:Z,headers:J})}newResponse=(...$)=>this.#L(...$);body=($,f,W)=>this.#L($,f,W);text=($,f,W)=>{return!this.#Y&&!this.#J&&!f&&!W&&!this.finalized?new Response($):this.#L($,f,dq(n00,W))};json=($,f,W)=>{return this.#L(JSON.stringify($),f,dq("application/json",W))};html=($,f,W)=>{let J=(Z)=>this.#L(Z,f,dq("text/html; charset=UTF-8",W));return typeof $==="object"?M5($,$2.Stringify,!1,{}).then(J):J($)};redirect=($,f)=>{return this.header("Location",String($)),this.newResponse(null,f??302)};notFound=()=>{return this.#G??=()=>new Response,this.#G(this)}};var iq=K(()=>{cq();qW()});var e0="ALL",gh="all",bh,mG="Can not add a route since the matcher is already built.",kG;var VW=K(()=>{bh=["get","post","put","delete","options","patch"],kG=class extends Error{}});var Y7="__COMPOSED_HANDLER";var rq=()=>{};var s00=($)=>{return $.text("404 Not Found",404)},uh=($,f)=>{if("getResponse"in $){let W=$.getResponse();return f.newResponse(W.body,W)}return console.error($),f.text("Internal Server Error",500)},lq=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#$="/";routes=[];constructor($={}){[...bh,gh].forEach((Z)=>{this[Z]=(X,...z)=>{if(typeof X==="string")this.#$=X;else this.#J(Z,this.#$,X);return z.forEach((w)=>{this.#J(Z,this.#$,w)}),this}}),this.on=(Z,X,...z)=>{for(let w of[X].flat()){this.#$=w;for(let G of[Z].flat())z.map((Y)=>{this.#J(G.toUpperCase(),this.#$,Y)})}return this},this.use=(Z,...X)=>{if(typeof Z==="string")this.#$=Z;else this.#$="*",X.unshift(Z);return X.forEach((z)=>{this.#J(e0,this.#$,z)}),this};let{strict:W,...J}=$;Object.assign(this,J),this.getPath=W??!0?$.getPath??BH:SN}#f(){let $=new lq({router:this.router,getPath:this.getPath});return $.errorHandler=this.errorHandler,$.#W=this.#W,$.routes=this.routes,$}#W=s00;errorHandler=uh;route($,f){let W=this.basePath($);return f.routes.map((J)=>{let Z;if(f.errorHandler===uh)Z=J.handler;else Z=async(X,z)=>(await uq([],f.errorHandler)(X,()=>J.handler(X,z))).res,Z[Y7]=J.handler;W.#J(J.method,J.path,Z)}),this}basePath($){let f=this.#f();return f._basePath=I6(this._basePath,$),f}onError=($)=>{return this.errorHandler=$,this};notFound=($)=>{return this.#W=$,this};mount($,f,W){let J,Z;if(W)if(typeof W==="function")Z=W;else if(Z=W.optionHandler,W.replaceRequest===!1)J=(w)=>w;else J=W.replaceRequest;let X=Z?(w)=>{let G=Z(w);return Array.isArray(G)?G:[G]}:(w)=>{let G=void 0;try{G=w.executionCtx}catch{}return[w.env,G]};J||=(()=>{let w=I6(this._basePath,$),G=w==="/"?0:w.length;return(Y)=>{let L=new URL(Y.url);return L.pathname=L.pathname.slice(G)||"/",new Request(L,Y)}})();let z=async(w,G)=>{let Y=await f(J(w.req.raw),...X(w));if(Y)return Y;await G()};return this.#J(e0,I6($,"*"),z),this}#J($,f,W){$=$.toUpperCase(),f=I6(this._basePath,f);let J={basePath:this._basePath,path:f,method:$,handler:W};this.router.add($,f,[W,J]),this.routes.push(J)}#Z($,f){if($ instanceof Error)return this.errorHandler($,f);throw $}#X($,f,W,J){if(J==="HEAD")return(async()=>new Response(null,await this.#X($,f,W,"GET")))();let Z=this.getPath($,{env:W}),X=this.router.match(J,Z),z=new jh($,{path:Z,matchResult:X,env:W,executionCtx:f,notFoundHandler:this.#W});if(X[0].length===1){let G;try{G=X[0][0][0][0](z,async()=>{z.res=await this.#W(z)})}catch(Y){return this.#Z(Y,z)}return G instanceof Promise?G.then((Y)=>Y||(z.finalized?z.res:this.#W(z))).catch((Y)=>this.#Z(Y,z)):G??this.#W(z)}let w=uq(X[0],this.errorHandler,this.#W);return(async()=>{try{let G=await w(z);if(!G.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return G.res}catch(G){return this.#Z(G,z)}})()}fetch=($,...f)=>{return this.#X($,f[1],f[0],$.method)};request=($,f,W,J)=>{if($ instanceof Request)return this.fetch(f?new Request($,f):$,W,J);return $=$.toString(),this.fetch(new Request(/^https?:\/\//.test($)?$:`http://localhost${I6("/",$)}`,f),W,J)};fire=()=>{addEventListener("fetch",($)=>{$.respondWith(this.#X($.request,$,void 0,$.request.method))})}};var ch=K(()=>{hh();iq();VW();rq();O6()});function a00($,f){if($.length===1)return f.length===1?$<f?-1:1:-1;if(f.length===1)return 1;if($===L7||$===K7)return 1;else if(f===L7||f===K7)return-1;if($===yG)return 1;else if(f===yG)return-1;return $.length===f.length?$<f?-1:1:f.length-$.length}var yG="[^/]+",L7=".*",K7="(?:|/.*)",QW,t00,jG=class{#$;#f;#W=Object.create(null);insert($,f,W,J,Z){if($.length===0){if(this.#$!==void 0)throw QW;if(Z)return;this.#$=f;return}let[X,...z]=$,w=X==="*"?z.length===0?["","",L7]:["","",yG]:X==="/*"?["","",K7]:X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),G;if(w){let Y=w[1],L=w[2]||yG;if(Y&&w[2]){if(L=L.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(L))throw QW}if(G=this.#W[L],!G){if(Object.keys(this.#W).some((U)=>U!==L7&&U!==K7))throw QW;if(Z)return;if(G=this.#W[L]=new jG,Y!=="")G.#f=J.varIndex++}if(!Z&&Y!=="")W.push([Y,G.#f])}else if(G=this.#W[X],!G){if(Object.keys(this.#W).some((Y)=>Y.length>1&&Y!==L7&&Y!==K7))throw QW;if(Z)return;G=this.#W[X]=new jG}G.insert(z,f,W,J,Z)}buildRegExpStr(){let f=Object.keys(this.#W).sort(a00).map((W)=>{let J=this.#W[W];return(typeof J.#f==="number"?`(${W})@${J.#f}`:t00.has(W)?`\\${W}`:W)+J.buildRegExpStr()});if(typeof this.#$==="number")f.unshift(`#${this.#$}`);if(f.length===0)return"";if(f.length===1)return f[0];return"(?:"+f.join("|")+")"}};var pq=K(()=>{QW=Symbol(),t00=new Set(".\\+*[^]$()")});var dh=class{#$={varIndex:0};#f=new jG;insert($,f,W){let J=[],Z=[];for(let z=0;;){let w=!1;if($=$.replace(/\{[^}]+\}/g,(G)=>{let Y=`@\\${z}`;return Z[z]=[Y,G],z++,w=!0,Y}),!w)break}let X=$.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let z=Z.length-1;z>=0;z--){let[w]=Z[z];for(let G=X.length-1;G>=0;G--)if(X[G].indexOf(w)!==-1){X[G]=X[G].replace(w,Z[z][1]);break}}return this.#f.insert(X,f,J,this.#$,W),J}buildRegExp(){let $=this.#f.buildRegExpStr();if($==="")return[/^$/,[],[]];let f=0,W=[],J=[];return $=$.replace(/#(\d+)|@(\d+)|\.\*\$/g,(Z,X,z)=>{if(X!==void 0)return W[++f]=Number(X),"$()";if(z!==void 0)return J[Number(z)]=++f,"";return""}),[new RegExp(`^${$}`),W,J]}};var ih=K(()=>{pq()});function ph($){return lh[$]??=new RegExp($==="*"?"":`^${$.replace(/\/\*$|([.\\+*[^\]$()])/g,(f,W)=>W?`\\${W}`:"(?:|/.*)")}$`)}function e00(){lh=Object.create(null)}function $10($){let f=new dh,W=[];if($.length===0)return o00;let J=$.map((Y)=>[!/\*|\/:/.test(Y[0]),...Y]).sort(([Y,L],[U,M])=>Y?1:U?-1:L.length-M.length),Z=Object.create(null);for(let Y=0,L=-1,U=J.length;Y<U;Y++){let[M,q,V]=J[Y];if(M)Z[q]=[V.map(([O])=>[O,Object.create(null)]),rh];else L++;let Q;try{Q=f.insert(q,L,M)}catch(O){throw O===QW?new kG(q):O}if(M)continue;W[L]=V.map(([O,x])=>{let y=Object.create(null);x-=1;for(;x>=0;x--){let[F,B]=Q[x];y[F]=B}return[O,y]})}let[X,z,w]=f.buildRegExp();for(let Y=0,L=W.length;Y<L;Y++)for(let U=0,M=W[Y].length;U<M;U++){let q=W[Y][U]?.[1];if(!q)continue;let V=Object.keys(q);for(let Q=0,O=V.length;Q<O;Q++)q[V[Q]]=w[q[V[Q]]]}let G=[];for(let Y in z)G[Y]=W[z[Y]];return[X,G,Z]}function IW($,f){if(!$)return;for(let W of Object.keys($).sort((J,Z)=>Z.length-J.length))if(ph(W).test(f))return[...$[W]];return}var rh,o00,lh,nq=class{name="RegExpRouter";#$;#f;constructor(){this.#$={[e0]:Object.create(null)},this.#f={[e0]:Object.create(null)}}add($,f,W){let J=this.#$,Z=this.#f;if(!J||!Z)throw new Error(mG);if(!J[$])[J,Z].forEach((w)=>{w[$]=Object.create(null),Object.keys(w[e0]).forEach((G)=>{w[$][G]=[...w[e0][G]]})});if(f==="/*")f="*";let X=(f.match(/\/:/g)||[]).length;if(/\*$/.test(f)){let w=ph(f);if($===e0)Object.keys(J).forEach((G)=>{J[G][f]||=IW(J[G],f)||IW(J[e0],f)||[]});else J[$][f]||=IW(J[$],f)||IW(J[e0],f)||[];Object.keys(J).forEach((G)=>{if($===e0||$===G)Object.keys(J[G]).forEach((Y)=>{w.test(Y)&&J[G][Y].push([W,X])})}),Object.keys(Z).forEach((G)=>{if($===e0||$===G)Object.keys(Z[G]).forEach((Y)=>w.test(Y)&&Z[G][Y].push([W,X]))});return}let z=Cz(f)||[f];for(let w=0,G=z.length;w<G;w++){let Y=z[w];Object.keys(Z).forEach((L)=>{if($===e0||$===L)Z[L][Y]||=[...IW(J[L],Y)||IW(J[e0],Y)||[]],Z[L][Y].push([W,X-G+w+1])})}}match($,f){e00();let W=this.#W();return this.match=(J,Z)=>{let X=W[J]||W[e0],z=X[2][Z];if(z)return z;let w=Z.match(X[0]);if(!w)return[[],rh];let G=w.indexOf("",1);return[X[1][G],w]},this.match($,f)}#W(){let $=Object.create(null);return Object.keys(this.#f).concat(Object.keys(this.#$)).forEach((f)=>{$[f]||=this.#J(f)}),this.#$=this.#f=void 0,$}#J($){let f=[],W=$===e0;if([this.#$,this.#f].forEach((J)=>{let Z=J[$]?Object.keys(J[$]).map((X)=>[X,J[$][X]]):[];if(Z.length!==0)W||=!0,f.push(...Z);else if($!==e0)f.push(...Object.keys(J[e0]).map((X)=>[X,J[e0][X]]))}),!W)return null;else return $10(f)}};var nh=K(()=>{VW();O6();pq();ih();rh=[],o00=[/^$/,[],Object.create(null)],lh=Object.create(null)});var sh=K(()=>{nh()});var sq=class{name="SmartRouter";#$=[];#f=[];constructor($){this.#$=$.routers}add($,f,W){if(!this.#f)throw new Error(mG);this.#f.push([$,f,W])}match($,f){if(!this.#f)throw new Error("Fatal error");let W=this.#$,J=this.#f,Z=W.length,X=0,z;for(;X<Z;X++){let w=W[X];try{for(let G=0,Y=J.length;G<Y;G++)w.add(...J[G]);z=w.match($,f)}catch(G){if(G instanceof kG)continue;throw G}this.match=w.match.bind(w),this.#$=[w],this.#f=void 0;break}if(X===Z)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,z}get activeRouter(){if(this.#f||this.#$.length!==1)throw new Error("No active router has been determined yet.");return this.#$[0]}};var th=K(()=>{VW()});var ah=K(()=>{th()});var H7,tq=class{#$;#f;#W;#J=0;#Z=H7;constructor($,f,W){if(this.#f=W||Object.create(null),this.#$=[],$&&f){let J=Object.create(null);J[$]={handler:f,possibleKeys:[],score:0},this.#$=[J]}this.#W=[]}insert($,f,W){this.#J=++this.#J;let J=this,Z=_N(f),X=[];for(let z=0,w=Z.length;z<w;z++){let G=Z[z],Y=Z[z+1],L=NN(G,Y),U=Array.isArray(L)?L[0]:G;if(U in J.#f){if(J=J.#f[U],L)X.push(L[1]);continue}if(J.#f[U]=new tq,L)J.#W.push(L),X.push(L[1]);J=J.#f[U]}return J.#$.push({[$]:{handler:W,possibleKeys:X.filter((z,w,G)=>G.indexOf(z)===w),score:this.#J}}),J}#X($,f,W,J){let Z=[];for(let X=0,z=$.#$.length;X<z;X++){let w=$.#$[X],G=w[f]||w[e0],Y={};if(G!==void 0){if(G.params=Object.create(null),Z.push(G),W!==H7||J&&J!==H7)for(let L=0,U=G.possibleKeys.length;L<U;L++){let M=G.possibleKeys[L],q=Y[G.score];G.params[M]=J?.[M]&&!q?J[M]:W[M]??J?.[M],Y[G.score]=!0}}}return Z}search($,f){let W=[];this.#Z=H7;let Z=[this],X=FH(f),z=[];for(let w=0,G=X.length;w<G;w++){let Y=X[w],L=w===G-1,U=[];for(let M=0,q=Z.length;M<q;M++){let V=Z[M],Q=V.#f[Y];if(Q)if(Q.#Z=V.#Z,L){if(Q.#f["*"])W.push(...this.#X(Q.#f["*"],$,V.#Z));W.push(...this.#X(Q,$,V.#Z))}else U.push(Q);for(let O=0,x=V.#W.length;O<x;O++){let y=V.#W[O],F=V.#Z===H7?{}:{...V.#Z};if(y==="*"){let j=V.#f["*"];if(j)W.push(...this.#X(j,$,V.#Z)),j.#Z=F,U.push(j);continue}if(!Y)continue;let[B,i,w0]=y,L0=V.#f[B],K0=X.slice(w).join("/");if(w0 instanceof RegExp){let j=w0.exec(K0);if(j){if(F[i]=j[0],W.push(...this.#X(L0,$,V.#Z,F)),Object.keys(L0.#f).length){L0.#Z=F;let y1=j[0].match(/\//)?.length??0;(z[y1]||=[]).push(L0)}continue}}if(w0===!0||w0.test(Y))if(F[i]=Y,L){if(W.push(...this.#X(L0,$,F,V.#Z)),L0.#f["*"])W.push(...this.#X(L0.#f["*"],$,F,V.#Z))}else L0.#Z=F,U.push(L0)}}Z=U.concat(z.shift()??[])}if(W.length>1)W.sort((w,G)=>{return w.score-G.score});return[W.map(({handler:w,params:G})=>[w,G])]}};var oh=K(()=>{VW();O6();H7=Object.create(null)});var aq=class{name="TrieRouter";#$;constructor(){this.#$=new tq}add($,f,W){let J=Cz(f);if(J){for(let Z=0,X=J.length;Z<X;Z++)this.#$.insert($,J[Z],W);return}this.#$.insert($,f,W)}match($,f){return this.#$.search($,f)}};var eh=K(()=>{O6();oh()});var $D=K(()=>{eh()});var o$;var oq=K(()=>{ch();sh();ah();$D();o$=class extends lq{constructor($={}){super($);this.router=$.router??new sq({routers:[new nq,new aq]})}}});var OW=K(()=>{oq()});async function f10($,f,W,J){let Z=eq.filter((G)=>G.version>$&&G.version<=f),X=Object.assign({},W),z=0,w=$;for(let G of Z)try{X=await G.up(X,J),w=G.version,z++}catch(Y){throw console.error(Y),new Error(`Migration ${G.version} failed: ${Y.message}`)}return[w,X]}async function WD($,f,W){return f10($,AW,f,W)}var eq,AW,fD="__bknd";var JD=K(()=>{_();j2();eq=[{version:1,up:async($)=>$},{version:2,up:async($,{db:f})=>{return $}},{version:3,up:async($)=>$},{version:4,up:async($,{db:f})=>{return{...$,auth:{...$.auth,basepath:"/api/auth2"}}}},{version:5,up:async($,{db:f})=>{let W=$.server.cors?.allow_methods??[];return k4($.server,"cors.allow_methods",[...new Set([...W,"PATCH"])]),$}},{version:6,up:async($,{db:f})=>{return $}},{version:7,up:async($,{db:f})=>{let{expiresIn:W,...J}=$.auth.jwt;return{...$,auth:{...$.auth,jwt:J}}}},{version:8,up:async($)=>{let f=M0($.auth.strategies,(W)=>{return{...W,enabled:!0}});return{...$,auth:{...$.auth,strategies:f}}}},{version:9,up:async($)=>{let{admin:f,...W}=$.server;return{...$,server:W}}}],AW=eq[eq.length-1]?.version??0});var ZD=($)=>{let W={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...$},J=((X)=>{if(typeof X==="string")if(X==="*")return()=>X;else return(z)=>X===z?z:null;else if(typeof X==="function")return X;else return(z)=>X.includes(z)?z:null})(W.origin),Z=((X)=>{if(typeof X==="function")return X;else if(Array.isArray(X))return()=>X;else return()=>[]})(W.allowMethods);return async function X(z,w){function G(L,U){z.res.headers.set(L,U)}let Y=J(z.req.header("origin")||"",z);if(Y)G("Access-Control-Allow-Origin",Y);if(W.origin!=="*"){let L=z.req.header("Vary");if(L)G("Vary",L);else G("Vary","Origin")}if(W.credentials)G("Access-Control-Allow-Credentials","true");if(W.exposeHeaders?.length)G("Access-Control-Expose-Headers",W.exposeHeaders.join(","));if(z.req.method==="OPTIONS"){if(W.maxAge!=null)G("Access-Control-Max-Age",W.maxAge.toString());let L=Z(z.req.header("origin")||"",z);if(L.length)G("Access-Control-Allow-Methods",L.join(","));let U=W.allowHeaders;if(!U?.length){let M=z.req.header("Access-Control-Request-Headers");if(M)U=M.split(/\s*,\s*/)}if(U?.length)G("Access-Control-Allow-Headers",U.join(",")),z.res.headers.append("Vary","Access-Control-Request-Headers");return z.res.headers.delete("Content-Length"),z.res.headers.delete("Content-Type"),new Response(null,{headers:z.res.headers,status:204,statusText:"No Content"})}await w()}};var XD=()=>{};class gG{_schema;options;_default;_value;_config;_restriction_bypass=!1;constructor($,f,W){this._schema=$;this.options=W;this._default=R6($.template({},{withOptional:!0})),this._value=R6(F0($,structuredClone(f??{}),{withDefaults:!0,forceParse:this.isForceParse(),skipMark:this.isForceParse()})),this._config=R6(this._value)}isForceParse(){return this.options?.forceParse??!0}default(){return this._default}async onBeforeUpdate($,f){if(this.options?.onBeforeUpdate)return this.options.onBeforeUpdate($,f);return f}get($){if($?.stripMark)return gJ(this._config);return this._config}clone(){return structuredClone(this._config)}async set($,f){let W=F0(this._schema,structuredClone($),{coerce:!1,forceParse:!0,skipMark:this.isForceParse()}),J=await this.onBeforeUpdate(this._config,W);if(this._value=R6(J),this._config=R6(J),f!==!0)await this.options?.onUpdate?.(this._config);return this._config}bypass(){return this._restriction_bypass=!0,this}throwIfRestricted($){if(this._restriction_bypass){this._restriction_bypass=!1;return}let f=this.options?.restrictPaths??[];if(Array.isArray(f)&&f.length>0){for(let W of f)if(typeof $==="string"?$.startsWith(W):W7($,W))throw new Error(`Path "${W}" is restricted`)}return}async patch($,f){let W=this.clone(),J=$.length>0?k4({},$,f):f;this.throwIfRestricted(J);let Z=dK(W,J,(z,w)=>{if(Array.isArray(z)&&Array.isArray(w))return w});if(this.options?.overwritePaths){let w=cK(f).map((G)=>{return $.length>0?$+"."+G:G}).filter((G)=>{return this.options?.overwritePaths?.some((Y)=>{if(typeof Y==="string")return G===Y;else return Y.test(G)})});if(w.length>0){let G=w.length>1?w.filter((Y)=>w.some((L)=>{return L!==Y&&L.startsWith(Y)})):w;for(let Y of G)k4(Z,Y,k2(J,Y))}}let X=await this.set(Z);return[J,X]}async overwrite($,f){let W=this.clone(),J=$.length>0?k4({},$,f):f;this.throwIfRestricted(J);let Z=k4(W,$,f),X=await this.set(Z);return[J,X]}has($){let f=$.split(".");if(f.length>1){let W=f.slice(0,-1).join(".");if(!W7(this._config,W))throw new Error(`Parent path "${W}" does not exist`)}return W7(this._config,$)}async remove($){if(this.throwIfRestricted($),!this.has($))throw new Error(`Path "${$}" does not exist`);let f=this.clone(),W=k2(f,$),J=xq(f,$),Z=await this.set(J);return[W,Z]}}var zD=K(()=>{j2();_()});var C$;var q5=K(()=>{zD();C$=class C${_ctx;_built=!1;_schema;_listener=()=>null;constructor($,f){this._ctx=f;this._schema=new gG(this.getSchema(),$,{forceParse:this.useForceParse(),onUpdate:async(W)=>{await this._listener(W)},restrictPaths:this.getRestrictedPaths(),overwritePaths:this.getOverwritePaths(),onBeforeUpdate:this.onBeforeUpdate.bind(this)})}static ctx_flags={sync_required:!1,ctx_reload_required:!1};onBeforeUpdate($,f){return f}setListener($){return this._listener=$,this}useForceParse(){return!1}getRestrictedPaths(){return}getOverwritePaths(){return}get configDefault(){return this._schema.default()}get config(){return this._schema.get()}setContext($){return this._ctx=$,this}schema(){return this._schema}onServerInit($){}get ctx(){if(!this._ctx)throw new Error("Context not set");return this._ctx}async build(){throw new Error("Not implemented")}setBuilt(){this._built=!0,this._schema=new gG(this.getSchema(),this.toJSON(!0),{onUpdate:async($)=>{await this._listener($)},forceParse:this.useForceParse(),restrictPaths:this.getRestrictedPaths(),overwritePaths:this.getOverwritePaths(),onBeforeUpdate:this.onBeforeUpdate.bind(this)})}isBuilt(){return this._built}throwIfNotBuilt(){if(!this._built)throw new Error("Config not built: "+this.constructor.name)}toJSON($){return this.config}}});var u4,W10,$V,U7,fV,f2;var R7=K(()=>{Y9();V$();u4=class u4 extends w1{getSafeErrorAndCode(){return{error:"Invalid credentials",code:401}}toJSON(){if(Z1())return super.toJSON();return{error:this.getSafeErrorAndCode().error,type:"AuthException"}}};W10=class W10 extends u4{name="UserExistsException";code=422;constructor(){super("User already exists")}};$V=class $V extends u4{name="UserNotFoundException";code=404;constructor(){super("User not found")}};U7=class U7 extends u4{name="InvalidCredentialsException";code=401;constructor(){super("Invalid credentials")}};fV=class fV extends u4{name="UnableToCreateUserException";code=500;constructor(){super("Unable to create user")}};f2=class f2 extends u4{code=422;constructor($){super($??"Invalid conditions")}}});var wD,J10,WV;var GD=K(()=>{Y9();V$();_();XD();q5();R7();wD=["GET","POST","PATCH","PUT","DELETE"],J10=R.strictObject({cors:R.strictObject({origin:R.string({default:"*"}),allow_methods:R.array(R.string({enum:wD}),{default:wD,uniqueItems:!0}),allow_headers:R.array(R.string(),{default:["Content-Type","Content-Length","Authorization","Accept"]}),allow_credentials:R.boolean({default:!0})})});WV=class WV extends C${getRestrictedPaths(){return[]}get client(){return this.ctx.server}getSchema(){return J10}async build(){let $=this.config.cors.origin??"";this.client.use("*",ZD({origin:$.includes(",")?$.split(",").map((f)=>f.trim()):$,allowMethods:this.config.cors.allow_methods,allowHeaders:this.config.cors.allow_headers,credentials:this.config.cors.allow_credentials})),this.client.use("/",async(f,W)=>{if(await W(),!f.finalized||f.res.status===404){if(new URL(f.req.url).pathname==="/")f.res=void 0,f.res=Response.json({bknd:"hello world!"})}}),this.client.onError((f,W)=>{if(A.error("[AppServer:onError]",f),f instanceof Response)return f;if(f instanceof u4)return W.json(f.toJSON(),f.getSafeErrorAndCode().code);if(f instanceof w1)return W.json(f.toJSON(),f.code);if(f instanceof Error){if(Z1())return W.json({error:f.message,stack:f.stack},500)}return W.json({error:f.message},500)}),this.setBuilt()}toJSON($){return this.config}}});var M7={};V1(M7,{createUser:()=>JV});var JV;var bG=K(()=>{JV=new B0("auth.user.create")});var Q5={};V1(Q5,{rawQuery:()=>Z10,rawMutate:()=>X10,entityUpdate:()=>uG,entityRead:()=>W2,entityDelete:()=>cG,entityCreate:()=>V5,databaseSync:()=>ZV});var W2,V5,uG,cG,ZV,Z10,X10;var xW=K(()=>{W2=new B0("data.entity.read"),V5=new B0("data.entity.create"),uG=new B0("data.entity.update"),cG=new B0("data.entity.delete"),ZV=new B0("data.database.sync"),Z10=new B0("data.raw.query"),X10=new B0("data.raw.mutate")});var Ob0=class{initApp;#$;constructor($){this.initApp=$?.initApp,this.#$=$?.defaultAppOptions}createApp=($)=>{let f=new o$($&&this.#$?{...this.#$,...$}:$??this.#$);if(this.initApp)this.initApp(f);return f};createMiddleware=($)=>$;createHandlers=(...$)=>{return $.filter((f)=>f!==void 0)}},XV=($)=>$;var YD=K(()=>{oq()});function zV($){let f=$ instanceof Request?$:$.req.raw;return new URL(f.url).pathname}function z10($,f){let W=$.get("auth");if(!W)throw new Error("auth ctx not found");if(W.skip)return!0;let J=$.req.raw;if(!f)return!1;let Z=zV(J),X=f.some((z)=>M_(Z,z));return W.skip=X,X}var LD=($)=>XV(async(f,W)=>{if(!f.get("auth"))f.set("auth",{registered:!1,resolved:!1,skip:!1,user:void 0});let J=f.get("app"),Z=f.get("auth"),X=J?.module.auth.authenticator,z=z10(f,$?.skip)||!J?.module.auth.enabled;if(Z.registered)z=!0,A.warn(`auth middleware already registered for ${zV(f)}`);else if(Z.registered=!0,!z&&!Z.resolved&&J?.module.auth.enabled)Z.user=await X?.resolveAuthFromRequest(f),Z.resolved=!0;await W(),Z.skip=!1,Z.resolved=!1,Z.user=void 0}),KD=($,f)=>XV(async(W,J)=>{let Z=W.get("app"),X=W.get("auth");if(!X)throw new Error("auth ctx not found");if(!X.registered||!Z){let z=`auth middleware not registered, cannot check permissions for ${zV(W)}`;if(Z?.module.auth.enabled)throw new Error(z);else A.warn(z)}else if(!X.skip){let z=Z.modules.ctx().guard,w=Array.isArray($)?$:[$];if(f?.onGranted||f?.onDenied){let G;if(w.every((Y)=>z.granted(Y,W)))G=await f?.onGranted?.(W);else G=await f?.onDenied?.(W);if(G instanceof Response)return G}else w.some((G)=>z.throwUnlessGranted(G,W))}await J()});var HD=K(()=>{_();YD()});var dG={};V1(dG,{permission:()=>KD,auth:()=>LD});var wV=K(()=>{HD()});class If{middlewares=dG;create(){return If.createServer()}static createServer(){return new o$}getController(){return this.create()}isJsonRequest($){return $.req.header("Content-Type")==="application/json"||$.req.header("Accept")==="application/json"}notFound($){if(this.isJsonRequest($))return $.json({error:"Not found"},404);return $.notFound()}getEntitiesEnum($){let f=$.entities.map((W)=>W.name);return f.length>0?R.anyOf([R.string({enum:f}),R.string()]):R.string()}}var _W=K(()=>{OW();wV();_()});var GV;var UD=K(()=>{bG();xW();_W();_();GV=class GV extends If{auth;constructor($){super();this.auth=$}get guard(){return this.auth.ctx.guard}get em(){return this.auth.ctx.em}get userRepo(){let $=this.auth.config.entity_name;return this.em.repo($)}registerStrategyActions($,f){if(!this.auth.isStrategyEnabled($))return;let W=$.getActions?.();if(!W)return;let{auth:J,permission:Z}=this.middlewares,X=this.create().use(J()),z=$.getName(),{create:w,change:G}=W,Y=this.auth.em;if(w)X.post("/create",Z([JV,V5]),G0({summary:"Create a new user",tags:["auth"]}),async(L)=>{try{let U=await this.auth.authenticator.getBody(L),M=F0(w.schema,U,{}),q=await w.preprocess?.(M)??M,V=Y.mutator(this.auth.config.entity_name);V.__unstable_toggleSystemEntityCreation(!1);let{data:Q}=await V.insertOne({...q,strategy:z});return V.__unstable_toggleSystemEntityCreation(!0),L.json({success:!0,action:"create",strategy:z,data:Q})}catch(U){if(U instanceof G9)return L.json({success:!1,errors:U.errors},400);throw U}}),X.get("create/schema.json",G0({summary:"Get the schema for creating a user",tags:["auth"]}),async(L)=>{return L.json(w.schema)});f.route(`/${z}/actions`,X)}getController(){let{auth:$}=this.middlewares,f=this.create();f.get("/me",G0({summary:"Get the current user",tags:["auth"]}),$(),async(J)=>{let Z=J.get("auth")?.user;if(Z){let{data:X}=await this.userRepo.findId(Z.id);return await this.auth.authenticator?.requestCookieRefresh(J),J.json({user:X})}return J.json({user:null},403)}),f.get("/logout",G0({summary:"Logout the current user",tags:["auth"]}),$(),async(J)=>{if(await this.auth.authenticator.logout(J),this.auth.authenticator.isJsonRequest(J))return J.json({ok:!0});let Z=J.req.header("referer");if(Z)return J.redirect(Z);return J.redirect("/")}),f.get("/strategies",G0({summary:"Get the available authentication strategies",tags:["auth"]}),W0("query",R.object({include_disabled:R.boolean().optional()})),async(J)=>{let{include_disabled:Z}=J.req.valid("query"),{strategies:X,basepath:z}=this.auth.toJSON(!1);if(!Z)return J.json({strategies:M0(X??{},(w,G)=>{return this.auth.isStrategyEnabled(G)?w:void 0}),basepath:z});return J.json({strategies:X,basepath:z})});let W=this.auth.authenticator.getStrategies();for(let[J,Z]of Object.entries(W)){if(!this.auth.isStrategyEnabled(Z))continue;f.route(`/${J}`,Z.getController(this.auth.authenticator)),this.registerStrategyActions(Z,f)}return f}}});function NW($,f,W="info"){if($.req.header("Accept")?.includes("text/html"))EH($,w10,JSON.stringify({type:W,message:f}),{path:"/"})}var w10="__bknd_flash";var YV=K(()=>{e5()});var LV=($)=>{return HV($.replace(/_|-/g,(f)=>({_:"/","-":"+"})[f]??f))},KV=($)=>G10($).replace(/\/|\+/g,(f)=>({"/":"_","+":"-"})[f]??f),G10=($)=>{let f="",W=new Uint8Array($);for(let J=0,Z=W.length;J<Z;J++)f+=String.fromCharCode(W[J]);return btoa(f)},HV=($)=>{let f=atob($),W=new Uint8Array(new ArrayBuffer(f.length)),J=f.length/2;for(let Z=0,X=f.length-1;Z<=J;Z++,X--)W[Z]=f.charCodeAt(Z),W[X]=f.charCodeAt(X);return W};var UV=()=>{};var RV;var RD=K(()=>{RV=(($)=>{return $.HS256="HS256",$.HS384="HS384",$.HS512="HS512",$.RS256="RS256",$.RS384="RS384",$.RS512="RS512",$.PS256="PS256",$.PS384="PS384",$.PS512="PS512",$.ES256="ES256",$.ES384="ES384",$.ES512="ES512",$.EdDSA="EdDSA",$})(RV||{})});var MD,q7,qD,VD,QD,MV,ID,OD,SW;var qV=K(()=>{MD=class extends Error{constructor($){super(`${$} is not an implemented algorithm`);this.name="JwtAlgorithmNotImplemented"}},q7=class extends Error{constructor($){super(`invalid JWT token: ${$}`);this.name="JwtTokenInvalid"}},qD=class extends Error{constructor($){super(`token (${$}) is being used before it's valid`);this.name="JwtTokenNotBefore"}},VD=class extends Error{constructor($){super(`token (${$}) expired`);this.name="JwtTokenExpired"}},QD=class extends Error{constructor($,f){super(`Invalid "iat" claim, must be a valid number lower than "${$}" (iat: "${f}")`);this.name="JwtTokenIssuedAt"}},MV=class extends Error{constructor($){super(`jwt header is invalid: ${JSON.stringify($)}`);this.name="JwtHeaderInvalid"}},ID=class extends Error{constructor($){super(`required "kid" in jwt header: ${JSON.stringify($)}`);this.name="JwtHeaderRequiresKid"}},OD=class extends Error{constructor($){super(`token(${$}) signature mismatched`);this.name="JwtTokenSignatureMismatched"}},SW=(($)=>{return $.Encrypt="encrypt",$.Decrypt="decrypt",$.Sign="sign",$.Verify="verify",$.DeriveKey="deriveKey",$.DeriveBits="deriveBits",$.WrapKey="wrapKey",$.UnwrapKey="unwrapKey",$})(SW||{})});var c4,AD;var VV=K(()=>{c4=new TextEncoder,AD=new TextDecoder});async function _D($,f,W){let J=SD(f),Z=await Y10($,J);return await crypto.subtle.sign(J,Z,W)}async function ND($,f,W,J){let Z=SD(f),X=await L10($,Z);return await crypto.subtle.verify(Z,X,W,J)}function QV($){return HV($.replace(/-+(BEGIN|END).*/g,"").replace(/\s/g,""))}async function Y10($,f){if(!crypto.subtle||!crypto.subtle.importKey)throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");if(FD($)){if($.type!=="private"&&$.type!=="secret")throw new Error(`unexpected key type: CryptoKey.type is ${$.type}, expected private or secret`);return $}let W=[SW.Sign];if(typeof $==="object")return await crypto.subtle.importKey("jwk",$,f,!1,W);if($.includes("PRIVATE"))return await crypto.subtle.importKey("pkcs8",QV($),f,!1,W);return await crypto.subtle.importKey("raw",c4.encode($),f,!1,W)}async function L10($,f){if(!crypto.subtle||!crypto.subtle.importKey)throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");if(FD($)){if($.type==="public"||$.type==="secret")return $;$=await xD($)}if(typeof $==="string"&&$.includes("PRIVATE")){let J=await crypto.subtle.importKey("pkcs8",QV($),f,!0,[SW.Sign]);$=await xD(J)}let W=[SW.Verify];if(typeof $==="object")return await crypto.subtle.importKey("jwk",$,f,!1,W);if($.includes("PUBLIC"))return await crypto.subtle.importKey("spki",QV($),f,!1,W);return await crypto.subtle.importKey("raw",c4.encode($),f,!1,W)}async function xD($){if($.type!=="private")throw new Error(`unexpected key type: ${$.type}`);if(!$.extractable)throw new Error("unexpected private key is unextractable");let f=await crypto.subtle.exportKey("jwk",$),{kty:W}=f,{alg:J,e:Z,n:X}=f,{crv:z,x:w,y:G}=f;return{kty:W,alg:J,e:Z,n:X,crv:z,x:w,y:G,key_ops:[SW.Verify]}}function SD($){switch($){case"HS256":return{name:"HMAC",hash:{name:"SHA-256"}};case"HS384":return{name:"HMAC",hash:{name:"SHA-384"}};case"HS512":return{name:"HMAC",hash:{name:"SHA-512"}};case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"RS384":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case"RS512":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case"PS256":return{name:"RSA-PSS",hash:{name:"SHA-256"},saltLength:32};case"PS384":return{name:"RSA-PSS",hash:{name:"SHA-384"},saltLength:48};case"PS512":return{name:"RSA-PSS",hash:{name:"SHA-512"},saltLength:64};case"ES256":return{name:"ECDSA",hash:{name:"SHA-256"},namedCurve:"P-256"};case"ES384":return{name:"ECDSA",hash:{name:"SHA-384"},namedCurve:"P-384"};case"ES512":return{name:"ECDSA",hash:{name:"SHA-512"},namedCurve:"P-521"};case"EdDSA":return{name:"Ed25519",namedCurve:"Ed25519"};default:throw new MD($)}}function FD($){if(Kz()==="node"&&!!crypto.webcrypto)return $ instanceof crypto.webcrypto.CryptoKey;return $ instanceof CryptoKey}var BD=K(()=>{pK();UV();qV();VV()});function TD($){if(typeof $==="object"&&$!==null){let f=$;return"alg"in f&&Object.values(RV).includes(f.alg)&&(!("typ"in f)||f.typ==="JWT")}return!1}var IV=($)=>KV(c4.encode(JSON.stringify($)).buffer).replace(/=/g,""),K10=($)=>KV($).replace(/=/g,""),OV=($)=>JSON.parse(AD.decode(LV($))),PD=async($,f,W="HS256")=>{let J=IV($),Z;if(typeof f==="object"&&"alg"in f)W=f.alg,Z=IV({alg:W,typ:"JWT",kid:f.kid});else Z=IV({alg:W,typ:"JWT"});let X=`${Z}.${J}`,z=await _D(f,W,c4.encode(X)),w=K10(z);return`${X}.${w}`},AV=async($,f,W="HS256")=>{let J=$.split(".");if(J.length!==3)throw new q7($);let{header:Z,payload:X}=xV($);if(!TD(Z))throw new MV(Z);let z=Date.now()/1000|0;if(X.nbf&&X.nbf>z)throw new qD($);if(X.exp&&X.exp<=z)throw new VD($);if(X.iat&&z<X.iat)throw new QD(z,X.iat);let w=$.substring(0,$.lastIndexOf("."));if(!await ND(f,W,LV(J[2]),c4.encode(w)))throw new OD($);return X},CD=async($,f,W)=>{let J=H10($);if(!TD(J))throw new MV(J);if(!J.kid)throw new ID(J);if(f.jwks_uri){let X=await fetch(f.jwks_uri,W);if(!X.ok)throw new Error(`failed to fetch JWKS from ${f.jwks_uri}`);let z=await X.json();if(!z.keys)throw new Error('invalid JWKS response. "keys" field is missing');if(!Array.isArray(z.keys))throw new Error('invalid JWKS response. "keys" field is not an array');if(f.keys)f.keys.push(...z.keys);else f.keys=z.keys}else if(!f.keys)throw new Error('verifyFromJwks requires options for either "keys" or "jwks_uri" or both');let Z=f.keys.find((X)=>X.kid===J.kid);if(!Z)throw new q7($);return await AV($,Z,Z.alg||J.alg)},xV=($)=>{try{let[f,W]=$.split("."),J=OV(f),Z=OV(W);return{header:J,payload:Z}}catch{throw new q7($)}},H10=($)=>{try{let[f]=$.split(".");return OV(f)}catch{throw new q7($)}};var ED=K(()=>{UV();RD();BD();qV();VV()});var iG;var hD=K(()=>{ED();iG={sign:PD,verify:AV,decode:xV,verifyFromJwks:CD}});var _V,NV,SV;var DD=K(()=>{e5();hH();hD();iq();_V=iG.verify,NV=iG.decode,SV=iG.sign});var FV=K(()=>{DD()});class PV{strategies;userPool;config;constructor($,f,W){this.strategies=$;this.userPool=f;this.config=F0(U10,W??{})}async resolveLogin($,f,W,J,Z){try{let X=Z?.identifier||"email";if(typeof X!=="string"||X.length===0)throw new f2("Identifier must be a string");if(!(X in W))throw new f2(`Profile must have identifier "${X}"`);let z=await this.userPool.findBy(f.getName(),X,W[X]);if(!z.strategy_value)throw new f2("User must have a strategy value");else if(z.strategy!==f.getName())throw new f2("User signed up with a different strategy");await J(z);let w=await this.safeAuthResponse(z);return this.respondWithUser($,w,Z)}catch(X){return this.respondWithError($,X,Z)}}async resolveRegister($,f,W,J,Z){try{let X=Z?.identifier||"email";if(typeof X!=="string"||X.length===0)throw new f2("Identifier must be a string");if(!(X in W))throw new f2(`Profile must have identifier "${X}"`);if(!("strategy_value"in W))throw new f2("Profile must have a strategy value");let z=await this.userPool.create(f.getName(),{...W,strategy_value:W.strategy_value});await J(z);let w=await this.safeAuthResponse(z);return this.respondWithUser($,w,Z)}catch(X){return this.respondWithError($,X,Z)}}async respondWithUser($,f,W){let J=this.getSafeUrl($,W?.redirect??this.config.cookie.pathSuccess??"/");if("token"in f){if(await this.setAuthCookie($,f.token),this.isJsonRequest($)||W?.forceJsonResponse)return $.json(f);return $.redirect(J)}throw new w1("Invalid response")}async respondWithError($,f,W){if(A.error("respondWithError",f),this.isJsonRequest($)||W?.forceJsonResponse)throw f;await NW($,String(f),"error");let J=this.getSafeUrl($,$.req.header("Referer")??"/");return $.redirect(J)}getStrategies(){return this.strategies}strategy($){try{return this.strategies[$]}catch(f){throw new Error(`Strategy "${String($)}" not found`)}}async jwt($){let W={...LW($,this.config.jwt.fields),iat:Math.floor(Date.now()/1000)};if(this.config.jwt?.issuer)W.iss=this.config.jwt.issuer;if(this.config.jwt?.expires)W.exp=Math.floor(Date.now()/1000)+this.config.jwt.expires;let J=this.config.jwt.secret;if(!J||J.length===0)throw new Error("Cannot sign JWT without a secret");return SV(W,J,this.config.jwt?.alg??"HS256")}async safeAuthResponse($){let f=LW($,this.config.jwt.fields);return{user:f,token:await this.jwt(f)}}async verify($){try{let f=await _V($,this.config.jwt?.secret??"",this.config.jwt?.alg??"HS256");if(this.config.jwt?.issuer){if(f.iss!==this.config.jwt.issuer)throw new w1("Invalid issuer",403)}return f}catch(f){}return}get cookieOptions(){let{expires:$=vD,renew:f,...W}=this.config.cookie;return{...W,expires:new Date(Date.now()+$*1000)}}async getAuthCookie($){try{let f=this.config.jwt.secret,W=await yJ($,f,"auth");if(typeof W!=="string")return;return W}catch(f){if(f instanceof Error)A.error("[getAuthCookie]",f.message);return}}async requestCookieRefresh($){if(this.config.cookie.renew&&$.get("auth")?.user){let f=await this.getAuthCookie($);if(f)await this.setAuthCookie($,f)}}async setAuthCookie($,f){A.debug("setting auth cookie",q_(f));let W=this.config.jwt.secret;await vz($,"auth",f,W,this.cookieOptions)}async unsafeGetAuthCookie($){return o5("auth",$,this.config.jwt.secret,this.cookieOptions)}deleteAuthCookie($){A.debug("deleting auth cookie"),EN($,"auth",this.cookieOptions)}async logout($){if(A.info("Logging out"),$.set("auth",void 0),await this.getAuthCookie($))NW($,"Signed out","info");this.deleteAuthCookie($)}isJsonRequest($){return $.req.header("Content-Type")==="application/json"}async getBody($){if(this.isJsonRequest($))return await $.req.json();else return Object.fromEntries((await $.req.formData()).entries())}getSafeUrl($,f){let W=f.replace(/\/+$/,"/");if(!I_("redirects_non_fq"))return new URL($.req.url).origin+W;return W}async resolveAuthFromRequest($){let f;if($.req.raw.headers.has("Authorization"))f=String($.req.header("Authorization")).replace("Bearer ","");else f=await this.getAuthCookie($);if(f)return await this.verify(f);return}toJSON($){return{...this.config,jwt:$?this.config.jwt:void 0}}}var vD=604800,BV,TV,U10;var CV=K(()=>{Y9();YV();e5();FV();CH();j2();R7();_();BV=R.object({path:R.string({default:"/"}),sameSite:R.string({enum:["strict","lax","none"],default:"lax"}),secure:R.boolean({default:!0}),httpOnly:R.boolean({default:!0}),expires:R.number({default:vD}),partitioned:R.boolean({default:!1}),renew:R.boolean({default:!0}),pathSuccess:R.string({default:"/"}),pathLoggedOut:R.string({default:"/"})}).partial().strict(),TV=R.object({secret:gz({default:""}),alg:R.string({enum:["HS256","HS384","HS512"],default:"HS256"}).optional(),expires:R.number().optional(),issuer:R.string().optional(),fields:R.array(R.string(),{default:["id","email","role"]})},{default:{}}).strict(),U10=R.object({jwt:TV,cookie:BV})});function Q7($,f){if($==null)return!1;try{return $ instanceof f||Object.getPrototypeOf($)[Symbol.toStringTag]===f.prototype[Symbol.toStringTag]}catch{return!1}}function d4($){if(typeof $==="string")return q10.encode($);return V10.decode($)}function Q10($){if($ instanceof ArrayBuffer)$=new Uint8Array($);let f=[];for(let W=0;W<$.byteLength;W+=mD)f.push(String.fromCharCode.apply(null,$.subarray(W,W+mD)));return btoa(f.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function I10($){try{let f=atob($.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),W=new Uint8Array(f.length);for(let J=0;J<f.length;J++)W[J]=f.charCodeAt(J);return W}catch(f){throw new k("The input to be decoded is not correctly encoded.",{cause:f})}}function j9($){if(typeof $==="string")return I10($);return Q10($)}class dD{constructor($){this.cache=new Map,this._cache=new Map,this.maxSize=$}get($){let f=this.cache.get($);if(f)return f;if(f=this._cache.get($))return this.update($,f),f;return}has($){return this.cache.has($)||this._cache.has($)}set($,f){if(this.cache.has($))this.cache.set($,f);else this.update($,f);return this}delete($){if(this.cache.has($))return this.cache.delete($);if(this._cache.has($))return this._cache.delete($);return!1}update($,f){if(this.cache.set($,f),this.cache.size>=this.maxSize)this._cache=this.cache,this.cache=new Map}}function lD($){return $ instanceof CryptoKey}function pD($){return lD($)&&$.type==="private"}function O10($){return lD($)&&$.type==="public"}function mV($){try{let f=$.headers.get("dpop-nonce");if(f)rD.set(new URL($.url).origin,f)}catch{}return $}function FW($){if($===null||typeof $!=="object"||Array.isArray($))return!1;return!0}function pG($){if(Q7($,Headers))$=Object.fromEntries($.entries());let f=new Headers($);if(DV&&!f.has("user-agent"))f.set("user-agent",DV);if(f.has("authorization"))throw new TypeError('"options.headers" must not include the "authorization" header name');if(f.has("dpop"))throw new TypeError('"options.headers" must not include the "dpop" header name');return f}function kV($){if(typeof $==="function")$=$();if(!($ instanceof AbortSignal))throw new TypeError('"options.signal" must return or be an instance of AbortSignal');return $}async function nD($,f){if(!($ instanceof URL))throw new TypeError('"issuerIdentifier" must be an instance of URL');if($.protocol!=="https:"&&$.protocol!=="http:")throw new TypeError('"issuer.protocol" must be "https:" or "http:"');let W=new URL($.href);switch(f?.algorithm){case void 0:case"oidc":W.pathname=`${W.pathname}/.well-known/openid-configuration`.replace("//","/");break;case"oauth2":if(W.pathname==="/")W.pathname=".well-known/oauth-authorization-server";else W.pathname=`.well-known/oauth-authorization-server/${W.pathname}`.replace("//","/");break;default:throw new TypeError('"options.algorithm" must be "oidc" (default), or "oauth2"')}let J=pG(f?.headers);return J.set("accept","application/json"),(f?.[vV]||fetch)(W.href,{headers:Object.fromEntries(J.entries()),method:"GET",redirect:"manual",signal:f?.signal?kV(f.signal):null}).then(mV)}function N1($){return typeof $==="string"&&$.length!==0}async function sD($,f){if(!($ instanceof URL))throw new TypeError('"expectedIssuer" must be an instance of URL');if(!Q7(f,Response))throw new TypeError('"response" must be an instance of Response');if(f.status!==200)throw new k('"response" is not a conform Authorization Server Metadata response');V7(f);let W;try{W=await f.json()}catch(J){throw new k('failed to parse "response" body as JSON',{cause:J})}if(!FW(W))throw new k('"response" body must be a top level object');if(!N1(W.issuer))throw new k('"response" body "issuer" property must be a non-empty string');if(new URL(W.issuer).href!==$.href)throw new k('"response" body "issuer" does not match "expectedIssuer"');return W}function yV(){return j9(crypto.getRandomValues(new Uint8Array(32)))}function jV(){return yV()}async function tD($){if(!N1($))throw new TypeError('"codeVerifier" must be a non-empty string');return j9(await crypto.subtle.digest("SHA-256",d4($)))}function A10($){if($ instanceof CryptoKey)return{key:$};if(!($?.key instanceof CryptoKey))return{};if($.kid!==void 0&&!N1($.kid))throw new TypeError('"kid" must be a non-empty string');return{key:$.key,kid:$.kid,modifyAssertion:$[uD]}}function kD($){return encodeURIComponent($).replace(/%20/g,"+")}function x10($,f){let W=kD($),J=kD(f);return`Basic ${btoa(`${W}:${J}`)}`}function _10($){switch($.algorithm.hash.name){case"SHA-256":return"PS256";case"SHA-384":return"PS384";case"SHA-512":return"PS512";default:throw new Of("unsupported RsaHashedKeyAlgorithm hash name")}}function N10($){switch($.algorithm.hash.name){case"SHA-256":return"RS256";case"SHA-384":return"RS384";case"SHA-512":return"RS512";default:throw new Of("unsupported RsaHashedKeyAlgorithm hash name")}}function S10($){switch($.algorithm.namedCurve){case"P-256":return"ES256";case"P-384":return"ES384";case"P-521":return"ES512";default:throw new Of("unsupported EcKeyAlgorithm namedCurve")}}function aD($){switch($.algorithm.name){case"RSA-PSS":return _10($);case"RSASSA-PKCS1-v1_5":return N10($);case"ECDSA":return S10($);case"Ed25519":case"Ed448":return"EdDSA";default:throw new Of("unsupported CryptoKey algorithm name")}}function I5($){let f=$?.[lG];return typeof f==="number"&&Number.isFinite(f)?f:0}function gV($){let f=$?.[R10];return typeof f==="number"&&Number.isFinite(f)&&Math.sign(f)!==-1?f:30}function nG(){return Math.floor(Date.now()/1000)}function F10($,f){let W=nG()+I5(f);return{jti:yV(),aud:[$.issuer,$.token_endpoint],exp:W+60,iat:W,nbf:W,iss:f.client_id,sub:f.client_id}}async function B10($,f,W,J,Z){let X={alg:aD(W),kid:J},z=F10($,f);return Z?.(X,z),oD(X,z,W)}function I7($){if(typeof $!=="object"||$===null)throw new TypeError('"as" must be an object');if(!N1($.issuer))throw new TypeError('"as.issuer" property must be a non-empty string');return!0}function O7($){if(typeof $!=="object"||$===null)throw new TypeError('"client" must be an object');if(!N1($.client_id))throw new TypeError('"client.client_id" property must be a non-empty string');return!0}function yD($){if(!N1($))throw new TypeError('"client.client_secret" property must be a non-empty string');return $}function EV($,f){if(f!==void 0)throw new TypeError(`"options.clientPrivateKey" property must not be provided when ${$} client authentication method is used.`)}function jD($,f){if(f!==void 0)throw new TypeError(`"client.client_secret" property must not be provided when ${$} client authentication method is used.`)}async function T10($,f,W,J,Z){switch(W.delete("client_secret"),W.delete("client_assertion_type"),W.delete("client_assertion"),f.token_endpoint_auth_method){case void 0:case"client_secret_basic":{EV("client_secret_basic",Z),J.set("authorization",x10(f.client_id,yD(f.client_secret)));break}case"client_secret_post":{EV("client_secret_post",Z),W.set("client_id",f.client_id),W.set("client_secret",yD(f.client_secret));break}case"private_key_jwt":{if(jD("private_key_jwt",f.client_secret),Z===void 0)throw new TypeError('"options.clientPrivateKey" must be provided when "client.token_endpoint_auth_method" is "private_key_jwt"');let{key:X,kid:z,modifyAssertion:w}=A10(Z);if(!pD(X))throw new TypeError('"options.clientPrivateKey.key" must be a private CryptoKey');W.set("client_id",f.client_id),W.set("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),W.set("client_assertion",await B10($,f,X,z,w));break}case"tls_client_auth":case"self_signed_tls_client_auth":case"none":{jD(f.token_endpoint_auth_method,f.client_secret),EV(f.token_endpoint_auth_method,Z),W.set("client_id",f.client_id);break}default:throw new Of("unsupported client token_endpoint_auth_method")}}async function oD($,f,W){if(!W.usages.includes("sign"))throw new TypeError('CryptoKey instances used for signing assertions must include "sign" in their "usages"');let J=`${j9(d4(JSON.stringify($)))}.${j9(d4(JSON.stringify(f)))}`,Z=j9(await crypto.subtle.sign(Lv(W),W,d4(J)));return`${J}.${Z}`}async function eD($,f,W,J,Z,X){let{privateKey:z,publicKey:w,nonce:G=rD.get(W.origin)}=f;if(!pD(z))throw new TypeError('"DPoP.privateKey" must be a private CryptoKey');if(!O10(w))throw new TypeError('"DPoP.publicKey" must be a public CryptoKey');if(G!==void 0&&!N1(G))throw new TypeError('"DPoP.nonce" must be a non-empty string or undefined');if(!w.extractable)throw new TypeError('"DPoP.publicKey.extractable" must be true');let Y=nG()+Z,L={alg:aD(z),typ:"dpop+jwt",jwk:await C10(w)},U={iat:Y,jti:yV(),htm:J,nonce:G,htu:`${W.origin}${W.pathname}`,ath:X?j9(await crypto.subtle.digest("SHA-256",d4(X))):void 0};f[uD]?.(L,U),$.set("dpop",await oD(L,U,z))}async function P10($){let{kty:f,e:W,n:J,x:Z,y:X,crv:z}=await crypto.subtle.exportKey("jwk",$),w={kty:f,e:W,n:J,x:Z,y:X,crv:z};return rG.set($,w),w}async function C10($){return rG||(rG=new WeakMap),rG.get($)||P10($)}function gD($,f,W){if(typeof $!=="string"){if(W)throw new TypeError(`"as.mtls_endpoint_aliases.${f}" must be a string`);throw new TypeError(`"as.${f}" must be a string`)}return new URL($)}function $v($,f,W=!1){if(W&&$.mtls_endpoint_aliases&&f in $.mtls_endpoint_aliases)return gD($.mtls_endpoint_aliases[f],f,W);return gD($[f],f,W)}function fv($,f){if($.use_mtls_endpoint_aliases||f?.[M10])return!0;return!1}function O5($){let f=$;if(typeof f!=="object"||Array.isArray(f)||f===null)return!1;return f.error!==void 0}function E10($){if($.length>=2&&$[0]==='"'&&$[$.length-1]==='"')return $.slice(1,-1);return $}function v10($,f){let W=f.split(h10).slice(1);if(!W.length)return{scheme:$.toLowerCase(),parameters:{}};W[W.length-1]=W[W.length-1].replace(/,$/,"");let J={};for(let Z=1;Z<W.length;Z+=2){let X=Z;if(W[X][0]==='"')while(W[X].slice(-1)!=='"'&&++Z<W.length)W[X]+=W[Z];let z=W[X-1].replace(/^(?:, ?)|=$/g,"").toLowerCase();J[z]=E10(W[X])}return{scheme:$.toLowerCase(),parameters:J}}function bV($){if(!Q7($,Response))throw new TypeError('"response" must be an instance of Response');let f=$.headers.get("www-authenticate");if(f===null)return;let W=[];for(let{1:Z,index:X}of f.matchAll(D10))W.push([Z,X]);if(!W.length)return;return W.map(([Z,X],z,w)=>{let G=w[z+1],Y;if(G)Y=f.slice(X,G[1]);else Y=f.slice(X);return v10(Z,Y)})}async function m10($,f,W,J,Z,X){if(!N1($))throw new TypeError('"accessToken" must be a non-empty string');if(!(W instanceof URL))throw new TypeError('"url" must be an instance of URL');if(J=pG(J),X?.DPoP===void 0)J.set("authorization",`Bearer ${$}`);else await eD(J,X.DPoP,W,f.toUpperCase(),I5({[lG]:X?.[lG]}),$),J.set("authorization",`DPoP ${$}`);return(X?.[vV]||fetch)(W.href,{body:Z,headers:Object.fromEntries(J.entries()),method:f,redirect:"manual",signal:X?.signal?kV(X.signal):null}).then(mV)}async function uV($,f,W,J){I7($),O7(f);let Z=$v($,"userinfo_endpoint",fv(f,J)),X=pG(J?.headers);if(f.userinfo_signed_response_alg)X.set("accept","application/jwt");else X.set("accept","application/json"),X.append("accept","application/jwt");return m10(W,"GET",Z,X,null,{...J,[lG]:I5(f)})}function y10($){return $.headers.get("content-type")?.split(";")[0]}async function Wv($,f,W,J){if(I7($),O7(f),!Q7(J,Response))throw new TypeError('"response" must be an instance of Response');if(J.status!==200)throw new k('"response" is not a conform UserInfo Endpoint response');let Z;if(y10(J)==="application/jwt"){V7(J);let{claims:X,jwt:z}=await Kv(await J.text(),Hv.bind(void 0,f.userinfo_signed_response_alg,$.userinfo_signing_alg_values_supported),iV,I5(f),gV(f),f[cD]).then(u10.bind(void 0,f.client_id)).then(c10.bind(void 0,$.issuer));b10.set(J,z),Z=X}else{if(f.userinfo_signed_response_alg)throw new k("JWT UserInfo Response expected");V7(J);try{Z=await J.json()}catch(X){throw new k('failed to parse "response" body as JSON',{cause:X})}}if(!FW(Z))throw new k('"response" body must be a top level object');if(!N1(Z.sub))throw new k('"response" body "sub" property must be a non-empty string');switch(W){case k10:break;default:if(!N1(W))throw new k('"expectedSubject" must be a non-empty string');if(Z.sub!==W)throw new k('unexpected "response" body "sub" value')}return Z}async function j10($,f,W,J,Z,X,z){return await T10($,f,Z,X,z?.clientPrivateKey),X.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(z?.[vV]||fetch)(J.href,{body:Z,headers:Object.fromEntries(X.entries()),method:W,redirect:"manual",signal:z?.signal?kV(z.signal):null}).then(mV)}async function g10($,f,W,J,Z){let X=$v($,"token_endpoint",fv(f,Z));J.set("grant_type",W);let z=pG(Z?.headers);if(z.set("accept","application/json"),Z?.DPoP!==void 0)await eD(z,Z.DPoP,X,"POST",I5(f));return j10($,f,"POST",X,J,z,Z)}function cV($){if(!$.id_token)return;let f=Jv.get($);if(!f)throw new TypeError('"ref" was already garbage collected or did not resolve from the proper sources');return f[0]}async function Zv($,f,W,J=!1,Z=!1){if(I7($),O7(f),!Q7(W,Response))throw new TypeError('"response" must be an instance of Response');if(W.status!==200){let z;if(z=await p10(W))return z;throw new k('"response" is not a conform Token Endpoint response')}V7(W);let X;try{X=await W.json()}catch(z){throw new k('failed to parse "response" body as JSON',{cause:z})}if(!FW(X))throw new k('"response" body must be a top level object');if(!N1(X.access_token))throw new k('"response" body "access_token" property must be a non-empty string');if(!N1(X.token_type))throw new k('"response" body "token_type" property must be a non-empty string');if(X.token_type=X.token_type.toLowerCase(),X.token_type!=="dpop"&&X.token_type!=="bearer")throw new Of("unsupported `token_type` value");if(X.expires_in!==void 0&&(typeof X.expires_in!=="number"||X.expires_in<=0))throw new k('"response" body "expires_in" property must be a positive number');if(!Z&&X.refresh_token!==void 0&&!N1(X.refresh_token))throw new k('"response" body "refresh_token" property must be a non-empty string');if(X.scope!==void 0&&typeof X.scope!=="string")throw new k('"response" body "scope" property must be a string');if(!J){if(X.id_token!==void 0&&!N1(X.id_token))throw new k('"response" body "id_token" property must be a non-empty string');if(X.id_token){let{claims:z,jwt:w}=await Kv(X.id_token,Hv.bind(void 0,f.id_token_signed_response_alg,$.id_token_signing_alg_values_supported),iV,I5(f),gV(f),f[cD]).then(r10.bind(void 0,["aud","exp","iat","iss","sub"])).then(zv.bind(void 0,$.issuer)).then(Xv.bind(void 0,f.client_id));if(Array.isArray(z.aud)&&z.aud.length!==1){if(z.azp===void 0)throw new k('ID Token "aud" (audience) claim includes additional untrusted audiences');if(z.azp!==f.client_id)throw new k('unexpected ID Token "azp" (authorized party) claim value')}if(z.auth_time!==void 0&&(!Number.isFinite(z.auth_time)||Math.sign(z.auth_time)!==1))throw new k('ID Token "auth_time" (authentication time) must be a positive number');Jv.set(X,[z,w])}}return X}function u10($,f){if(f.claims.aud!==void 0)return Xv($,f);return f}function Xv($,f){if(Array.isArray(f.claims.aud)){if(!f.claims.aud.includes($))throw new k('unexpected JWT "aud" (audience) claim value')}else if(f.claims.aud!==$)throw new k('unexpected JWT "aud" (audience) claim value');return f}function c10($,f){if(f.claims.iss!==void 0)return zv($,f);return f}function zv($,f){if(f.claims.iss!==$)throw new k('unexpected JWT "iss" (issuer) claim value');return f}function d10($){return wv.add($),$}async function dV($,f,W,J,Z,X){if(I7($),O7(f),!wv.has(W))throw new TypeError('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()');if(!N1(J))throw new TypeError('"redirectUri" must be a non-empty string');if(!N1(Z))throw new TypeError('"codeVerifier" must be a non-empty string');let z=y9(W,"code");if(!z)throw new k('no authorization code in "callbackParameters"');let w=new URLSearchParams(X?.additionalParameters);return w.set("redirect_uri",J),w.set("code_verifier",Z),w.set("code",z),g10($,f,"authorization_code",w,X)}function r10($,f){for(let W of $)if(f.claims[W]===void 0)throw new k(`JWT "${W}" (${i10[W]}) claim missing`);return f}async function Gv($,f,W,J,Z){let X=await Zv($,f,W);if(O5(X))return X;if(!N1(X.id_token))throw new k('"response" body "id_token" property must be a non-empty string');Z??(Z=f.default_max_age??hV);let z=cV(X);if((f.require_auth_time||Z!==hV)&&z.auth_time===void 0)throw new k('ID Token "auth_time" (authentication time) claim missing');if(Z!==hV){if(typeof Z!=="number"||Z<0)throw new TypeError('"maxAge" must be a non-negative number');let w=nG()+I5(f),G=gV(f);if(z.auth_time+Z<w-G)throw new k("too much time has elapsed since the last End-User authentication")}switch(J){case void 0:case l10:if(z.nonce!==void 0)throw new k('unexpected ID Token "nonce" claim value');break;default:if(!N1(J))throw new TypeError('"expectedNonce" must be a non-empty string');if(z.nonce===void 0)throw new k('ID Token "nonce" claim missing');if(z.nonce!==J)throw new k('unexpected ID Token "nonce" claim value')}return X}async function Yv($,f,W){let J=await Zv($,f,W,!0);if(O5(J))return J;if(J.id_token!==void 0){if(typeof J.id_token==="string"&&J.id_token.length)throw new k("Unexpected ID Token returned, use processAuthorizationCodeOpenIDResponse() for OpenID Connect callback processing");delete J.id_token}return J}function V7($){if($.bodyUsed)throw new TypeError('"response" body has been used already')}async function p10($){if($.status>399&&$.status<500){V7($);try{let f=await $.json();if(FW(f)&&typeof f.error==="string"&&f.error.length){if(f.error_description!==void 0&&typeof f.error_description!=="string")delete f.error_description;if(f.error_uri!==void 0&&typeof f.error_uri!=="string")delete f.error_uri;if(f.algs!==void 0&&typeof f.algs!=="string")delete f.algs;if(f.scope!==void 0&&typeof f.scope!=="string")delete f.scope;return f}}catch{}}return}function bD($){if(typeof $.modulusLength!=="number"||$.modulusLength<2048)throw new k(`${$.name} modulusLength must be at least 2048 bits`)}function n10($){switch($){case"P-256":return"SHA-256";case"P-384":return"SHA-384";case"P-521":return"SHA-512";default:throw new Of}}function Lv($){switch($.algorithm.name){case"ECDSA":return{name:$.algorithm.name,hash:n10($.algorithm.namedCurve)};case"RSA-PSS":switch(bD($.algorithm),$.algorithm.hash.name){case"SHA-256":case"SHA-384":case"SHA-512":return{name:$.algorithm.name,saltLength:parseInt($.algorithm.hash.name.slice(-3),10)>>3};default:throw new Of}case"RSASSA-PKCS1-v1_5":return bD($.algorithm),$.algorithm.name;case"Ed448":case"Ed25519":return $.algorithm.name}throw new Of}async function s10($,f,W,J){let Z=`${$}.${f}`;if(!await crypto.subtle.verify(Lv(W),W,J,d4(Z)))throw new k("JWT signature verification failed")}async function Kv($,f,W,J,Z,X){let{0:z,1:w,2:G,length:Y}=$.split(".");if(Y===5)if(X!==void 0)$=await X($),{0:z,1:w,2:G,length:Y}=$.split(".");else throw new Of("JWE structure JWTs are not supported");if(Y!==3)throw new k("Invalid JWT");let L;try{L=JSON.parse(d4(j9(z)))}catch(Q){throw new k("failed to parse JWT Header body as base64url encoded JSON",{cause:Q})}if(!FW(L))throw new k("JWT Header must be a top level object");if(f(L),L.crit!==void 0)throw new k('unexpected JWT "crit" header parameter');let U=j9(G),M;if(W!==iV)M=await W(L),await s10(z,w,M,U);let q;try{q=JSON.parse(d4(j9(w)))}catch(Q){throw new k("failed to parse JWT Payload body as base64url encoded JSON",{cause:Q})}if(!FW(q))throw new k("JWT Payload must be a top level object");let V=nG()+J;if(q.exp!==void 0){if(typeof q.exp!=="number")throw new k('unexpected JWT "exp" (expiration time) claim type');if(q.exp<=V-Z)throw new k('unexpected JWT "exp" (expiration time) claim value, timestamp is <= now()')}if(q.iat!==void 0){if(typeof q.iat!=="number")throw new k('unexpected JWT "iat" (issued at) claim type')}if(q.iss!==void 0){if(typeof q.iss!=="string")throw new k('unexpected JWT "iss" (issuer) claim type')}if(q.nbf!==void 0){if(typeof q.nbf!=="number")throw new k('unexpected JWT "nbf" (not before) claim type');if(q.nbf>V+Z)throw new k('unexpected JWT "nbf" (not before) claim value, timestamp is > now()')}if(q.aud!==void 0){if(typeof q.aud!=="string"&&!Array.isArray(q.aud))throw new k('unexpected JWT "aud" (audience) claim type')}return{header:L,claims:q,signature:U,key:M,jwt:$}}function Hv($,f,W){if($!==void 0){if(W.alg!==$)throw new k('unexpected JWT "alg" header parameter');return}if(Array.isArray(f)){if(!f.includes(W.alg))throw new k('unexpected JWT "alg" header parameter');return}if(W.alg!=="RS256")throw new k('unexpected JWT "alg" header parameter')}function y9($,f){let{0:W,length:J}=$.getAll(f);if(J>1)throw new k(`"${f}" parameter must be provided only once`);return W}function rV($,f,W,J){if(I7($),O7(f),W instanceof URL)W=W.searchParams;if(!(W instanceof URLSearchParams))throw new TypeError('"parameters" must be an instance of URLSearchParams, or URL');if(y9(W,"response"))throw new k('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()');let Z=y9(W,"iss"),X=y9(W,"state");if(!Z&&$.authorization_response_iss_parameter_supported)throw new k('response parameter "iss" (issuer) missing');if(Z&&Z!==$.issuer)throw new k('unexpected "iss" (issuer) response parameter value');switch(J){case void 0:case sG:if(X!==void 0)throw new k('unexpected "state" response parameter encountered');break;case t10:break;default:if(!N1(J))throw new k('"expectedState" must be a non-empty string');if(X===void 0)throw new k('response parameter "state" missing');if(X!==J)throw new k('unexpected "state" response parameter value')}let z=y9(W,"error");if(z)return{error:z,error_description:y9(W,"error_description"),error_uri:y9(W,"error_uri")};let w=y9(W,"id_token"),G=y9(W,"token");if(w!==void 0||G!==void 0)throw new Of("implicit and hybrid flows are not supported");return d10(new URLSearchParams(W))}var DV,lG,R10,vV,uD,cD,_u0,M10,q10,V10,mD=32768,Of,iD,k,rD,rG,h10,D10,k10,Jv,b10,wv,i10,l10,hV,iV,t10,sG;var Uv=K(()=>{if(typeof navigator==="undefined"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))DV="oauth4webapi/v2.17.0";lG=Symbol(),R10=Symbol(),vV=Symbol(),uD=Symbol(),cD=Symbol(),_u0=Symbol(),M10=Symbol(),q10=new TextEncoder,V10=new TextDecoder;Of=class Of extends Error{constructor($){super($??"operation not supported");this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};iD=class iD extends Error{constructor($,f){super($,f);this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};k=iD,rD=new dD(100);h10=/((?:,|, )?[0-9a-zA-Z!#$%&'*+-.^_`|~]+=)/,D10=/(?:^|, ?)([0-9a-zA-Z!#$%&'*+\-.^_`|~]+)(?=$|[ ,])/g;k10=Symbol();Jv=new WeakMap,b10=new WeakMap;wv=new WeakSet;i10={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation"};l10=Symbol(),hV=Symbol();iV=Symbol();t10=Symbol(),sG=Symbol()});var Rv;var Mv=K(()=>{Rv={type:"oidc",client:{token_endpoint_auth_method:"client_secret_basic"},as:{issuer:"https://accounts.google.com"},profile:async($)=>{return{...$,sub:$.sub,email:$.email}}}});var qv;var Vv=K(()=>{qv={type:"oauth2",client:{token_endpoint_auth_method:"client_secret_basic"},as:{code_challenge_methods_supported:["S256"],issuer:"https://github.com",scopes_supported:["read:user","user:email"],scope_separator:" ",authorization_endpoint:"https://github.com/login/oauth/authorize",token_endpoint:"https://github.com/login/oauth/access_token",userinfo_endpoint:"https://api.github.com/user"},profile:async($,f,W)=>{try{let X=(await(await fetch("https://api.github.com/user/emails",{headers:{"User-Agent":"bknd",Accept:"application/json",Authorization:`Bearer ${W.access_token}`}})).json()).find((z)=>z.primary)?.email;if(!X)throw new Error("No primary email found");return{...$,sub:String($.id),email:X}}catch(J){throw new Error("Couldn't retrive github email")}}}});var A7={};V1(A7,{google:()=>Rv,github:()=>qv});var lV=K(()=>{Mv();Vv()});class x7{config;type;name;mode;actions={};constructor($,f,W,J){this.config=$;this.type=f;this.name=W;this.mode=J;this.config=F0(this.getSchema(),$??{})}registerAction($,f,W){this.actions[$]={schema:f,preprocess:W}}getType(){return this.type}getMode(){return this.mode}getName(){return this.name}toJSON($){return{type:this.getType(),config:$?this.config:void 0}}getActions(){return this.actions}}var pV=K(()=>{_()});var o10,A5,x5;var nV=K(()=>{OW();e5();Uv();lV();_();Y9();V$();pV();o10=R.object({name:R.string({enum:Object.keys(A7)}),type:R.string({enum:["oidc","oauth2"],default:"oauth2"}),client:R.object({client_id:R.string(),client_secret:R.string()}).strict()},{title:"OAuth"});A5=class A5 extends w1{error;step;name="OAuthCallbackException";constructor($,f){super("OAuthCallbackException on "+f);this.error=$;this.step=f}};x5=class x5 extends x7{constructor($){super($,"oauth",$.name,"external")}getSchema(){return o10}getIssuerConfig(){return A7[this.config.name]}async getConfig(){let $=this.getIssuerConfig();if($.type==="oidc"){let f=new URL($.as.issuer),W=await nD(f);$.as=await sD(f,W)}return{...$,type:$.type,client:{...$.client,...this.config.client}}}async getCodeChallenge($,f,W="S256"){let J=$.code_challenge_methods_supported?.includes(W),Z,X;if(J)Z=await tD(f),X=W;return{challenge_supported:J,challenge:Z,challenge_method:X}}async request($){let{client:f,as:W}=await this.getConfig(),{challenge_supported:J,challenge:Z,challenge_method:X}=await this.getCodeChallenge(W,$.state);if(!W.authorization_endpoint)throw new Error("authorization_endpoint is not provided");let z=$.scopes??W.scopes_supported;if(!Array.isArray(z)||z.length===0)throw new Error("No scopes provided");if(z.every((Y)=>!W.scopes_supported?.includes(Y)))throw new Error("Invalid scopes provided");let w=W.authorization_endpoint,G={client_id:f.client_id,redirect_uri:$.redirect_uri,response_type:"code",scope:z.join(W.scope_separator??" ")};if(J)G.code_challenge=Z,G.code_challenge_method=X;else G.nonce=$.state;return{url:new URL(w)+"?"+new URLSearchParams(G).toString(),endpoint:w,params:G}}async oidc($,f){let W=await this.getConfig(),{client:J,as:Z,type:X}=W,z=rV(Z,J,$,sG);if(O5(z))throw new A5(z,"validateAuthResponse");let w=await dV(Z,J,z,f.redirect_uri,f.state),G=bV(w);if(G)throw new A5(G,"www-authenticate");let{challenge_supported:Y,challenge:L}=await this.getCodeChallenge(Z,f.state),M=await Gv(Z,J,w,Y?void 0:L);if(O5(M))throw new A5(M,"processAuthorizationCodeOpenIDResponse");let q=cV(M),V=await uV(Z,J,M.access_token),Q=await Wv(Z,J,q.sub,V);return await W.profile(Q,W,q)}async oauth2($,f){let W=await this.getConfig(),{client:J,type:Z,as:X,profile:z}=W,w=rV(X,J,$,sG);if(O5(w))throw new A5(w,"validateAuthResponse");let G=await dV(X,J,w,f.redirect_uri,f.state),Y=bV(G);if(Y)throw new A5(Y,"www-authenticate");let L=G.clone(),U={};try{if(U=await Yv(X,J,G),O5(U))throw new Error}catch(V){U=await L.json()}let q=await(await uV(X,J,U.access_token)).json();return await W.profile(q,W,U)}async callback($,f){switch(this.getIssuerConfig().type){case"oidc":return await this.oidc($,f);case"oauth2":return await this.oauth2($,f);default:throw new Error("Unsupported type")}}getController($){let f=new o$,W="secret",J="_challenge",Z=async(z,w)=>{await vz(z,"_challenge",JSON.stringify(w),"secret",{secure:!0,httpOnly:!0,sameSite:"Lax",maxAge:300})},X=async(z)=>{if(z.req.header("X-State-Challenge"))return{state:z.req.header("X-State-Challenge"),action:z.req.header("X-State-Action"),mode:"token"};let w=await yJ(z,"secret","_challenge");try{return JSON.parse(w)}catch(G){throw new Error("Invalid state")}};return f.get("/callback",async(z)=>{let w=new URL(z.req.url),G=new URLSearchParams(w.search),Y=await X(z),L=Y.mode==="cookie"?w.origin+w.pathname:w.origin+w.pathname.replace("/callback","/token"),U=await this.callback(G,{redirect_uri:L,state:Y.state}),M={email:U.email,strategy_value:U.sub},q=async(Q)=>{if(Q.strategy_value!==U.sub)throw new w1("Invalid credentials")},V={redirect:Y.redirect,forceJsonResponse:Y.mode!=="cookie"};switch(Y.action){case"login":return $.resolveLogin(z,this,M,q,V);case"register":return $.resolveRegister(z,this,M,q,V);default:throw new Error("Invalid action")}}),f.get("/token",async(z)=>{let w=new URL(z.req.url),G=new URLSearchParams(w.search);return z.json({code:G.get("code")??null})}),f.post("/:action",async(z)=>{let w=z.req.param("action");if(!["login","register"].includes(w))return z.notFound();let G=new URL(z.req.url),Y=G.pathname.replace(`/${w}`,""),L=G.origin+Y+"/callback",U=new URL(z.req.header("Referer")??"/"),M=jV(),q=await this.request({redirect_uri:L,state:M});return await Z(z,{state:M,action:w,redirect:U.toString(),mode:"cookie"}),z.redirect(q.url)}),f.get("/:action",async(z)=>{let w=z.req.param("action");if(!["login","register"].includes(w))return z.notFound();let G=new URL(z.req.url),Y=G.pathname.replace(`/${w}`,""),L=G.origin+Y+"/token",U=jV(),M=await this.request({redirect_uri:L,state:U});if(Z1())return z.json({url:M.url,redirect_uri:L,challenge:U,action:w,params:M.params});return z.json({url:M.url,challenge:U,action:w})}),f}toJSON($){let f=$?this.config:bK(this.config,["secret","client_id"]);return{...super.toJSON($),config:{...f,type:this.getIssuerConfig().type}}}}});var sV,e10,_7;var Qv=K(()=>{nV();_();sV=R.string({pattern:"^(https?|wss?)://[^\\s/$.?#].[^\\s]*$"}),e10=R.strictObject({type:R.string({enum:["oidc","oauth2"],default:"oidc"}),name:R.string(),client:R.object({client_id:R.string(),client_secret:R.string(),token_endpoint_auth_method:R.string({enum:["client_secret_basic"]})}),as:R.strictObject({issuer:R.string(),code_challenge_methods_supported:R.string({enum:["S256"]}).optional(),scopes_supported:R.array(R.string()).optional(),scope_separator:R.string({default:" "}).optional(),authorization_endpoint:sV.optional(),token_endpoint:sV.optional(),userinfo_endpoint:sV.optional()})},{title:"Custom OAuth"});_7=class _7 extends x5{constructor($){super($);this.type="custom_oauth"}getIssuerConfig(){return{...this.config,profile:async($)=>$}}getSchema(){return e10}}});import $$0 from"crypto";function f$0($){try{return crypto.getRandomValues(new Uint8Array($))}catch{}try{return $$0.randomBytes($)}catch{}if(!Iv)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return Iv($)}function W$0($,f){if($=$||Fv,typeof $!=="number")throw Error("Illegal arguments: "+typeof $+", "+typeof f);if($<4)$=4;else if($>31)$=31;var W=[];if(W.push("$2b$"),$<10)W.push("0");return W.push($.toString()),W.push("$"),W.push(tV(f$0(N7),N7)),W.join("")}function aV($,f,W){if(typeof f==="function")W=f,f=void 0;if(typeof $==="function")W=$,$=void 0;if(typeof $==="undefined")$=Fv;else if(typeof $!=="number")throw Error("illegal arguments: "+typeof $);function J(Z){J2(function(){try{Z(null,W$0($))}catch(X){Z(X)}})}if(W){if(typeof W!=="function")throw Error("Illegal callback: "+typeof W);J(W)}else return new Promise(function(Z,X){J(function(z,w){if(z){X(z);return}Z(w)})})}function oV($,f,W,J){function Z(X){if(typeof $==="string"&&typeof f==="number")aV(f,function(z,w){Nv($,w,X,J)});else if(typeof $==="string"&&typeof f==="string")Nv($,f,X,J);else J2(X.bind(this,Error("Illegal arguments: "+typeof $+", "+typeof f)))}if(W){if(typeof W!=="function")throw Error("Illegal callback: "+typeof W);Z(W)}else return new Promise(function(X,z){Z(function(w,G){if(w){z(w);return}X(G)})})}function J$0($,f){var W=$.length^f.length;for(var J=0;J<$.length;++J)W|=$.charCodeAt(J)^f.charCodeAt(J);return W===0}function Sv($,f,W,J){function Z(X){if(typeof $!=="string"||typeof f!=="string"){J2(X.bind(this,Error("Illegal arguments: "+typeof $+", "+typeof f)));return}if(f.length!==60){J2(X.bind(this,null,!1));return}oV($,f.substring(0,29),function(z,w){if(z)X(z);else X(null,J$0(w,f))},J)}if(W){if(typeof W!=="function")throw Error("Illegal callback: "+typeof W);Z(W)}else return new Promise(function(X,z){Z(function(w,G){if(w){z(w);return}X(G)})})}function Z$0($){var f=0,W=0;for(var J=0;J<$.length;++J)if(W=$.charCodeAt(J),W<128)f+=1;else if(W<2048)f+=2;else if((W&64512)===55296&&($.charCodeAt(J+1)&64512)===56320)++J,f+=4;else f+=3;return f}function X$0($){var f=0,W,J,Z=new Array(Z$0($));for(var X=0,z=$.length;X<z;++X)if(W=$.charCodeAt(X),W<128)Z[f++]=W;else if(W<2048)Z[f++]=W>>6|192,Z[f++]=W&63|128;else if((W&64512)===55296&&((J=$.charCodeAt(X+1))&64512)===56320)W=65536+((W&1023)<<10)+(J&1023),++X,Z[f++]=W>>18|240,Z[f++]=W>>12&63|128,Z[f++]=W>>6&63|128,Z[f++]=W&63|128;else Z[f++]=W>>12|224,Z[f++]=W>>6&63|128,Z[f++]=W&63|128;return Z}function tV($,f){var W=0,J=[],Z,X;if(f<=0||f>$.length)throw Error("Illegal len: "+f);while(W<f){if(Z=$[W++]&255,J.push(BW[Z>>2&63]),Z=(Z&3)<<4,W>=f){J.push(BW[Z&63]);break}if(X=$[W++]&255,Z|=X>>4&15,J.push(BW[Z&63]),Z=(X&15)<<2,W>=f){J.push(BW[Z&63]);break}X=$[W++]&255,Z|=X>>6&3,J.push(BW[Z&63]),J.push(BW[X&63])}return J.join("")}function z$0($,f){var W=0,J=$.length,Z=0,X=[],z,w,G,Y,L,U;if(f<=0)throw Error("Illegal len: "+f);while(W<J-1&&Z<f){if(U=$.charCodeAt(W++),z=U<i4.length?i4[U]:-1,U=$.charCodeAt(W++),w=U<i4.length?i4[U]:-1,z==-1||w==-1)break;if(L=z<<2>>>0,L|=(w&48)>>4,X.push(String.fromCharCode(L)),++Z>=f||W>=J)break;if(U=$.charCodeAt(W++),G=U<i4.length?i4[U]:-1,G==-1)break;if(L=(w&15)<<4>>>0,L|=(G&60)>>2,X.push(String.fromCharCode(L)),++Z>=f||W>=J)break;U=$.charCodeAt(W++),Y=U<i4.length?i4[U]:-1,L=(G&3)<<6>>>0,L|=Y,X.push(String.fromCharCode(L)),++Z}var M=[];for(W=0;W<Z;W++)M.push(X[W].charCodeAt(0));return M}function S7($,f,W,J){var Z,X=$[f],z=$[f+1];return X^=W[0],Z=J[X>>>24],Z+=J[256|X>>16&255],Z^=J[512|X>>8&255],Z+=J[768|X&255],z^=Z^W[1],Z=J[z>>>24],Z+=J[256|z>>16&255],Z^=J[512|z>>8&255],Z+=J[768|z&255],X^=Z^W[2],Z=J[X>>>24],Z+=J[256|X>>16&255],Z^=J[512|X>>8&255],Z+=J[768|X&255],z^=Z^W[3],Z=J[z>>>24],Z+=J[256|z>>16&255],Z^=J[512|z>>8&255],Z+=J[768|z&255],X^=Z^W[4],Z=J[X>>>24],Z+=J[256|X>>16&255],Z^=J[512|X>>8&255],Z+=J[768|X&255],z^=Z^W[5],Z=J[z>>>24],Z+=J[256|z>>16&255],Z^=J[512|z>>8&255],Z+=J[768|z&255],X^=Z^W[6],Z=J[X>>>24],Z+=J[256|X>>16&255],Z^=J[512|X>>8&255],Z+=J[768|X&255],z^=Z^W[7],Z=J[z>>>24],Z+=J[256|z>>16&255],Z^=J[512|z>>8&255],Z+=J[768|z&255],X^=Z^W[8],Z=J[X>>>24],Z+=J[256|X>>16&255],Z^=J[512|X>>8&255],Z+=J[768|X&255],z^=Z^W[9],Z=J[z>>>24],Z+=J[256|z>>16&255],Z^=J[512|z>>8&255],Z+=J[768|z&255],X^=Z^W[10],Z=J[X>>>24],Z+=J[256|X>>16&255],Z^=J[512|X>>8&255],Z+=J[768|X&255],z^=Z^W[11],Z=J[z>>>24],Z+=J[256|z>>16&255],Z^=J[512|z>>8&255],Z+=J[768|z&255],X^=Z^W[12],Z=J[X>>>24],Z+=J[256|X>>16&255],Z^=J[512|X>>8&255],Z+=J[768|X&255],z^=Z^W[13],Z=J[z>>>24],Z+=J[256|z>>16&255],Z^=J[512|z>>8&255],Z+=J[768|z&255],X^=Z^W[14],Z=J[X>>>24],Z+=J[256|X>>16&255],Z^=J[512|X>>8&255],Z+=J[768|X&255],z^=Z^W[15],Z=J[z>>>24],Z+=J[256|z>>16&255],Z^=J[512|z>>8&255],Z+=J[768|z&255],X^=Z^W[16],$[f]=z^W[w$0+1],$[f+1]=X,$}function TW($,f){for(var W=0,J=0;W<4;++W)J=J<<8|$[f]&255,f=(f+1)%$.length;return{key:J,offp:f}}function xv($,f,W){var J=0,Z=[0,0],X=f.length,z=W.length,w;for(var G=0;G<X;G++)w=TW($,J),J=w.offp,f[G]=f[G]^w.key;for(G=0;G<X;G+=2)Z=S7(Z,0,f,W),f[G]=Z[0],f[G+1]=Z[1];for(G=0;G<z;G+=2)Z=S7(Z,0,f,W),W[G]=Z[0],W[G+1]=Z[1]}function Y$0($,f,W,J){var Z=0,X=[0,0],z=W.length,w=J.length,G;for(var Y=0;Y<z;Y++)G=TW(f,Z),Z=G.offp,W[Y]=W[Y]^G.key;Z=0;for(Y=0;Y<z;Y+=2)G=TW($,Z),Z=G.offp,X[0]^=G.key,G=TW($,Z),Z=G.offp,X[1]^=G.key,X=S7(X,0,W,J),W[Y]=X[0],W[Y+1]=X[1];for(Y=0;Y<w;Y+=2)G=TW($,Z),Z=G.offp,X[0]^=G.key,G=TW($,Z),Z=G.offp,X[1]^=G.key,X=S7(X,0,W,J),J[Y]=X[0],J[Y+1]=X[1]}function _v($,f,W,J,Z){var X=Bv.slice(),z=X.length,w;if(W<4||W>31)if(w=Error("Illegal number of rounds (4-31): "+W),J){J2(J.bind(this,w));return}else throw w;if(f.length!==N7)if(w=Error("Illegal salt length: "+f.length+" != "+N7),J){J2(J.bind(this,w));return}else throw w;W=1<<W>>>0;var G,Y,L=0,U;if(typeof Int32Array==="function")G=new Int32Array(Ov),Y=new Int32Array(Av);else G=Ov.slice(),Y=Av.slice();Y$0(f,$,G,Y);function M(){if(Z)Z(L/W);if(L<W){var V=Date.now();for(;L<W;)if(L=L+1,xv($,G,Y),xv(f,G,Y),Date.now()-V>G$0)break}else{for(L=0;L<64;L++)for(U=0;U<z>>1;U++)S7(X,U<<1,G,Y);var Q=[];for(L=0;L<z;L++)Q.push((X[L]>>24&255)>>>0),Q.push((X[L]>>16&255)>>>0),Q.push((X[L]>>8&255)>>>0),Q.push((X[L]&255)>>>0);if(J){J(null,Q);return}else return Q}if(J)J2(M)}if(typeof J!=="undefined")M();else{var q;while(!0)if(typeof(q=M())!=="undefined")return q||[]}}function Nv($,f,W,J){var Z;if(typeof $!=="string"||typeof f!=="string")if(Z=Error("Invalid string / salt: Not a string"),W){J2(W.bind(this,Z));return}else throw Z;var X,z;if(f.charAt(0)!=="$"||f.charAt(1)!=="2")if(Z=Error("Invalid salt version: "+f.substring(0,2)),W){J2(W.bind(this,Z));return}else throw Z;if(f.charAt(2)==="$")X=String.fromCharCode(0),z=3;else{if(X=f.charAt(2),X!=="a"&&X!=="b"&&X!=="y"||f.charAt(3)!=="$")if(Z=Error("Invalid salt revision: "+f.substring(2,4)),W){J2(W.bind(this,Z));return}else throw Z;z=4}if(f.charAt(z+2)>"$")if(Z=Error("Missing salt rounds"),W){J2(W.bind(this,Z));return}else throw Z;var w=parseInt(f.substring(z,z+1),10)*10,G=parseInt(f.substring(z+1,z+2),10),Y=w+G,L=f.substring(z+3,z+25);$+=X>="a"?"\x00":"";var U=X$0($),M=z$0(L,N7);function q(V){var Q=[];if(Q.push("$2"),X>="a")Q.push(X);if(Q.push("$"),Y<10)Q.push("0");return Q.push(Y.toString()),Q.push("$"),Q.push(tV(M,M.length)),Q.push(tV(V,Bv.length*4-1)),Q.join("")}if(typeof W=="undefined")return q(_v(U,M,Y));else _v(U,M,Y,function(V,Q){if(V)W(V,null);else W(null,q(Q))},J)}var Iv=null,J2,BW,i4,N7=16,Fv=10,w$0=16,G$0=100,Ov,Av,Bv;var Tv=K(()=>{J2=typeof process!=="undefined"&&process&&typeof process.nextTick==="function"?typeof setImmediate==="function"?setImmediate:process.nextTick:setTimeout;BW="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),i4=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,54,55,56,57,58,59,60,61,62,63,-1,-1,-1,-1,-1,-1,-1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,-1,-1,-1,-1,-1,-1,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,-1,-1,-1,-1,-1];Ov=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Av=[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946,1266315497,3048417604,3681880366,3289982499,2909710000,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055,3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504,976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409000,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462],Bv=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892]});var L$0,F7;var Pv=K(()=>{R7();_();OW();Tv();pV();_();L$0=R.object({hashing:R.string({enum:["plain","sha256","bcrypt"],default:"sha256"}),rounds:R.number({minimum:1,maximum:10}).optional()}).strict();F7=class F7 extends x7{constructor($={}){super($,"password","password","form");this.registerAction("create",this.getPayloadSchema(),async({password:f,...W})=>{return{...W,strategy_value:await this.hash(f)}})}getSchema(){return L$0}getPayloadSchema(){return R.object({email:R.string({format:"email"}),password:R.string({minLength:8})})}async hash($){switch(this.config.hashing){case"sha256":return Qz.sha256($);case"bcrypt":{let f=await aV(this.config.rounds??4);return oV($,f)}default:return $}}async compare($,f){switch(this.config.hashing){case"sha256":{let W=await this.hash(f);return $===W}case"bcrypt":return await Sv(f,$)}return!1}verify($){return async(f)=>{if(await this.compare(f?.strategy_value,$)!==!0)throw new U7}}getController($){let f=new o$,W=R.object({redirect:R.string().optional()}),J=this.getPayloadSchema();return f.post("/login",W0("query",W),async(Z)=>{try{let X=F0(J,await $.getBody(Z),{onError:(w)=>{throw A.error("Invalid login payload",[...w]),new U7}}),{redirect:z}=Z.req.valid("query");return await $.resolveLogin(Z,this,X,this.verify(X.password),{redirect:z})}catch(X){return $.respondWithError(Z,X)}}),f.post("/register",W0("query",W),async(Z)=>{try{let{redirect:X}=Z.req.valid("query"),{password:z,email:w,...G}=F0(J,await $.getBody(Z),{onError:(L)=>{A.error("Invalid register payload",[...L]),new U7}}),Y={...G,email:w,strategy_value:await this.hash(z)};return await $.resolveRegister(Z,this,Y,async()=>{return},{redirect:X})}catch(X){return $.respondWithError(Z,X)}}),f}}});var Cv=K(()=>{Qv();Pv();nV();lV()});var K$0,eV,H$0,U$0,R$0,M$0,$Q;var Ev=K(()=>{CV();Cv();_();K$0={password:{cls:F7,schema:F7.prototype.getSchema()},oauth:{cls:x5,schema:x5.prototype.getSchema()},custom_oauth:{cls:_7,schema:_7.prototype.getSchema()}},eV=K$0,H$0=Y4(eV,($,f)=>{return R.strictObject({enabled:R.boolean({default:!0}).optional(),type:R.literal(f),config:$.schema},{title:f})}),U$0=R.anyOf(Object.values(H$0)),R$0=R.object({enabled:R.boolean({default:!1}).optional()}),M$0=R.strictObject({permissions:R.array(R.string()).optional(),is_default:R.boolean().optional(),implicit_allow:R.boolean().optional()}),$Q=R.strictObject({enabled:R.boolean({default:!1}),basepath:R.string({default:"/api/auth"}),entity_name:R.string({default:"users"}),allow_register:R.boolean({default:!0}).optional(),jwt:TV,cookie:BV,strategies:R.record(U$0,{title:"Strategies",default:{password:{type:"password",enabled:!0,config:{hashing:"sha256"}}}}),guard:R$0.optional(),roles:R.record(M$0,{default:{}}).optional()},{title:"Authentication"})});class fQ{appAuth;constructor($){this.appAuth=$}get em(){return this.appAuth.em}get users(){return this.appAuth.getUsersEntity()}async findBy($,f,W){A.debug("[AppUserPool:findBy]",{strategy:$,prop:f,value:W}),this.toggleStrategyValueVisibility(!0);let J=await this.em.repo(this.users).findOne({[f]:W,strategy:$});if(this.toggleStrategyValueVisibility(!1),!J.data)throw A.debug("[AppUserPool]: User not found"),new $V;return J.data}async create($,f){if(A.debug("[AppUserPool:create]",{strategy:$,payload:f}),!("strategy_value"in f))throw new f2("Profile must have a strategy_value value");let W=this.users.getSelect(void 0,"create"),Z={...LW(f,W),strategy:$},X=this.em.mutator(this.users);X.__unstable_toggleSystemEntityCreation(!1),this.toggleStrategyValueVisibility(!0);let z=await X.insertOne(Z);if(X.__unstable_toggleSystemEntityCreation(!0),this.toggleStrategyValueVisibility(!1),!z.data)throw new fV;return A.debug("[AppUserPool]: User created",z.data),z.data}toggleStrategyValueVisibility($){let f=(W,J)=>{let Z=this.users.field(W);if(J)Z.config.hidden=!1,Z.config.fillable=!0;else{let X=PW.usersFields.strategy_value.config;Z.config.hidden=X.hidden,Z.config.fillable=X.fillable}};f("strategy_value",$),f("strategy",$)}}var hv=K(()=>{WQ();_();j2();R7()});var tG;var JQ=K(()=>{R5();tG={email:ef().required(),strategy:ef({fillable:["create"],hidden:["update","form"]}).required(),strategy_value:ef({fillable:["create"],hidden:["read","table","update","form"]}).required(),role:ef()}});var PW;var WQ=K(()=>{bG();_();R5();q5();UD();Ev();hv();JQ();CV();jH();PW=class PW extends C${_authenticator;cache={};_controller;async onBeforeUpdate($,f){let W=$Q.properties.jwt.properties.secret.default;if(!$.enabled&&f.enabled){if(f.jwt.secret===W)A.warn("No JWT secret provided, generating a random one"),f.jwt.secret=l_(64)}if(!f.strategies?.password?.enabled)A.warn("Password strategy cannot be disabled."),f.strategies.password.enabled=!0;return f}get enabled(){return this.config.enabled}async build(){if(!this.enabled){this.setBuilt();return}let $=M0(this.config.roles??{},(W,J)=>{return A6.create({name:J,...W})});this.ctx.guard.setRoles(Object.values($)),this.ctx.guard.setConfig(this.config.guard??{});let f=M0(this.config.strategies??{},(W,J)=>{try{return new eV[W.type].cls(W.config)}catch(Z){throw new Error(`Could not build strategy ${String(J)} with config ${JSON.stringify(W.config)}`)}});this._authenticator=new PV(f,new fQ(this),{jwt:this.config.jwt,cookie:this.config.cookie}),this.registerEntities(),super.setBuilt(),this._controller=new GV(this),this.ctx.server.route(this.config.basepath,this._controller.getController()),this.ctx.guard.registerPermissions(M7)}isStrategyEnabled($){let f=typeof $==="string"?$:$.getName();if(f==="password")return!0;return this.config.strategies?.[f]?.enabled??!1}get controller(){if(!this.isBuilt())throw new Error("Can't access controller, AppAuth not built yet");return this._controller}getSchema(){return $Q}get authenticator(){return this.throwIfNotBuilt(),this._authenticator}get em(){return this.ctx.em}getUsersEntity($){let f=this.config.entity_name;if($||!this.em.hasEntity(f))return MW(f,PW.usersFields,void 0,"system");return this.em.entity(f)}static usersFields=tG;registerEntities(){let $=this.getUsersEntity(!0);this.ctx.helper.ensureSchema(EG({[$.name]:$},({index:f},{users:W})=>{f(W).on(["email"],!0).on(["strategy"]).on(["strategy_value"])}));try{let f=Object.keys(this.config.roles??{});this.ctx.helper.replaceEntityField($,"role",G7({enum:f}))}catch(f){}try{let f=Object.keys(this.config.strategies??{});this.ctx.helper.replaceEntityField($,"strategy",G7({enum:f}))}catch(f){}}async createUser({email:$,password:f,...W}){if(!this.enabled)throw new Error("Cannot create user, auth not enabled");let J="password",X=await this.authenticator.strategy(J).hash(f),z=this.em.mutator(this.config.entity_name);z.__unstable_toggleSystemEntityCreation(!1);let{data:w}=await z.insertOne({...W,email:$,strategy:J,strategy_value:X});return z.__unstable_toggleSystemEntityCreation(!0),w}toJSON($){if(!this.config.enabled)return this.configDefault;let f=this.authenticator.getStrategies();return{...this.config,...this.authenticator.toJSON($),strategies:M0(f,(W)=>({enabled:this.isStrategyEnabled(W),...W.toJSON($)}))}}}});var EW={};V1(EW,{schemaRead:()=>CW,configWrite:()=>_5,configReadSecrets:()=>B7,configRead:()=>oG,build:()=>XQ,accessApi:()=>ZQ,accessAdmin:()=>aG});var aG,ZQ,oG,B7,_5,CW,XQ;var T7=K(()=>{aG=new B0("system.access.admin"),ZQ=new B0("system.access.api"),oG=new B0("system.config.read"),B7=new B0("system.config.read.secrets"),_5=new B0("system.config.write"),CW=new B0("system.schema.read"),XQ=new B0("system.build")});var zQ;var Dv=K(()=>{_W();_();T7();xW();kq();zQ=class zQ extends If{ctx;config;constructor($,f){super();this.ctx=$;this.config=f}get em(){return this.ctx.em}get guard(){return this.ctx.guard}entityExists($){try{return!!this.em.entity($)}catch(f){return!1}}getController(){let{permission:$,auth:f}=this.middlewares,W=this.create().use(f(),$(ZQ)),J=this.getEntitiesEnum(this.em);function Z(X,z){let w=z;return w.description=X,w}return W.get("/",G0({summary:"Retrieve data configuration",tags:["data"]}),Z("data info",(X)=>{return X.json(this.em.toJSON())})),W.get("/sync",$(ZV),G0({summary:"Sync database schema",tags:["data"]}),W0("query",R.object({force:R.boolean(),drop:R.boolean()}).partial()),async(X)=>{let{force:z,drop:w}=X.req.valid("query"),G=await this.em.schema().introspect(),Y=await this.em.schema().sync({force:z,drop:w});return X.json({tables:G.map((L)=>L.name),changes:Y})}),W.get("/schema.json",$(W2),G0({summary:"Retrieve data schema",tags:["data"]}),async(X)=>{let z=`${this.config.basepath}/schema.json`,w=Object.fromEntries(this.em.entities.map((G)=>[G.name,{$ref:`${this.config.basepath}/schemas/${G.name}`}]));return X.json({$schema:"https://json-schema.org/draft/2020-12/schema",$id:z,properties:w})}),W.get("/schemas/:entity/:context?",$(W2),G0({summary:"Retrieve entity schema",tags:["data"]}),W0("param",R.object({entity:J,context:R.string({enum:["create","update"],default:"create"}).optional()})),async(X)=>{let{entity:z,context:w}=X.req.param();if(!this.entityExists(z))return this.notFound(X);let G=this.em.entity(z),Y=G.toSchema({context:w}),U=`${new URL(X.req.url).origin}${this.config.basepath}`,M=`${this.config.basepath}/schemas/${z}`;return X.json({$schema:`${U}/schema.json`,$id:M,title:G.label,$comment:G.config.description,...Y})}),W.route("/entity",this.getEntityRoutes()),W.get("/info/:entity",$(W2),G0({summary:"Retrieve entity info",tags:["data"]}),W0("param",R.object({entity:J})),async(X)=>{let{entity:z}=X.req.param();if(!this.entityExists(z))return this.notFound(X);let w=this.em.entity(z),G=w.fields.map((L)=>L.name),Y=(L)=>L.map((U)=>({entity:U.other(w).entity.name,ref:U.other(w).reference}));return X.json({name:w.name,fields:G,relations:{all:Y(this.em.relations.relationsOf(w)),listable:Y(this.em.relations.listableRelationsOf(w)),source:Y(this.em.relations.sourceRelationsOf(w)),target:Y(this.em.relations.targetRelationsOf(w))}})}),W}getEntityRoutes(){let{permission:$}=this.middlewares,f=this.create(),W=this.getEntitiesEnum(this.em),J=R.anyOf([R.number(),R.string()],{coerce:(w)=>w});f.post("/:entity/fn/count",$(W2),G0({summary:"Count entities",tags:["data"]}),W0("param",R.object({entity:W})),W0("json",Qf.properties.where),async(w)=>{let{entity:G}=w.req.valid("param");if(!this.entityExists(G))return this.notFound(w);let Y=w.req.valid("json"),L=await this.em.repository(G).count(Y);return w.json({entity:G,...L.data})}),f.post("/:entity/fn/exists",$(W2),G0({summary:"Check if entity exists",tags:["data"]}),W0("param",R.object({entity:W})),W0("json",Qf.properties.where),async(w)=>{let{entity:G}=w.req.valid("param");if(!this.entityExists(G))return this.notFound(w);let Y=w.req.valid("json"),L=await this.em.repository(G).exists(Y);return w.json({entity:G,...L.data})});let Z=R.object({...s1(Qf.properties,["with"]),sort:R.string({default:"id"}),select:R.array(R.string()),join:R.array(R.string())}).partial(),X=(w=Object.keys(Qf.properties))=>[...jJ(Z,"query").parameters?.filter((G)=>w.includes(G.name))];f.get("/:entity",G0({summary:"Read many",parameters:X(["limit","offset","sort","select","join"]),tags:["data"]}),$(W2),W0("param",R.object({entity:W})),W0("query",Qf,{skipOpenAPI:!0}),async(w)=>{let{entity:G}=w.req.valid("param");if(!this.entityExists(G))return this.notFound(w);let Y=w.req.valid("query"),L=await this.em.repository(G).findMany(Y);return w.json(L,{status:L.data?200:404})}),f.get("/:entity/:id",G0({summary:"Read one",parameters:X(["offset","sort","select"]),tags:["data"]}),$(W2),W0("param",R.object({entity:W,id:J})),W0("query",Qf,{skipOpenAPI:!0}),async(w)=>{let{entity:G,id:Y}=w.req.valid("param");if(!this.entityExists(G))return this.notFound(w);let L=w.req.valid("query"),U=await this.em.repository(G).findId(Y,L);return w.json(U,{status:U.data?200:404})}),f.get("/:entity/:id/:reference",G0({summary:"Read many by reference",parameters:X(),tags:["data"]}),$(W2),W0("param",R.object({entity:W,id:J,reference:R.string()})),W0("query",Qf,{skipOpenAPI:!0}),async(w)=>{let{entity:G,id:Y,reference:L}=w.req.valid("param");if(!this.entityExists(G))return this.notFound(w);let U=w.req.valid("query"),M=await this.em.repository(G).findManyByReference(Y,L,U);return w.json(M,{status:M.data?200:404})});let z=R.object({...Z.properties,with:R.object({})}).partial();return f.post("/:entity/query",G0({summary:"Query entities",requestBody:{content:{"application/json":{schema:z.toJSON(),example:z.template({withOptional:!0})}}},tags:["data"]}),$(W2),W0("param",R.object({entity:W})),W0("json",Qf,{skipOpenAPI:!0}),async(w)=>{let{entity:G}=w.req.valid("param");if(!this.entityExists(G))return this.notFound(w);let Y=w.req.valid("json"),L=await this.em.repository(G).findMany(Y);return w.json(L,{status:L.data?200:404})}),f.post("/:entity",G0({summary:"Insert one or many",tags:["data"]}),$(V5),W0("param",R.object({entity:W})),W0("json",R.anyOf([R.object({}),R.array(R.object({}))])),async(w)=>{let{entity:G}=w.req.valid("param");if(!this.entityExists(G))return this.notFound(w);let Y=await w.req.json();if(Array.isArray(Y)){let U=await this.em.mutator(G).insertMany(Y);return w.json(U,201)}let L=await this.em.mutator(G).insertOne(Y);return w.json(L,201)}),f.patch("/:entity",G0({summary:"Update many",tags:["data"]}),$(uG),W0("param",R.object({entity:W})),W0("json",R.object({update:R.object({}),where:Qf.properties.where})),async(w)=>{let{entity:G}=w.req.param();if(!this.entityExists(G))return this.notFound(w);let{update:Y,where:L}=await w.req.json(),U=await this.em.mutator(G).updateWhere(Y,L);return w.json(U)}),f.patch("/:entity/:id",G0({summary:"Update one",tags:["data"]}),$(uG),W0("param",R.object({entity:W,id:J})),W0("json",R.object({})),async(w)=>{let{entity:G,id:Y}=w.req.valid("param");if(!this.entityExists(G))return this.notFound(w);let L=await w.req.json(),U=await this.em.mutator(G).updateOne(Y,L);return w.json(U)}),f.delete("/:entity/:id",G0({summary:"Delete one",tags:["data"]}),$(cG),W0("param",R.object({entity:W,id:J})),async(w)=>{let{entity:G,id:Y}=w.req.valid("param");if(!this.entityExists(G))return this.notFound(w);let L=await this.em.mutator(G).deleteOne(Y);return w.json(L)}),f.delete("/:entity",G0({summary:"Delete many",tags:["data"]}),$(cG),W0("param",R.object({entity:W})),W0("json",Qf.properties.where),async(w)=>{let{entity:G}=w.req.valid("param");if(!this.entityExists(G))return this.notFound(w);let Y=await w.req.json(),L=await this.em.mutator(G).deleteWhere(Y);return w.json(L)}),f}}});var eG,vv,q$0,V$0,Q$0,I$0,O$0,A$0,mv;var wQ=K(()=>{_();PG();sf();y4();j4();sf();_();eG={...Xh,...Ih,media:{schema:bq,field:b4}},vv=hq,q$0=Y4(eG,($,f)=>{return R.strictObject({name:R.string().optional(),type:R.literal(f),config:$.schema.optional()},{title:f})}),V$0=R.anyOf(Object.values(q$0)),Q$0=R.record(V$0),I$0=R.strictObject({name:R.string().optional(),type:R.string({enum:KW,default:"regular"}),config:Sq,fields:Q$0}),O$0=Object.entries(hq).map(([$,f])=>{return R.strictObject({type:R.literal($),source:R.string(),target:R.string(),config:f.schema.optional()},{title:$})}),A$0=R.strictObject({entity:R.string(),fields:R.array(R.string(),{minItems:1}),unique:R.boolean({default:!1}).optional()}),mv=R.strictObject({basepath:R.string({default:"/api/data"}).optional(),default_primary_format:R.string({enum:mZ,default:"integer"}).optional(),entities:R.record(I$0,{default:{}}).optional(),relations:R.record(R.anyOf(O$0),{default:{}}).optional(),indices:R.record(A$0,{default:{}}).optional()})});function kv($,f){let W=M0(f.fields??{},(J,Z)=>{let{type:X}=J;if(!(X in eG))throw new Error(`Field type "${X}" not found`);let{field:z}=eG[X];return new z(Z,J.config)});return new P$($,Object.values(W),f.config,f.type)}function yv($,f){return new vv[$.type].cls(f($.source),f($.target),$.config)}var jv=K(()=>{_();j4();wQ()});var GQ;var gv=K(()=>{_();q5();Dv();wQ();jv();sf();xW();GQ=class GQ extends C${async build(){let{entities:$={},relations:f={},indices:W={}}=this.config,J=M0($,(w,G)=>{return kv(G,w)}),Z=(w)=>{let G=typeof w==="string"?w:w.name,Y=J[G];if(Y)return Y;throw new Error(`[AppData] Entity "${G}" not found`)},X=M0(f,(w)=>yv(w,Z)),z=M0(W,(w,G)=>{let Y=Z(w.entity),L=w.fields.map((U)=>Y.field(U));return new kZ(Y,L,w.unique,G)});for(let w of Object.values(J))this.ctx.em.addEntity(w);for(let w of Object.values(X))this.ctx.em.addRelation(w);for(let w of Object.values(z))this.ctx.em.addIndex(w);this.ctx.server.route(this.basepath,new zQ(this.ctx,this.config).getController()),this.ctx.guard.registerPermissions(Object.values(Q5)),this.setBuilt()}async onBeforeUpdate($,f){let W={from:Object.keys($.entities??{}),to:Object.keys(f.entities??{})};if(W.from.length-W.to.length>1)throw new Error("Cannot remove more than one entity at a time");return f}getSchema(){return mv}get em(){return this.throwIfNotBuilt(),this.ctx.em}get basepath(){return this.config.basepath??"/api/data"}getOverwritePaths(){return[/^entities\..*\.config$/,/^entities\..*\.fields\..*\.config$/]}toJSON($){return{...this.config,...this.em.toJSON()}}}});class $Y{variables;options;constructor($={},f={}){this.variables=$;this.options=f}another(){return 1}static hasMarkup($){let f="";if(Array.isArray($)||typeof $==="object"){if(!["Array","Object"].includes($.constructor.name))return!1;f=JSON.stringify($)}else f=String($);return["{{"].some((J)=>f.includes(J))}async render($){if(typeof $==="undefined"||$===null)return $;if(typeof $==="string")return await this.renderString($);else if(Array.isArray($))return await Promise.all($.map((f)=>this.render(f)));else if(typeof $==="object")return await this.renderObject($);throw new Error("Invalid template type")}async renderString($){return $.replace(/{{\s*([^{}]+?)\s*}}/g,(f,W)=>{let J=k2(this.variables,W.trim());return J==null?"":String(J)})}async renderObject($){let f={};for(let[W,J]of Object.entries($)){let Z=W;if(this.options.renderKeys)Z=await this.renderString(W);f[Z]=await this.render(J)}return f}}var bv=K(()=>{j2()});var N5=($,f)=>$,Z2;var P7=K(()=>{Y9();_();bv();Z2=class Z2{name;static schema=R.any();_params;constructor($,f){if(typeof $!=="string")throw new Error(`Task name must be a string, got ${typeof $}`);this.name=$;let W=this.constructor.schema;if(W===Z2.schema&&typeof f!=="undefined"&&Object.keys(f||{}).length>0)throw new Error(`Task "${$}" has no schema defined but params passed: ${JSON.stringify(f)}`);this._params=F0(W,f||{})}get params(){return this._params}clone($,f){return new this.constructor($,f)}static async resolveParams($,f,W={}){let J={},Z=new $Y(W,{renderKeys:!0});for(let[X,z]of Object.entries(f)){if(z&&$Y.hasMarkup(z)){try{J[X]=await Z.render(z)}catch(w){if(!(w instanceof R2))throw new R2("Failed to resolve param",{key:X,value:z,error:w.message},"resolve-params");throw w}continue}J[X]=z}return $.coerce(J)}async cloneWithResolvedParams($){let f=Object.fromEntries($.entries()),W=await Z2.resolveParams(this.constructor.schema,this._params,f);return this.clone(this.name,W)}async run($=new Map){let f=new Date,W,J,Z,X,z,w=performance.now();try{let G=await this.cloneWithResolvedParams($);X=G.params,W=await G.execute($),Z=!0}catch(G){if(Z=!1,G instanceof R2)J=G.toJSON();else J={type:"unknown",message:G.message}}return{start:f,output:W,error:J,success:Z,params:X,time:performance.now()-w}}error($,f){return new R2($,f,"runtime")}get label(){return this.name}toJSON(){return{type:this.type,params:this.params}}}});var YQ,LQ;var uv=K(()=>{P7();_();YQ=["GET","POST","PUT","PATCH","DELETE"];LQ=class LQ extends Z2{type="fetch";static schema=R.strictObject({url:R.string({pattern:"^(http|https)://"}),method:N5(R.string({enum:YQ,default:"GET"})).optional(),headers:N5(R.array(R.strictObject({key:R.string(),value:R.string()})),JSON.parse).optional(),body:N5(R.string()).optional(),normal:N5(R.number(),Number.parseInt).optional()});getBody(){let $=this.params.body;if(!$)return;if(typeof $==="string")return $;if(typeof $==="object")return JSON.stringify($);throw new Error(`Invalid body type: ${typeof $}`)}async execute(){if(!YQ.includes(this.params.method??"GET"))throw this.error("Invalid method",{given:this.params.method,valid:YQ});let $=this.getBody(),f=new Headers(this.params.headers?.map((Z)=>[Z.key,Z.value])),W=await fetch(this.params.url,{method:this.params.method??"GET",headers:f,body:$});if(!W.ok)throw this.error("Failed to fetch",{status:W.status,statusText:W.statusText});return await W.json()}}});var KQ;var cv=K(()=>{P7();_();_();KQ=class KQ extends Z2{type="log";static schema=R.strictObject({delay:R.number({default:10})});async execute(){return await new Promise(($)=>setTimeout($,this.params.delay)),A.log(`[DONE] LogTask: ${this.name}`),!0}}});var HQ;var dv=K(()=>{P7();_();HQ=class HQ extends Z2{type="render";static schema=R.strictObject({render:R.string()});async execute(){return this.params.render}}});class C7{source;target;config;id;constructor($,f,W,J){if(this.source=$,this.target=f,this.config=W??{},!(this.config.condition instanceof X2))this.config.condition=X2.default();this.id=J??e_()}get condition(){return this.config.condition}get max_retries(){return this.config.max_retries??0}toJSON(){return wz({source:this.source.name,target:this.target.name,config:{...this.config,condition:this.config.condition?.toJSON()}})}}class X2{type;path;value;constructor($,f="",W=void 0){this.type=$;this.path=f;this.value=W}static default(){return X2.success()}static success(){return new X2("success")}static error(){return new X2("error")}static matches($,f){if(typeof $!=="string"||$.length===0)throw new Error("Invalid path");return new X2("matches",$,f)}isMet($){switch(this.type){case"success":return $.success;case"error":return $.success===!1;case"matches":return k2($.output,this.path)===this.value}}sameAs($=X2.default()){return this.type===$.type&&this.path===$.path&&this.value===$.value}toJSON(){return{type:this.type,path:this.path.length===0?void 0:this.path,value:this.value}}static fromObject($){return new X2($.type,$.path,$.value)}}var UQ=K(()=>{_();j2()});var fY,WY,JY;var iv=K(()=>{M2();_();fY=class fY extends s0{static slug="flow-execution-event";task(){return this.params.task}getState(){if(this.succeeded())return"success";if(this.failed())return"failed";if(this.isStart())return"running";return"idle"}isStart(){return this.params.end===void 0}isEnd(){return!this.isStart()}succeeded(){return this.isEnd()&&this.params.result?.success}failed(){return this.isEnd()&&!this.params.result?.success}};WY=class WY extends s0{static slug="flow-execution-state"};JY=class JY{flow;started_at;finished_at;logs=[];inputs=new Map;queue=[];emgr;static Events={ExecutionEvent:fY,ExecutionState:WY};constructor($){this.flow=$,this.logs=[],this.queue=[this.flow.startTask],this.emgr=new Q$(JY.Events)}subscribe($){this.emgr.onAny($)}async onDone($,f){let W=new Date;if(this.logs.push({...f,task:$,end:W}),this.inputs.set($.name,f),this.flow.respondingTask===$){this.queue=[];return}this.queue=this.queue.filter((Z)=>Z!==$);let J=this.flow.task($).getOutConnections(f).filter((Z)=>{let X=Z.target,z=this.logs.filter((G)=>G.task===X&&G.success).length,w=this.flow.task(X).getInConnections().find((G)=>G.source===$)?.max_retries??0;if(z>w)throw new Error(`Task "${X.name}" reached max retries (${z}/${w})`);return this.flow.task(X).getInTasks(!0).every((G)=>this.logs.some((Y)=>Y.task===G&&Y.end!==void 0))}).map((Z)=>Z.target);this.queue.push(...J)}__getLastTaskLog($){for(let f=this.logs.length-1;f>=0;f--)if(this.logs[f]?.task===$)return this.logs[f];return null}async run(){let $=this.queue;if($.length===0)return;let f=$.map(async(W)=>{await this.emgr.emit(new fY({task:W}));let J=await W.run(this.inputs);return await this.emgr.emit(new fY({task:W,result:J,end:new Date})),await this.onDone(W,J),J});try{return await Promise.all(f),this.run()}catch(W){throw A.error("RuntimeExecutor: error",W),W}}async start($){await this.emgr.emit(new WY({execution:this,state:"started"})),this.inputs.set("flow",{start:new Date,output:$,error:void 0,success:!0,params:$}),this.started_at=new Date,await this.run(),this.finished_at=new Date,await this.emgr.emit(new WY({execution:this,state:"ended"}))}finished(){return this.finished_at!==void 0}errorCount(){return this.logs.filter(($)=>!$.success).length}hasErrors(){return this.errorCount()>0}getErrorLogs(){return this.logs.filter(($)=>!$.success)}getErrors(){return this.getErrorLogs().map(($)=>$.error)}getResponse(){let $=this.flow.respondingTask;if(!$)$=this.flow.tasks[this.flow.tasks.length-1];let f=this.__getLastTaskLog($);if(!f)return;return f.output}}});class ZY{flow;source;constructor($,f){this.flow=$,this.source=f}task($){return new ZY(this.flow,$)}asInputFor($,f,W){let J=this.getDepth(),Z=this.getOutConnections(),X=Z.map((w)=>w.condition),z=Z.some((w)=>this.task(w.target).getDepth()<=J);if(X.length>0&&z){if(this.getOutConnections().some((w)=>w.condition.sameAs(f)))throw new Error("Task cannot be connected to a deeper task with the same condition")}this.flow.addConnection(new C7(this.source,$,{condition:f,max_retries:W}))}asOutputFor($,f){this.task($).asInputFor(this.source,f)}getNext(){return this.flow.connections.filter(($)=>$.source===this.source).map(($)=>$.target)}getDepth(){return this.flow.getSequence().findIndex(($)=>$.includes(this.source))}getInConnections($=!1){if($){let f=this.getDepth();return this.getInConnections().filter((W)=>W.target===this.source&&this.task(W.source).getDepth()<f)}return this.flow.connections.filter((f)=>f.target===this.source)}getInTasks($=!1){if($){let f=this.getDepth();return this.getInConnections().map((W)=>W.source).filter((W)=>this.task(W).getDepth()<f)}return this.getInConnections().map((f)=>f.source)}getOutConnections($){if($)return this.flow.connections.filter((f)=>f.source===this.source&&f.condition.isMet($));return this.flow.connections.filter((f)=>f.source===this.source)}getOutTasks($){return this.getOutConnections($).map((f)=>f.target)}}var rv=K(()=>{UQ()});var Af;var E7=K(()=>{_();Af=class Af{executions=[];type="manual";config;static schema=R.strictObject({mode:R.string({enum:["sync","async"],default:"async"})});constructor($){let f=this.constructor.schema;this.config=F0(f,$??{})}async register($,...f){this.executions.push(await $.start())}toJSON(){return{type:this.type,config:this.config}}}});class S5{name;trigger;tasks=[];connections=[];respondingTask;startTask;sequence;constructor($,f,W,J){this.name=$,this.trigger=J??new Af,f.map((Z)=>this.addTask(Z)),this.connections=W||[],this.startTask=f[0],this.sequence=this.getSequence()}setStartTask($){return this.startTask=$,this.sequence=this.getSequence(),this}getSequence($=[]){if($.length===0)return $.push([this.startTask]),this.getSequence($);let f=$[$.length-1],W=[];if(f?.forEach((J)=>{this.task(J).getOutTasks().forEach((X)=>{if($.some((z)=>z.includes(X)))return;W.push(X)})}),W.length===0)return $;return $.push(W),this.getSequence($)}addTask($){if(this.tasks.includes($))throw new Error("Task already defined");if(this.tasks.some((f)=>f.name===$.name))throw new Error(`Task with name "${$.name}" already defined. Use a unique name.`);return this.tasks.push($),this}setRespondingTask($){if(!this.tasks.includes($))throw new Error(`Cannot set task "${$.name}" as responding, not registered.`);return this.respondingTask=$,this}addConnection($){if(this.connections.some((W)=>{return W.source===$.source&&W.target===$.target&&W.condition[0]===$.condition[0]&&W.condition[1]===$.condition[1]}))throw new Error("Connection already defined");return this.connections.push($),this}task($){return new ZY(this,$)}createExecution(){return this.sequence=this.getSequence(),new JY(this)}async start($=void 0){let f=this.createExecution();return await f.start($),f}toJSON(){return{trigger:this.trigger.toJSON(),tasks:Object.fromEntries(this.tasks.map(($)=>[$.name,$.toJSON()])),connections:Object.fromEntries(this.connections.map(($)=>[$.id,$.toJSON()])),start_task:this.startTask?.name,responding_task:this.respondingTask?.name}}static fromObject($,f,W){let J=M0(f.tasks??{},(w,G)=>{let Y=W[w.type];if(!Y)throw new Error(`Task ${G} not found in taskMap`);try{return new Y.cls(G,w.params)}catch(L){throw A.error("Error creating task",G,w.type,w,Y),new Error(`Error creating task ${w.type}: ${L.message}`)}}),Z=M0(f.connections??{},(w,G)=>{let Y=w.config.condition?X2.fromObject(w.config.condition):void 0;return new C7(J[w.source],J[w.target],{...w.config,condition:Y},G)}),X;if(f.trigger){let w=h7[f.trigger.type]?.cls;if(w)X=new w(f.trigger.config)}let z=new S5($,Object.values(J),Object.values(Z),X);if(z.startTask=f.start_task?J[f.start_task]:null,f.responding_task)z.respondingTask=J[f.responding_task];return z}}var RQ=K(()=>{_();XY();UQ();iv();rv();E7()});var MQ;var lv=K(()=>{RQ();P7();_();MQ=class MQ extends Z2{type="subflow";static schema=R.strictObject({flow:R.any(),input:N5(R.any(),JSON.parse).optional(),loop:R.boolean().optional()});async execute(){let $=this.params.flow;if(!($ instanceof S5))throw new Error("Invalid flow provided");if(this.params.loop){let W=Array.isArray(this.params.input)?this.params.input:[this.params.input],J=[];for(let Z of W){let X=$.createExecution();await X.start(Z),J.push(await X.getResponse())}return J}let f=$.createExecution();return await f.start(this.params.input),f.getResponse()}}});var zY;var pv=K(()=>{E7();_();_();zY=class zY extends Af{type="event";static schema=R.strictObject({event:R.string(),...Af.schema.properties});async register($,f){if(!f.eventExists(this.config.event))throw new Error(`Event ${this.config.event} is not registered.`);f.on(this.config.event,async(W)=>{let J=$.createExecution();this.executions.push(J);try{await J.start(W.params)}catch(Z){A.error(Z)}},this.config.mode)}}});var x$0,hW;var nv=K(()=>{E7();_();x$0=["GET","POST","PUT","PATCH","DELETE"];hW=class hW extends Af{type="http";static schema=R.strictObject({path:R.string({pattern:"^/.*$"}),method:R.string({enum:x$0,default:"GET"}),response_type:R.string({enum:["json","text","html"],default:"json"}),...Af.schema.properties});async register($,f){let W=this.config.method.toLowerCase();f[W](this.config.path,async(J)=>{let Z=J.req.raw,X=J[this.config.response_type],z=$.createExecution();if(this.executions.push(z),this.config.mode==="sync"){await z.start(Z);let w=z.getResponse(),G=z.getErrors();if(G.length>0)return J.json({success:!1,errors:G});return X(w)}return z.start(Z),J.json({success:!0})})}}});var h7;var sv=K(()=>{pv();nv();E7();h7={manual:{cls:Af},event:{cls:zY},http:{cls:hW}}});var tv;var XY=K(()=>{uv();cv();dv();lv();RQ();sv();tv={fetch:{cls:LQ},log:{cls:KQ},render:{cls:HQ},subflow:{cls:MQ}}});var qQ,_$0,av,nd0,ov,sd0,N$0,S$0,ev;var $m=K(()=>{_();XY();_();qQ={...tv},_$0=h7,av=M0(qQ,($,f)=>{return R.strictObject({type:R.literal(f),params:$.cls.schema},{title:String(f)})}),nd0=R.anyOf(Object.values(av)),ov=M0(_$0,($,f)=>{return R.strictObject({type:R.literal(f),config:$.cls.schema.optional()},{title:String(f)})}),sd0=R.anyOf(Object.values(ov)),N$0=R.strictObject({source:R.string(),target:R.string(),config:R.strictObject({condition:R.anyOf([R.strictObject({type:R.literal("success")},{title:"success"}),R.strictObject({type:R.literal("error")},{title:"error"}),R.strictObject({type:R.literal("matches"),path:R.string(),value:R.string()},{title:"matches"})]),max_retries:R.number()}).partial()}),S$0=R.strictObject({trigger:R.anyOf(Object.values(ov)),tasks:R.record(R.anyOf(Object.values(av))).optional(),connections:R.record(N$0).optional(),start_task:R.string().optional(),responding_task:R.string().optional()}),ev=R.strictObject({basepath:R.string({default:"/api/flows"}),flows:R.record(S$0,{default:{}})})});var VQ;var fm=K(()=>{XY();OW();q5();$m();_();VQ=class VQ extends C${flows={};getSchema(){return ev}getFlowInfo($){return{...$.toJSON(),tasks:$.tasks.length,connections:$.connections}}async build(){let $=M0(this.config.flows,(W,J)=>{return S5.fromObject(J,W,qQ)});this.flows=$;let f=new o$;f.get("/",async(W)=>{let J=M0(this.flows,(Z)=>this.getFlowInfo(Z));return W.json(J)}),f.get("/flow/:name",async(W)=>{let J=W.req.param("name");return W.json(this.flows[J]?.toJSON())}),f.get("/flow/:name/run",async(W)=>{let J=W.req.param("name"),Z=this.flows[J],X=Z.createExecution(),z=performance.now();await X.start();let w=performance.now()-z,G=X.getErrors();return W.json({success:G.length===0,time:w,errors:G,response:X.getResponse(),flow:this.getFlowInfo(Z),logs:X.logs})}),f.all("*",(W)=>W.notFound()),this.ctx.server.route(this.config.basepath,f);for(let[W,J]of Object.entries(this.flows)){let Z=J.trigger;switch(!0){case Z instanceof hW:await Z.register(J,this.ctx.server);break}}this.setBuilt()}toJSON(){return{...this.config,flows:M0(this.flows,($)=>$.toJSON())}}}});var DW={};V1(DW,{FileUploadedEvent:()=>wY,FileDeletedEvent:()=>GY,FileAccessEvent:()=>YY});var wY,GY,YY;var LY=K(()=>{M2();wY=class wY extends s0{static slug="file-uploaded";validate($){if(typeof $!=="object")throw new L9("object",typeof $);return this.clone({...$,...this.params})}};GY=class GY extends s0{static slug="file-deleted"};YY=class YY extends s0{static slug="file-access"}});var vW;var Wm=K(()=>{M2();_();TJ();LY();vW=class vW{#$;static Events=DW;emgr;config;constructor($,f={},W){this.#$=$,this.config={...f,body_max_size:f.body_max_size&&f.body_max_size>0?f.body_max_size:void 0},this.emgr=W??new Q$,this.emgr.registerEvents(vW.Events)}getAdapter(){return this.#$}async objectMetadata($){return await this.#$.getObjectMeta($)}getConfig(){return this.config}async uploadFile($,f,W){let J=await this.#$.putObject(f,$);if(typeof J==="undefined")throw new Error("Failed to upload file");let Z={name:f,meta:{size:0,type:"application/octet-stream"},etag:typeof J==="string"?J:""};if(typeof J==="object")Z=J;else if(j$($))Z.meta.size=$.size,Z.meta.type=$.type;if(!Yz(Z.meta.type,["application/octet-stream","application/json"])){let z=await this.#$.getObjectMeta(f);if(!z)throw new Error("Failed to get object meta");Z.meta=z}if(Z.meta.type.startsWith("image")&&(!Z.meta.width||!Z.meta.height))try{let z=await A_($);Z.meta={...Z.meta,...z}}catch(z){A.warn("Failed to get image dimensions",z)}let X={file:$,...Z,state:{name:Z.name,path:Z.name}};if(!W){let z=await this.emgr.emit(new wY(X));if(z.returned)return z.params}return X}async deleteFile($){await this.#$.deleteObject($),await this.emgr.emit(new GY({name:$}))}async fileExists($){return await this.#$.objectExists($)}}});var D7={};V1(D7,{uploadFile:()=>KY,readFile:()=>QQ,listFiles:()=>IQ,deleteFile:()=>OQ});var QQ,IQ,KY,OQ;var HY=K(()=>{QQ=new B0("media.file.read"),IQ=new B0("media.file.list"),KY=new B0("media.file.upload"),OQ=new B0("media.file.delete")});function F$0($){if(!$.includes("."))return;let f=$.split(".");return f[f.length-1]?.toLowerCase()}function AQ($,f=16){let W=typeof $==="string"?$:$.name;if(typeof W!=="string")throw console.error("Couldn't extract filename from",$),new Error("Invalid file name");let J=F$0(W);if(!J&&j$($)&&$.type){let Z=Lz($.type);if(Z.length>0)J=Z}return[Xz(f),J].filter(Boolean).join(".")}var Jm=K(()=>{_();TJ()});var xQ;var Zm=K(()=>{V$();xW();_W();PG();HY();LY();_();Jm();xQ=class xQ extends If{media;constructor($){super();this.media=$}getStorageAdapter(){return this.getStorage().getAdapter()}getStorage(){return this.media.storage}getController(){let{auth:$,permission:f}=this.middlewares,W=this.create().use($()),J=this.getEntitiesEnum(this.media.em);W.get("/files",G0({summary:"Get the list of files",tags:["media"]}),f(IQ),async(z)=>{let w=await this.getStorageAdapter().listObjects();return z.json(w)}),W.get("/file/:filename",G0({summary:"Get a file by name",tags:["media"]}),f(QQ),async(z)=>{let{filename:w}=z.req.param();if(!w)throw new Error("No file name provided");await this.getStorage().emgr.emit(new YY({name:w}));let G=await this.getStorageAdapter().getObject(w,z.req.raw.headers),Y=new Headers(G.headers);return Y.set("Cache-Control","public, max-age=31536000, immutable"),new Response(G.body,{status:G.status,statusText:G.statusText,headers:Y})}),W.delete("/file/:filename",G0({summary:"Delete a file by name",tags:["media"]}),f(OQ),async(z)=>{let{filename:w}=z.req.param();if(!w)throw new Error("No file name provided");return await this.getStorage().deleteFile(w),z.json({message:"File deleted"})});let Z=this.getStorage().getConfig().body_max_size??Number.POSITIVE_INFINITY;if(Z1())W.post("/inspect",G0({summary:"Inspect a file",tags:["media"]}),async(z)=>{let w=await Rz(z);return z.json({type:w?.type,name:w?.name,size:w?.size})});let X={content:{"multipart/form-data":{schema:{type:"object",properties:{file:{type:"string",format:"binary"}},required:["file"]}},"application/octet-stream":{schema:{type:"string",format:"binary"}}}};return W.post("/upload/:filename?",G0({summary:"Upload a file",tags:["media"],requestBody:X}),W0("param",R.object({filename:R.string().optional()})),f(KY),async(z)=>{let w=z.req.param("filename"),G=await Rz(z);if(!G)return z.json({error:"No file provided"},400);if(G.size>Z)return z.json({error:`Max size (${Z} bytes) exceeded`},413);let Y=w??AQ(G),L=await this.getStorage().uploadFile(G,Y);return z.json(L,201)}),W.post("/entity/:entity/:id/:field",G0({summary:"Add a file to an entity",tags:["media"],requestBody:X}),W0("param",R.object({entity:J,id:R.number(),field:R.string()})),W0("query",R.object({overwrite:R.boolean().optional()})),f([V5,KY]),async(z)=>{let w=z.req.param("entity"),G=z.req.param("field"),Y=Number.parseInt(z.req.param("id")),L=this.media.em.entity(w);if(!L)return z.json({error:`Entity "${w}" not found`},404);let U=L.field(G);if(!U||!(U instanceof b4))return z.json({error:`Invalid field "${G}"`},400);let M=this.media.getMediaEntity().name,q=`${w}.${G}`,V={scope:G,reference:q,entity_id:Y},Q=U.getMaxItems(),O=[];if(Q){let{overwrite:L0}=z.req.valid("query"),{data:{count:K0}}=await this.media.em.repository(M).count(V);if(K0>=Q){if(!L0)return z.json({error:`Max items (${Q}) reached`},400);if(K0>Q)return z.json({error:`Max items (${Q}) exceeded already with ${K0} items.`},422);let j=await this.media.em.repo(M).findMany({select:["path"],where:V,sort:{by:"id",dir:"asc"},limit:K0-Q+1});if(j.data&&j.data.length>0)j.data.map((y1)=>O.push(y1.path))}}let{data:{exists:x}}=await this.media.em.repository(L).exists({id:Y});if(!x)return z.json({error:`Entity "${w}" with ID "${Y}" doesn't exist found`},404);let y=await Rz(z);if(!y)return z.json({error:"No file provided"},400);if(y.size>Z)return z.json({error:`Max size (${Z} bytes) exceeded`},413);let F=AQ(y),B=await this.getStorage().uploadFile(y,F,!0),i=this.media.em.mutator(M);i.__unstable_toggleSystemEntityCreation(!1);let w0=await i.insertOne({...this.media.uploadedEventDataToMediaPayload(B),...V});if(i.__unstable_toggleSystemEntityCreation(!0),O.length>0)for(let L0 of O)await this.getStorage().deleteFile(L0);return z.json({ok:!0,result:w0.data,...B},201)}),W}}});class _Q{registerFn;is_set=!1;items={};constructor($){this.registerFn=$}set($){if(this.is_set)throw new Error("Registry is already set");return this.items=$,this.is_set=!0,this}add($,f){return this.items[$]=f,this}register($,f){if(this.registerFn){let W=this.registerFn(f);return this.items[$]=W,this}return this.add($,f)}get($){return this.items[$]}has($){return $ in this.items}all(){return this.items}}class FQ{constructor({accessKeyId:$,secretAccessKey:f,sessionToken:W,service:J,region:Z,cache:X,retries:z,initRetryMs:w}){if($==null)throw new TypeError("accessKeyId is a required option");if(f==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=$,this.secretAccessKey=f,this.sessionToken=W,this.service=J,this.region=Z,this.cache=X||new Map,this.retries=z!=null?z:10,this.initRetryMs=w||50}async sign($,f){if($ instanceof Request){let{method:Z,url:X,headers:z,body:w}=$;if(f=Object.assign({method:Z,url:X,headers:z},f),f.body==null&&z.has("Content-Type"))f.body=w!=null&&z.has("X-Amz-Content-Sha256")?w:await $.clone().arrayBuffer();$=X}let W=new Gm(Object.assign({url:$.toString()},f,this,f&&f.aws)),J=Object.assign({},f,await W.sign());delete J.aws;try{return new Request(J.url.toString(),J)}catch(Z){if(Z instanceof TypeError)return new Request(J.url.toString(),Object.assign({duplex:"half"},J));throw Z}}async fetch($,f){for(let W=0;W<=this.retries;W++){let J=fetch(await this.sign($,f));if(W===this.retries)return J;let Z=await J;if(Z.status<500&&Z.status!==429)return Z;await new Promise((X)=>setTimeout(X,Math.random()*this.initRetryMs*Math.pow(2,W)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class Gm{constructor({method:$,url:f,headers:W,body:J,accessKeyId:Z,secretAccessKey:X,sessionToken:z,service:w,region:G,cache:Y,datetime:L,signQuery:U,appendSessionToken:M,allHeaders:q,singleEncode:V}){if(f==null)throw new TypeError("url is a required option");if(Z==null)throw new TypeError("accessKeyId is a required option");if(X==null)throw new TypeError("secretAccessKey is a required option");this.method=$||(J?"POST":"GET"),this.url=new URL(f),this.headers=new Headers(W||{}),this.body=J,this.accessKeyId=Z,this.secretAccessKey=X,this.sessionToken=z;let Q,O;if(!w||!G)[Q,O]=P$0(this.url,this.headers);if(this.service=w||Q||"",this.region=G||O||"us-east-1",this.cache=Y||new Map,this.datetime=L||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=U,this.appendSessionToken=M||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256"))this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");let x=this.signQuery?this.url.searchParams:this.headers;if(x.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)x.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((F)=>q||!T$0.has(F)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((F)=>F+":"+(F==="host"?this.url.host:(this.headers.get(F)||"").replace(/\s+/g," "))).join(`
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!x.has("X-Amz-Expires"))x.set("X-Amz-Expires","86400");x.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),x.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),x.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(F){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!V)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=wm(this.encodedPath);let y=new Set;this.encodedSearch=[...this.url.searchParams].filter(([F])=>{if(!F)return!1;if(this.service==="s3"){if(y.has(F))return!1;y.add(F)}return!0}).map((F)=>F.map((B)=>wm(encodeURIComponent(B)))).sort(([F,B],[i,w0])=>F<i?-1:F>i?1:B<w0?-1:B>w0?1:0).map((F)=>F.join("=")).join("&")}async sign(){if(this.signQuery){if(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken)this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)}else this.headers.set("Authorization",await this.authHeader());return{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let $=this.datetime.slice(0,8),f=[this.secretAccessKey,$,this.region,this.service].join(),W=this.cache.get(f);if(!W){let J=await v7("AWS4"+this.secretAccessKey,$),Z=await v7(J,this.region),X=await v7(Z,this.service);W=await v7(X,"aws4_request"),this.cache.set(f,W)}return NQ(await v7(W,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,NQ(await Xm(await this.canonicalString()))].join(`
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
`,this.signedHeaders,await this.hexBodyHash()].join(`
`)}async hexBodyHash(){let $=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if($==null){if(this.body&&typeof this.body!=="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");$=NQ(await Xm(this.body||""))}return $}}async function v7($,f){let W=await crypto.subtle.importKey("raw",typeof $==="string"?SQ.encode($):$,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",W,SQ.encode(f))}async function Xm($){return crypto.subtle.digest("SHA-256",typeof $==="string"?SQ.encode($):$)}function NQ($){let f=new Uint8Array($),W="";for(let J=0;J<f.length;J++){let Z=f[J];W+=zm[Z>>>4&15],W+=zm[Z&15]}return W}function wm($){return $.replace(/[!'()*]/g,(f)=>"%"+f.charCodeAt(0).toString(16).toUpperCase())}function P$0($,f){let{hostname:W,pathname:J}=$;if(W.endsWith(".on.aws")){let w=W.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return w!=null?["lambda",w[1]||""]:["",""]}if(W.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(W.endsWith(".backblazeb2.com")){let w=W.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return w!=null?["s3",w[1]||""]:["",""]}let Z=W.replace("dualstack.","").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),X=Z&&Z[1]||"",z=Z&&Z[2];if(z==="us-gov")z="us-gov-west-1";else if(z==="s3"||z==="s3-accelerate")z="us-east-1",X="s3";else if(X==="iot")if(W.startsWith("iot."))X="execute-api";else if(W.startsWith("data.jobs.iot."))X="iot-jobs-data";else X=J==="/mqtt"?"iotdevicegateway":"iotdata";else if(X==="autoscaling"){let w=(f.get("X-Amz-Target")||"").split(".")[0];if(w==="AnyScaleFrontendService")X="application-autoscaling";else if(w==="AnyScaleScalingPlannerFrontendService")X="autoscaling-plans"}else if(z==null&&X.startsWith("s3-"))z=X.slice(3).replace(/^fips-|^external-1/,""),X="s3";else if(X.endsWith("-fips"))X=X.slice(0,-5);else if(z&&/-\d$/.test(X)&&!/-\d$/.test(z))[X,z]=[z,X];return[B$0[X]||X,z||""]}var SQ,B$0,T$0,zm;var Ym=K(()=>{SQ=new TextEncoder,B$0={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},T$0=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);zm=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]});var BQ;var Lm=K(()=>{Ym();iK();XH();BQ=class BQ extends FQ{#$;constructor($,f){super($);this.#$=f??{responseType:"json"}}convertParams($){switch(this.#$.convertParams){case"pascalToKebab":return zz($);default:return $}}getUrl($="/",f={}){let W=new URL($),J=this.convertParams(f);return Object.entries(J).forEach(([Z,X])=>{W.searchParams.append(Z,X)}),W.toString()}updateKeysRecursively($,f){if($===null||$===void 0)return $;if(Array.isArray($))return $.map((W)=>this.updateKeysRecursively(W,f));if(typeof $==="object")return Object.keys($).reduce((W,J)=>{let Z=J;if(J.indexOf(" ")===-1)Z=J.charAt(0)[f]()+J.slice(1);return W[Z]=this.updateKeysRecursively($[J],f),W},{});return $}async fetchJson($,f){let W=await this.fetch($,f);if(this.#$.responseType==="xml"){if(!W.ok){let X=await W.text();throw new Error(X)}let Z=await W.text();return i_(Z)}if(!W.ok){let Z=await W.json();throw new Error(Z.message)}let J=await W.json();if(this.#$.responseKeysToUpper)return this.updateKeysRecursively(J,"toUpperCase");return J}}});class r4{constructor(){this[Km]=!0}static isAdapter($){if(!$)return!1;return $[Km]===!0}}var Km;var UY=K(()=>{Km=Symbol.for("bknd:storage")});var Hm,m7;var Um=K(()=>{Lm();V$();_();j2();UY();Hm=R.object({access_key:R.string(),secret_access_key:R.string(),url:R.string({pattern:"^https?://(?:.*)?[^/.]+$",description:"URL to S3 compatible endpoint without trailing slash",examples:["https://{account_id}.r2.cloudflarestorage.com/{bucket}","https://{bucket}.s3.{region}.amazonaws.com"]})},{title:"AWS S3",description:"AWS S3 or compatible storage"});m7=class m7 extends r4{#$;client;constructor($){super();this.client=new BQ({accessKeyId:$.access_key,secretAccessKey:$.secret_access_key,retries:Z1()?0:10},{convertParams:"pascalToKebab",responseType:"xml"}),this.#$=F0(Hm,$)}getName(){return"s3"}getSchema(){return Hm}getUrl($="",f={}){let W=this.getObjectUrl("").slice(0,-1);if($.length>0)W+=`/${$}`;return this.client.getUrl(W,f)}getObjectUrl($){return`${this.#$.url}/${$}`}async listObjects($=""){let f={ListType:2,Prefix:$},W=this.getUrl("",f),J=await this.client.fetchJson(W,{method:"GET"}),{Contents:Z}=J.ListBucketResult,X=!Z?[]:Array.isArray(Z)?Z:[Z];return Nq(X,(w,G)=>{if(G.Key&&G.LastModified&&G.Size)w.push({key:G.Key,last_modified:G.LastModified,size:G.Size})},[])}async putObject($,f,W={}){let J=this.getUrl($,{}),Z=await this.client.fetch(J,{method:"PUT",body:f,headers:j$(f)?{"Content-Length":String(f.size)}:{}});if(!Z.ok)throw new Error(`Failed to upload object: ${Z.status} ${Z.statusText}`);return String(Z.headers.get("etag"))}async headObject($,f={}){let W=this.getUrl($,{});return await this.client.fetch(W,{method:"HEAD",headers:{Range:"bytes=0-1"}})}async getObjectMeta($){let f=await this.headObject($),W=String(f.headers.get("content-type")),J=Number(String(f.headers.get("content-range")?.split("/")[1]));return{type:W,size:J}}async objectExists($,f={}){return(await this.headObject($)).ok}async getObject($,f){let W=this.getUrl($),J=await this.client.fetch(W,{method:"GET",headers:N_(f,["if-none-match","accept-encoding","accept","if-modified-since"])});return new Response(J.body,{status:J.status,statusText:J.statusText,headers:J.headers})}async deleteObject($,f={}){let W=this.getUrl($,f),J=await this.client.fetch(W,{method:"DELETE"})}toJSON($){return{type:this.getName(),config:$?this.#$:void 0}}}});var Rm,k7;var Mm=K(()=>{_();UY();_();Rm=R.object({cloud_name:R.string(),api_key:R.string(),api_secret:R.string(),upload_preset:R.string().optional()},{title:"Cloudinary",description:"Cloudinary media storage"});k7=class k7 extends r4{config;constructor($){super();this.config=F0(Rm,$)}getSchema(){return Rm}getMimeType($){switch(!0){case($.format==="jpeg"||$.format==="jpg"):return"image/jpeg"}return`${$.resource_type}/${$.format}`}getName(){return"cloudinary"}getAuthorizationHeader(){return{Authorization:`Basic ${btoa(`${this.config.api_key}:${this.config.api_secret}`)}`}}async putObject($,f){let W=$.replace(/\.[a-z0-9]{2,5}$/,""),J=new FormData;if(J.append("file",f),J.append("public_id",W),J.append("api_key",this.config.api_key),this.config.upload_preset)J.append("upload_preset",this.config.upload_preset);let Z=await fetch(`https://api.cloudinary.com/v1_1/${this.config.cloud_name}/auto/upload`,{method:"POST",headers:{Accept:"application/json"},body:J});if(!Z.ok)return;let X=await Z.json();return{name:X.public_id+"."+X.format,etag:X.etag,meta:{type:this.getMimeType(X),size:X.bytes}}}async listObjects($){let f=await fetch(`https://api.cloudinary.com/v1_1/${this.config.cloud_name}/resources/search`,{method:"GET",headers:{Accept:"application/json","Cache-Control":"no-cache",...this.getAuthorizationHeader()}});if(!f.ok)throw new Error("Failed to list objects");return(await f.json()).resources.map((Z)=>({key:Z.public_id,last_modified:new Date(Z.uploaded_at),size:Z.bytes}))}async headObject($){let f=this.getObjectUrl($);return await fetch(f,{method:"HEAD",headers:{"Cache-Control":"no-cache, no-store, must-revalidate",Pragma:"no-cache",Expires:"0",Range:"bytes=0-1"}})}async objectExists($){return(await this.headObject($)).ok}async getObjectMeta($){let f=await this.headObject($);if(f.ok){let W=f.headers.get("content-type"),J=Number(f.headers.get("content-range")?.split("/")[1]);return{type:W,size:J}}throw new Error("Cannot get object meta")}guessType($){let f={image:["jpg","jpeg","png","gif","webp","svg"],video:["mp4","webm","ogg"]},W=$.split(".").pop();return Object.keys(f).find((J)=>f[J].includes(W))}getObjectUrl($){let f=this.guessType($)??"image";return`https://res.cloudinary.com/${this.config.cloud_name}/${f}/upload/${$}`}async generateSignature($,f){let W=$.timestamp??Math.floor(Date.now()/1000),J=Object.entries({...$,timestamp:W}).sort(([X],[z])=>X.localeCompare(z)).map(([X,z])=>`${X}=${z}`).join("&");return{signature:await Qz.sha1(J+(f??this.config.api_secret)),timestamp:W}}filenameToPublicId($){return $.split(".").slice(0,-1).join(".")}async getObject($,f){let W=await fetch(this.getObjectUrl($),{method:"GET",headers:__(f,["range"])});return new Response(W.body,{status:W.status,statusText:W.statusText,headers:W.headers})}async deleteObject($){let f=this.guessType($)??"image",W=this.filenameToPublicId($),{timestamp:J,signature:Z}=await this.generateSignature({public_id:W}),X=new FormData;X.append("public_id",W),X.append("timestamp",String(J)),X.append("signature",Z),X.append("api_key",this.config.api_key);let z=`https://api.cloudinary.com/v1_1/${this.config.cloud_name}/${f}/destroy`,w=await fetch(z,{headers:{Accept:"application/json","Cache-Control":"no-cache",...this.getAuthorizationHeader()},method:"POST",body:X});if(!w.ok)throw new Error(`Failed to delete object: ${w.status} ${w.statusText}`)}toJSON($){return{type:"cloudinary",config:$?this.config:{cloud_name:this.config.cloud_name}}}}});var qm,Vm;var TQ=K(()=>{Um();Mm();qm=new _Q(($)=>({cls:$,schema:$.prototype.getSchema()})).register("s3",m7).register("cloudinary",k7),Vm={s3:{cls:m7,schema:m7.prototype.getSchema()},cloudinary:{cls:k7,schema:k7.prototype.getSchema()}}});var y7;var PQ=K(()=>{TQ();y7={media:qm}});function CQ(){let $=Y4(RY.all(),(f,W)=>{return R.strictObject({type:R.literal(W),config:f.schema},{title:f.schema?.title??W,description:f.schema?.description})});return R.strictObject({enabled:R.boolean({default:!1}),basepath:R.string({default:"/api/media"}),entity_name:R.string({default:"media"}),storage:R.strictObject({body_max_size:R.number({description:"Max size of the body in bytes. Leave blank for unlimited."}).optional()},{default:{}}),adapter:R.anyOf(Object.values($)).optional()},{default:{}})}var ri0,RY,li0;var Qm=K(()=>{TQ();PQ();_();ri0={...Vm},RY=y7.media;li0=CQ()});var MY;var EQ=K(()=>{R5();MY={path:ef().required(),folder:Bh({default_value:!1,hidden:!0,fillable:["create"]}),mime_type:ef(),size:z7(),scope:ef({hidden:!0,fillable:["create"]}),etag:ef(),modified_at:w7(),reference:ef(),entity_id:z7(),metadata:Th()}});var qY;var Im=K(()=>{_();Wm();q5();R5();Zm();Qm();EQ();HY();qY=class qY extends C${_storage;async build(){if(!this.config.enabled){this.setBuilt();return}if(!this.config.adapter){console.info("No storage adapter provided, skip building media.");return}let $;try{let{type:f,config:W}=this.config.adapter;$=new(RY.get(f)).cls(W),this._storage=new vW($,this.config.storage,this.ctx.emgr),this.setBuilt(),this.setupListeners(),this.ctx.guard.registerPermissions(D7),this.ctx.server.route(this.basepath,new xQ(this).getController());let Z=this.getMediaEntity(!0);this.ctx.helper.ensureSchema(EG({[Z.name]:Z},({index:X},{media:z})=>{X(z).on(["path"],!0).on(["reference"]).on(["entity_id"])}))}catch(f){throw console.error(f),new Error(`Could not build adapter with config ${JSON.stringify(this.config.adapter)}`)}}getSchema(){return CQ()}get basepath(){return this.config.basepath}get storage(){return this.throwIfNotBuilt(),this._storage}uploadedEventDataToMediaPayload($){let f={};if($.meta.width&&$.meta.height)f.width=$.meta.width,f.height=$.meta.height;return{path:$.name,mime_type:$.meta.type,size:$.meta.size,etag:$.etag,modified_at:new Date,metadata:f}}static mediaFields=MY;getMediaEntity($){let f=this.config.entity_name;if($||!this.em.hasEntity(f))return MW(f,qY.mediaFields,void 0,"system");return this.em.entity(f)}get em(){return this.ctx.em}setupListeners(){let{emgr:$,em:f}=this.ctx,W=this.getMediaEntity().name;$.onEvent(vW.Events.FileUploadedEvent,async(J)=>{let Z=f.mutator(W);Z.__unstable_toggleSystemEntityCreation(!1);let X=this.uploadedEventDataToMediaPayload(J.params),{data:z}=await Z.insertOne(X);return Z.__unstable_toggleSystemEntityCreation(!0),{data:z}},{mode:"sync",id:"add-data-media"}),$.onEvent(vW.Events.FileDeletedEvent,async(J)=>{let{data:Z}=await f.repo(W).findOne({path:J.params.name});if(Z)await f.mutator(W).deleteOne(Z.id);A.log("App:storage:file deleted",J.params)},{mode:"sync",id:"delete-data-media"})}getOverwritePaths(){return[/^\.?adapter$/]}toJSON($){if(!this.isBuilt()||!this.config.enabled)return this.configDefault;return{...this.config,adapter:this.storage.getAdapter().toJSON($)}}}});class hQ{ctx;constructor($){this.ctx=$}get em(){return this.ctx.em}get flags(){return this.ctx.flags}ensureEntity($){let f=this.em.entity($.name,!0);if(!f){this.em.addEntity($),this.flags.sync_required=!0;return}for(let W of $.fields){let J=f.field(W.name);if(!J)f.addField(W),this.flags.sync_required=!0;else if(this.setEntityFieldConfigs(W,J)>0)this.flags.sync_required=!0}if(f.type!==$.type){let W=KW.indexOf(f.type),Z=KW.indexOf($.type)>W?$.type:f.type;this.em.__replaceEntity(new P$(f.name,f.fields,f.config,Z))}}ensureIndex($){if(!this.em.hasIndex($))this.em.addIndex($),this.flags.sync_required=!0}ensureRelation($){try{this.em.addRelation($),this.flags.sync_required=!0}catch(f){}if(!this.em.relations.exists($));}ensureSchema($){return Object.values($.entities??{}).forEach(this.ensureEntity.bind(this)),$.indices?.forEach(this.ensureIndex.bind(this)),$.relations?.forEach(this.ensureRelation.bind(this)),$}setEntityFieldConfigs($,f,W=["hidden","fillable","required"]){let J=0;for(let Z of W)if(!Aq(f.config[Z],$.config[Z]))f.config[Z]=$.config[Z],J++;return J}replaceEntityField($,f,W){let J=this.em.entity($),Z=typeof f==="string"?f:f.name,X=W instanceof of?Ch(Z,W):W;this.setEntityFieldConfigs(J.field(Z),X),J.__replaceField(Z,X)}}var Om=K(()=>{R5();j4();xG();j2()});function kQ(){return{type:"object",...M0(j7,(f)=>f.prototype.getSchema())}}function yQ(){let $=M0(j7,(f)=>{return f.prototype.getSchema().template({},{withOptional:!0,withExtendedOptional:!0})});return structuredClone($)}var j7,xm,C$0,DQ,E$0,_m,vQ,Am,mQ;var g7=K(()=>{_();bN();V$();Y9();M2();pN();TG();R5();B$();OW();j2();JD();GD();WQ();gv();fm();Im();q5();Om();j7={server:WV,data:GQ,auth:PW,media:qY,flows:VQ},xm=Object.keys(j7),C$0=R.anyOf([kQ(),R.array(R.strictObject({t:R.string({enum:["a","r","e"]}),p:R.array(R.anyOf([R.string(),R.number()])),o:R.any().optional(),n:R.any().optional()}))]),DQ=MW(fD,{version:z7().required(),type:G7({enum:["config","diff","backup"]}).required(),json:Ph({schema:C$0.toJSON()}).required(),created_at:w7(),updated_at:w7()}),E$0=W9("modules_debug");_m=class _m extends s0{};vQ=class vQ extends _m{static slug="mm-config-update"};Am={ModuleManagerConfigUpdateEvent:vQ};mQ=class mQ{connection;options;static Events=Am;modules;__em;em;server;emgr;guard;_version=0;_built=!1;_booted_with;_stable_configs;logger;constructor($,f){this.connection=$;this.options=f;this.__em=new k9([DQ],this.connection),this.modules={},this.emgr=new Q$({...Am}),this.logger=new gH(E$0);let W={};if(f?.initial)if("version"in f.initial){let{version:J,...Z}=f.initial;this._version=J,W=gJ(Z),this._booted_with="provided"}else W=Oq(yQ(),f.initial),this._booted_with="partial";this.logger.log("booted with",this._booted_with),this.createModules(W)}createModules($){this.logger.context("createModules").log("creating modules");try{let f=this.ctx(!0);for(let W in j7){let J=$&&W in $?$[W]:{},Z=new j7[W](J,f);Z.setListener(async(X)=>{await this.onModuleConfigUpdated(W,X)}),this.modules[W]=Z}this.logger.log("modules created")}catch(f){throw this.logger.log("failed to create modules",f),f}this.logger.clear()}get verbosity(){return this.options?.verbosity??0}isBuilt(){return this._built}async onModuleConfigUpdated($,f){if(this.options?.onUpdated)await this.options.onUpdated($,f);else await this.buildModules()}repo(){return this.__em.repo(DQ,{silent:!0,includeCounts:!1})}mutator(){return this.__em.mutator(DQ)}get db(){return this.connection.kysely}async syncConfigTable(){this.logger.context("sync").log("start");let $=await this.__em.schema().sync({force:!0});return this.logger.log("done").clear(),$}rebuildServer(){if(this.server=new o$,this.options?.basePath)this.server=this.server.basePath(this.options.basePath);if(this.options?.onServerInit)this.options.onServerInit(this.server);uK(this.modules,($)=>{$.onServerInit(this.server)})}ctx($){if($)this.rebuildServer(),this.em=this.em?this.em.clear():new k9([],this.connection,[],[],this.emgr),this.guard=new bz;let f={connection:this.connection,server:this.server,em:this.em,emgr:this.emgr,guard:this.guard,flags:C$.ctx_flags,logger:this.logger};return{...f,helper:new hQ(f)}}async fetch(){this.logger.context("fetch").log("fetching");let $=performance.now(),{data:f}=await this.repo().findOne({type:"config"},{sort:{by:"version",dir:"desc"}});if(!f){this.logger.log("error fetching").clear();return}return this.logger.log("took",performance.now()-$,"ms",{version:f.version,id:f.id}).clear(),f}async save(){this.logger.context("save").log("saving version",this.version());let $=this.configs(),f=this.version();try{let W=await this.fetch();if(!W)throw new R2("no config found");if(this.logger.log("fetched version",W.version),W.version!==f)this.logger.log("version conflict, storing new version",W.version,f),await this.mutator().insertOne({version:W.version,type:"backup",json:$}),await this.mutator().insertOne({version:f,type:"config",json:$});else{this.logger.log("version matches",W.version);let J=rN(W.json,f8($));if(this.logger.log("checking diff",[J.length]),J.length>0){this.validateDiffs(J);let Z=new Date;await this.mutator().insertOne({version:f,type:"diff",json:f8(J),created_at:Z,updated_at:Z}),await this.mutator().updateWhere({version:f,json:$,updated_at:Z},{type:"config",version:f})}else this.logger.log("no diff, not saving")}}catch(W){if(W instanceof R2&&W.message==="no config found")this.logger.log("no config, just save fresh"),await this.mutator().insertOne({type:"config",version:f,json:$,created_at:new Date,updated_at:new Date});else if(W instanceof f1)throw A.error("ModuleManager: Cannot save invalid config"),this.revertModules(),W;else throw A.error("ModuleManager: Aborting"),this.revertModules(),W}return this.setConfigs($),this.logger.clear(),this}revertModules(){if(this._stable_configs)A.warn("ModuleManager: Reverting modules"),this.setConfigs(this._stable_configs);else A.error("ModuleManager: No stable configs to revert to")}validateDiffs($){let f=[...new Set($.map((W)=>W.p[0]))];if(f.length===0)return;for(let W of f){let J=W,Z=this.get(J);if(!Z)throw A.error("validateDiffs: module not registered",JSON.stringify({module:J,diffs:$},null,2)),new Error("validateDiffs: module not registered");if(this._stable_configs?.[J]){let X=f8(this._stable_configs?.[J]),z=lN({[J]:X},$)[J];Z.onBeforeUpdate(X,z)}}}setConfigs($){this.logger.log("setting configs"),uK($,(f,W)=>{try{this.modules[W].schema().set(f,!0)}catch(J){throw console.error(J),new Error(`Failed to set config for module ${W}: ${JSON.stringify(f,null,2)}`)}})}async build($){if(this.logger.context("build").log("version",this.version()),await this.ctx().connection.init(),this.version()===0||$?.fetch===!0){if($?.fetch)this.logger.log("force fetch");let f=await this.fetch();if(!f)this.logger.log("nothing in database, go initial"),await this.setupInitial();else{if(this.logger.log("db has",f.version),this._version=f.version,this.options?.trustFetched===!0)this.logger.log("trusting fetched config (mark)"),kH(f.json);if(this.version()!==AW){this.logger.log("now migrating"),await this.syncConfigTable();let W=this.version(),[J,Z]=await WD(W,f.json,{db:this.db});this._version=J,this.ctx().flags.sync_required=!0,this.logger.log("migrated to",J),A.log("Migrated config from",W,"to",this.version()),this.createModules(Z),await this.buildModules()}else this.logger.log("version is current",this.version()),this.createModules(f.json),await this.buildModules()}}else{if(this.version()!==AW)throw new Error(`Given version (${this.version()}) and current version (${AW}) do not match.`);this.logger.log("current version is up to date",this.version()),await this.buildModules()}return this.logger.log("done"),this.logger.clear(),this}async buildModules($){let f={built:!1,modules:[],synced:!1,saved:!1,reloaded:!1};if(this.logger.context("buildModules").log("triggered",$,this._built),$?.graceful&&this._built)return this.logger.log("skipping build (graceful)"),f;this.logger.log("building");let W=this.ctx(!0);for(let J in this.modules)await this.modules[J].setContext(W).build(),this.logger.log("built",J),f.modules.push(J);if(this._built=f.built=!0,this.logger.log("modules built",W.flags),this.options?.onModulesBuilt)await this.options.onModulesBuilt(W);if($?.ignoreFlags!==!0){if(W.flags.sync_required)W.flags.sync_required=!1,this.logger.log("db sync requested"),await W.em.schema().sync({force:!0}),f.synced=!0,await this.save(),f.saved=!0;if(W.flags.ctx_reload_required)W.flags.ctx_reload_required=!1,this.logger.log("ctx reload requested"),this.ctx(!0),f.reloaded=!0}return this.logger.log("resetting flags"),W.flags=C$.ctx_flags,this._stable_configs=f8(this.configs()),this.logger.clear(),f}async setupInitial(){if(this.logger.context("initial").log("start"),this._version=AW,await this.syncConfigTable(),!(await this.buildModules()).saved)await this.save();let f={...this.ctx(),em:this.ctx().em.fork()};await f.em.schema().sync({force:!0}),await this.options?.seed?.(f),await this.options?.onFirstBoot?.(),this.logger.clear()}mutateConfigSafe($){let f=this.modules[$];return new Proxy(f.schema(),{get:(W,J)=>{if(!["set","patch","overwrite","remove"].includes(J))throw new Error(`Method ${J} is not allowed`);return async(...Z)=>{A.log("[Safe Mutate]",$);try{f.setListener(async()=>{await this.emgr.emit(new vQ({ctx:this.ctx(),module:$,config:f.config})),await this.buildModules()});let X=await W[J](...Z);if(f.setListener(async(z)=>{await this.onModuleConfigUpdated($,z)}),this.options?.onUpdated)await this.options.onUpdated($,f.config);return X}catch(X){throw A.error(`[Safe Mutate] failed "${$}":`,X),this.revertModules(),await this.onModuleConfigUpdated($,f.config),A.warn(`[Safe Mutate] reverted "${$}":`),X}}}})}get($){if(!($ in this.modules))throw new Error(`Module "${$}" doesn't exist, cannot get`);return this.modules[$]}version(){return this._version}built(){return this._built}configs(){return M0(this.modules,($)=>$.toJSON(!0))}getSchema(){let $=M0(this.modules,(f)=>f.getSchema());return{version:this.version(),...$}}toJSON($){let f=M0(this.modules,(W)=>{if(this._built)return W.isBuilt()?W.toJSON($):W.configDefault;return});return{version:this.version(),...f}}}});var b7=($,...f)=>{let W=[""];for(let J=0,Z=$.length-1;J<Z;J++){W[0]+=$[J];let X=Array.isArray(f[J])?f[J].flat(1/0):[f[J]];for(let z=0,w=X.length;z<w;z++){let G=X[z];if(typeof G==="string")u2(G,W);else if(typeof G==="number")W[0]+=G;else if(typeof G==="boolean"||G===null||G===void 0)continue;else if(typeof G==="object"&&G.isEscaped)if(G.callbacks)W.unshift("",G);else{let Y=G.toString();if(Y instanceof Promise)W.unshift("",Y);else W[0]+=Y}else if(G instanceof Promise)W.unshift("",G);else u2(G.toString(),W)}}return W[0]+=$.at(-1),W.length===1?"callbacks"in W?S0(vG(S0(W[0],W.callbacks))):S0(W[0]):DG(W,W.callbacks)};var g9=K(()=>{qW()});var xf,l4,v0,VY,jQ,mW;var e$=K(()=>{xf=Symbol("RENDERER"),l4=Symbol("ERROR_HANDLER"),v0=Symbol("STASH"),VY=Symbol("INTERNAL"),jQ=Symbol("MEMO"),mW=Symbol("PERMALINK")});var gQ=($)=>{return $[VY]=!0,$};var Fm=K(()=>{e$()});var bQ=($)=>({value:f,children:W})=>{if(!W)return;let J={children:[{tag:gQ(()=>{$.push(f)}),props:{}}]};if(Array.isArray(W))J.children.push(...W.flat());else J.children.push(W);J.children.push({tag:gQ(()=>{$.pop()}),props:{}});let Z={tag:"",props:J,type:""};return Z[l4]=(X)=>{throw $.pop(),X},Z},QY=($)=>{let f=[$],W=bQ(f);return W.values=f,W.Provider=W,b9.push(W),W};var IY=K(()=>{e$();c2();Fm()});var b9,u7=($)=>{let f=[$],W=(J)=>{f.push(J.value);let Z;try{Z=J.children?(Array.isArray(J.children)?new uQ("",{},J.children):J.children).toString():""}finally{f.pop()}if(Z instanceof Promise)return Z.then((X)=>S0(X,X.callbacks));else return S0(Z)};return W.values=f,W.Provider=W,W[xf]=bQ(f),b9.push(W),W},f$=($)=>{return $.values.at(-1)};var c2=K(()=>{g9();F5();e$();IY();b9=[]});var kW,c7,yW="data-precedence";var OY=K(()=>{kW={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},c7={}});var B5=($)=>Array.isArray($)?$:[$];var AY=()=>{};var r7={};V1(r7,{title:()=>h$0,style:()=>v$0,script:()=>D$0,meta:()=>k$0,link:()=>m$0,input:()=>j$0,form:()=>y$0,button:()=>g$0});var Bm,Tm=($,f,W,J)=>({buffer:Z,context:X})=>{if(!Z)return;let z=Bm.get(X)||{};Bm.set(X,z);let w=z[$]||=[],G=!1,Y=kW[$];if(Y.length>0)$:for(let[,L]of w)for(let U of Y)if((L?.[U]??null)===W?.[U]){G=!0;break $}if(G)Z[0]=Z[0].replaceAll(f,"");else if(Y.length>0)w.push([f,W,J]);else w.unshift([f,W,J]);if(Z[0].indexOf("</head>")!==-1){let L;if(J===void 0)L=w.map(([U])=>U);else{let U=[];L=w.map(([M,,q])=>{let V=U.indexOf(q);if(V===-1)U.push(q),V=U.length-1;return[M,V]}).sort((M,q)=>M[1]-q[1]).map(([M])=>M)}L.forEach((U)=>{Z[0]=Z[0].replaceAll(U,"")}),Z[0]=Z[0].replace(/(?=<\/head>)/,L.join(""))}},d7=($,f,W)=>S0(new $f($,W,B5(f??[])).toString()),i7=($,f,W,J)=>{if("itemProp"in W)return d7($,f,W);let{precedence:Z,blocking:X,...z}=W;if(Z=J?Z??"":void 0,J)z[yW]=Z;let w=new $f($,z,B5(f||[])).toString();if(w instanceof Promise)return w.then((G)=>S0(w,[...G.callbacks||[],Tm($,G,z,Z)]));else return S0(w,[Tm($,w,z,Z)])},h$0=({children:$,...f})=>{let W=xY();if(W){let J=f$(W);if(J==="svg"||J==="head")return new $f("title",f,B5($??[]))}return i7("title",$,f,!1)},D$0=({children:$,...f})=>{let W=xY();if(["src","async"].some((J)=>!f[J])||W&&f$(W)==="head")return d7("script",$,f);return i7("script",$,f,!1)},v$0=({children:$,...f})=>{if(!["href","precedence"].every((W)=>(W in f)))return d7("style",$,f);return f["data-href"]=f.href,delete f.href,i7("style",$,f,!0)},m$0=({children:$,...f})=>{if(["onLoad","onError"].some((W)=>(W in f))||f.rel==="stylesheet"&&(!("precedence"in f)||("disabled"in f)))return d7("link",$,f);return i7("link",$,f,"precedence"in f)},k$0=({children:$,...f})=>{let W=xY();if(W&&f$(W)==="head")return d7("meta",$,f);return i7("meta",$,f,!1)},Pm=($,{children:f,...W})=>new $f($,W,B5(f??[])),y$0=($)=>{if(typeof $.action==="function")$.action=mW in $.action?$.action[mW]:void 0;return Pm("form",$)},Cm=($,f)=>{if(typeof f.formAction==="function")f.formAction=mW in f.formAction?f.formAction[mW]:void 0;return Pm($,f)},j$0=($)=>Cm("input",$),g$0=($)=>Cm("button",$);var Em=K(()=>{g9();F5();AY();e$();c2();OY();Bm=new WeakMap});var b$0,jW=($)=>b$0.get($)||$,_Y=($,f)=>{for(let[W,J]of Object.entries($)){let Z=W[0]==="-"||!/[A-Z]/.test(W)?W:W.replace(/[A-Z]/g,(X)=>`-${X.toLowerCase()}`);f(Z,J==null?null:typeof J==="number"?!Z.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${J}px`:`${J}`:J)}};var cQ=K(()=>{b$0=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]])});var l7=void 0,xY=()=>l7,u$0=($)=>/[A-Z]/.test($)&&$.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?$.replace(/([A-Z])/g,"-$1").toLowerCase():$,c$0,d$0,iQ=($,f)=>{for(let W=0,J=$.length;W<J;W++){let Z=$[W];if(typeof Z==="string")u2(Z,f);else if(typeof Z==="boolean"||Z===null||Z===void 0)continue;else if(Z instanceof $f)Z.toStringToBuffer(f);else if(typeof Z==="number"||Z.isEscaped)f[0]+=Z;else if(Z instanceof Promise)f.unshift("",Z);else iQ(Z,f)}},$f=class{tag;props;key;children;isEscaped=!0;localContexts;constructor($,f,W){this.tag=$,this.props=f,this.children=W}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){let $=[""];this.localContexts?.forEach(([f,W])=>{f.values.push(W)});try{this.toStringToBuffer($)}finally{this.localContexts?.forEach(([f])=>{f.values.pop()})}return $.length===1?"callbacks"in $?vG(S0($[0],$.callbacks)).toString():$[0]:DG($,$.callbacks)}toStringToBuffer($){let f=this.tag,W=this.props,{children:J}=this;$[0]+=`<${f}`;let Z=l7&&f$(l7)==="svg"?(X)=>u$0(jW(X)):(X)=>jW(X);for(let[X,z]of Object.entries(W))if(X=Z(X),X==="children");else if(X==="style"&&typeof z==="object"){let w="";_Y(z,(G,Y)=>{if(Y!=null)w+=`${w?";":""}${G}:${Y}`}),$[0]+=' style="',u2(w,$),$[0]+='"'}else if(typeof z==="string")$[0]+=` ${X}="`,u2(z,$),$[0]+='"';else if(z===null||z===void 0);else if(typeof z==="number"||z.isEscaped)$[0]+=` ${X}="${z}"`;else if(typeof z==="boolean"&&d$0.includes(X)){if(z)$[0]+=` ${X}=""`}else if(X==="dangerouslySetInnerHTML"){if(J.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");J=[S0(z.__html)]}else if(z instanceof Promise)$[0]+=` ${X}="`,$.unshift('"',z);else if(typeof z==="function"){if(!X.startsWith("on")&&X!=="ref")throw new Error(`Invalid prop '${X}' of type 'function' supplied to '${f}'.`)}else $[0]+=` ${X}="`,u2(z.toString(),$),$[0]+='"';if(c$0.includes(f)&&J.length===0){$[0]+="/>";return}$[0]+=">",iQ(J,$),$[0]+=`</${f}>`}},dQ,uQ,hm=!1,NY=($,f,W)=>{if(!hm){for(let J in c7)r7[J][xf]=c7[J];hm=!0}if(typeof $==="function")return new dQ($,f,W);else if(r7[$])return new dQ(r7[$],f,W);else if($==="svg"||$==="head")return l7||=u7(""),new $f($,f,[new dQ(l7,{value:$},W)]);else return new $f($,f,W)},gW=({children:$})=>{return new uQ("",{children:$},Array.isArray($)?$:$?[$]:[])};var F5=K(()=>{g9();qW();e$();c2();OY();Em();cQ();c$0=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],d$0=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],dQ=class extends $f{toStringToBuffer($){let{children:f}=this,W=this.tag.call(null,{...this.props,children:f.length<=1?f[0]:f});if(typeof W==="boolean"||W==null)return;else if(W instanceof Promise)if(b9.length===0)$.unshift("",W);else{let J=b9.map((Z)=>[Z,Z.values.at(-1)]);$.unshift("",W.then((Z)=>{if(Z instanceof $f)Z.localContexts=J;return Z}))}else if(W instanceof $f)W.toStringToBuffer($);else if(typeof W==="number"||W.isEscaped){if($[0]+=W,W.callbacks)$.callbacks||=[],$.callbacks.push(...W.callbacks)}else u2(W,$)}},uQ=class extends $f{toStringToBuffer($){iQ(this.children,$)}}});var n7="_hp",i$0,r$0,d2,lQ,bW=void 0,gm=()=>bW,u9=($)=>("t"in $),rQ,Dm=($)=>{if(!$.startsWith("on"))return;if(rQ[$])return rQ[$];let f=$.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(f){let[,W,J]=f;return rQ[$]=[(i$0[W]||W).toLowerCase(),!!J]}return},vm=($,f)=>bW&&$ instanceof SVGElement&&/[A-Z]/.test(f)&&((f in $.style)||f.match(/^(?:o|pai|str|u|ve)/))?f.replace(/([A-Z])/g,"-$1").toLowerCase():f,l$0=($,f,W)=>{f||={};for(let J in f){let Z=f[J];if(J!=="children"&&(!W||W[J]!==Z)){J=jW(J);let X=Dm(J);if(X){if(W?.[J]!==Z){if(W)$.removeEventListener(X[0],W[J],X[1]);if(Z!=null){if(typeof Z!=="function")throw new Error(`Event handler for "${J}" is not a function`);$.addEventListener(X[0],Z,X[1])}}}else if(J==="dangerouslySetInnerHTML"&&Z)$.innerHTML=Z.__html;else if(J==="ref"){let z;if(typeof Z==="function")z=Z($)||(()=>Z(null));else if(Z&&"current"in Z)Z.current=$,z=()=>Z.current=null;lQ.set($,z)}else if(J==="style"){let z=$.style;if(typeof Z==="string")z.cssText=Z;else if(z.cssText="",Z!=null)_Y(Z,z.setProperty.bind(z))}else{if(J==="value"){let w=$.nodeName;if(w==="INPUT"||w==="TEXTAREA"||w==="SELECT"){if($.value=Z===null||Z===void 0||Z===!1?null:Z,w==="TEXTAREA"){$.textContent=Z;continue}else if(w==="SELECT"){if($.selectedIndex===-1)$.selectedIndex=0;continue}}}else if(J==="checked"&&$.nodeName==="INPUT"||J==="selected"&&$.nodeName==="OPTION")$[J]=Z;let z=vm($,J);if(Z===null||Z===void 0||Z===!1)$.removeAttribute(z);else if(Z===!0)$.setAttribute(z,"");else if(typeof Z==="string"||typeof Z==="number")$.setAttribute(z,Z);else $.setAttribute(z,Z.toString())}}}if(W)for(let J in W){let Z=W[J];if(J!=="children"&&!(J in f)){J=jW(J);let X=Dm(J);if(X)$.removeEventListener(X[0],Z,X[1]);else if(J==="ref")lQ.get($)?.();else $.removeAttribute(vm($,J))}}},p$0=($,f)=>{f[v0][0]=0,d2.push([$,f]);let W=f.tag[xf]||f.tag,J=W.defaultProps?{...W.defaultProps,...f.props}:f.props;try{return[W.call(null,J)]}finally{d2.pop()}},bm=($,f,W,J,Z)=>{if($.vR?.length)J.push(...$.vR),delete $.vR;if(typeof $.tag==="function")$[v0][1][nQ]?.forEach((X)=>Z.push(X));$.vC.forEach((X)=>{if(u9(X))W.push(X);else if(typeof X.tag==="function"||X.tag===""){X.c=f;let z=W.length;if(bm(X,f,W,J,Z),X.s){for(let w=z;w<W.length;w++)W[w].s=!0;X.s=!1}}else if(W.push(X),X.vR?.length)J.push(...X.vR),delete X.vR})},n$0=($)=>{for(;;$=$.tag===n7||!$.vC||!$.pP?$.nN:$.vC[0]){if(!$)return null;if($.tag!==n7&&$.e)return $.e}},um=($)=>{if(!u9($)){if($[v0]?.[1][nQ]?.forEach((f)=>f[2]?.()),lQ.get($.e)?.(),$.p===2)$.vC?.forEach((f)=>f.p=2);$.vC?.forEach(um)}if(!$.p)$.e?.remove(),delete $.e;if(typeof $.tag==="function")p7.delete($),SY.delete($),delete $[v0][3],$.a=!0},cm=($,f,W)=>{$.c=f,dm($,f,W)},mm=($,f)=>{if(!f)return;for(let W=0,J=$.length;W<J;W++)if($[W]===f)return W;return},km,dm=($,f,W)=>{let J=[],Z=[],X=[];bm($,f,J,Z,X),Z.forEach(um);let z=W?void 0:f.childNodes,w,G=null;if(W)w=-1;else if(!z.length)w=0;else{let Y=mm(z,n$0($.nN));if(Y!==void 0)G=z[Y],w=Y;else w=mm(z,J.find((L)=>L.tag!==n7&&L.e)?.e)??-1;if(w===-1)W=!0}for(let Y=0,L=J.length;Y<L;Y++,w++){let U=J[Y],M;if(U.s&&U.e)M=U.e,U.s=!1;else{let q=W||!U.e;if(u9(U)){if(U.e&&U.d)U.e.textContent=U.t;U.d=!1,M=U.e||=document.createTextNode(U.t)}else M=U.e||=U.n?document.createElementNS(U.n,U.tag):document.createElement(U.tag),l$0(M,U.props,U.pP),dm(U,M,q)}if(U.tag===n7)w--;else if(W){if(!M.parentNode)f.appendChild(M)}else if(z[w]!==M&&z[w-1]!==M)if(z[w+1]===M)f.appendChild(z[w]);else f.insertBefore(M,G||z[w]||null)}if($.pP)delete $.pP;if(X.length){let Y=[],L=[];if(X.forEach(([,U,,M,q])=>{if(U)Y.push(U);if(M)L.push(M);q?.()}),Y.forEach((U)=>U()),L.length)requestAnimationFrame(()=>{L.forEach((U)=>U())})}},s$0=($,f)=>!!($&&$.length===f.length&&$.every((W,J)=>W[1]===f[J][1])),SY,pQ=($,f,W)=>{let J=!W&&f.pC;if(W)f.pC||=f.vC;let Z;try{if(W||=typeof f.tag=="function"?p$0($,f):B5(f.props.children),W[0]?.tag===""&&W[0][l4])Z=W[0][l4],$[5].push([$,Z,f]);let X=J?[...f.pC]:f.vC?[...f.vC]:void 0,z=[],w;for(let G=0;G<W.length;G++){if(Array.isArray(W[G]))W.splice(G,1,...W[G].flat());let Y=t$0(W[G]);if(Y){if(typeof Y.tag==="function"&&!Y.tag[VY]){if(b9.length>0)Y[v0][2]=b9.map((U)=>[U,U.values.at(-1)]);if($[5]?.length)Y[v0][3]=$[5].at(-1)}let L;if(X&&X.length){let U=X.findIndex(u9(Y)?(M)=>u9(M):Y.key!==void 0?(M)=>M.key===Y.key&&M.tag===Y.tag:(M)=>M.tag===Y.tag);if(U!==-1)L=X[U],X.splice(U,1)}if(L)if(u9(Y)){if(L.t!==Y.t)L.t=Y.t,L.d=!0;Y=L}else{let U=L.pP=L.props;if(L.props=Y.props,L.f||=Y.f||f.f,typeof Y.tag==="function"){let M=L[v0][2];if(L[v0][2]=Y[v0][2]||[],L[v0][3]=Y[v0][3],!L.f&&((L.o||L)===Y.o||L.tag[jQ]?.(U,L.props))&&s$0(M,L[v0][2]))L.s=!0}Y=L}else if(!u9(Y)&&bW){let U=f$(bW);if(U)Y.n=U}if(!u9(Y)&&!Y.s)pQ($,Y),delete Y.f;if(z.push(Y),w&&!w.s&&!Y.s)for(let U=w;U&&!u9(U);U=U.vC?.at(-1))U.nN=Y;w=Y}}if(f.vR=J?[...f.vC,...X||[]]:X||[],f.vC=z,J)delete f.pC}catch(X){if(f.f=!0,X===km)if(Z)return;else throw X;let[z,w,G]=f[v0]?.[3]||[];if(w){let Y=()=>s7([0,!1,$[2]],G),L=SY.get(G)||[];L.push(Y),SY.set(G,L);let U=w(X,()=>{let M=SY.get(G);if(M){let q=M.indexOf(Y);if(q!==-1)return M.splice(q,1),Y()}});if(U){if($[0]===1)$[1]=!0;else if(pQ($,G,[U]),(w.length===1||$!==z)&&G.c){cm(G,G.c,!1);return}throw km}}throw X}finally{if(Z)$[5].pop()}},t$0=($)=>{if($===void 0||$===null||typeof $==="boolean")return;else if(typeof $==="string"||typeof $==="number")return{t:$.toString(),d:!0};else{if("vR"in $)$={tag:$.tag,props:$.props,key:$.key,f:$.f,type:$.tag,ref:$.props.ref,o:$.o||$};if(typeof $.tag==="function")$[v0]=[0,[]];else{let f=r$0[$.tag];if(f)bW||=QY(""),$.props.children=[{tag:bW,props:{value:$.n=`http://www.w3.org/${f}`,children:$.props.children}}]}return $}},ym=($,f)=>{f[v0][2]?.forEach(([W,J])=>{W.values.push(J)});try{pQ($,f,void 0)}catch{return}if(f.a){delete f.a;return}if(f[v0][2]?.forEach(([W])=>{W.values.pop()}),$[0]!==1||!$[1])cm(f,f.c,!1)},p7,jm,s7=async($,f)=>{$[5]||=[];let W=p7.get(f);if(W)W[0](void 0);let J,Z=new Promise((X)=>J=X);if(p7.set(f,[J,()=>{if($[2])$[2]($,f,(X)=>{ym(X,f)}).then(()=>J(f));else ym($,f),J(f)}]),jm.length)jm.at(-1).add(f);else{await Promise.resolve();let X=p7.get(f);if(X)p7.delete(f),X[1]()}return Z},im=($,f,W)=>({tag:n7,props:{children:$},key:W,e:f,p:1});var FY=K(()=>{AY();e$();c2();t7();cQ();IY();i$0={Change:"Input",DoubleClick:"DblClick"},r$0={svg:"2000/svg",math:"1998/Math/MathML"},d2=[],lQ=new WeakMap,rQ={onClick:["click",!1]},km=Symbol(),SY=new WeakMap,p7=new WeakMap,jm=[]});var a$0=0,nQ=1,o$0=2,e$0=3,sQ,lm=($,f)=>!$||!f||$.length!==f.length||f.some((W,J)=>W!==$[J]),$f0=void 0,rm,BY=($)=>{let f=()=>typeof $==="function"?$():$,W=d2.at(-1);if(!W)return[f(),()=>{}];let[,J]=W,Z=J[v0][1][a$0]||=[],X=J[v0][0]++;return Z[X]||=[f(),(z)=>{let w=$f0,G=Z[X];if(typeof z==="function")z=z(G[0]);if(!Object.is(z,G[0]))if(G[0]=z,rm.length){let[Y,L]=rm.at(-1);Promise.all([Y===3?J:s7([Y,!1,w],J),L]).then(([U])=>{if(!U||!(Y===2||Y===3))return;let M=U.vC;requestAnimationFrame(()=>{setTimeout(()=>{if(M!==U.vC)return;s7([Y===3?1:0,!1,w],U)})})})}else s7([0,!1,w],J)}]},uW=($,f)=>{let W=d2.at(-1);if(!W)return $;let[,J]=W,Z=J[v0][1][o$0]||=[],X=J[v0][0]++,z=Z[X];if(lm(z?.[1],f))Z[X]=[$,f];else $=Z[X][0];return $},tQ=($)=>{let f=sQ.get($);if(f){if(f.length===2)throw f[1];return f[0]}throw $.then((W)=>sQ.set($,[W]),(W)=>sQ.set($,[void 0,W])),$},aQ=($,f)=>{let W=d2.at(-1);if(!W)return $();let[,J]=W,Z=J[v0][1][e$0]||=[],X=J[v0][0]++,z=Z[X];if(lm(z?.[1],f))Z[X]=[$(),f];return Z[X][0]};var t7=K(()=>{e$();FY();sQ=new WeakMap,rm=[]});var nm,pm,sm=($)=>{pm.add($),$.finally(()=>pm.delete($))};var oQ=K(()=>{e$();c2();t7();IY();nm=QY({pending:!1,data:null,method:null,action:null}),pm=new Set});var PY={};V1(PY,{title:()=>tm,style:()=>om,script:()=>am,meta:()=>$k,link:()=>em,input:()=>Zk,form:()=>Wk,composeRef:()=>TY,clearCache:()=>ff0,button:()=>Xk});var ff0=()=>{eQ=Object.create(null),$I=Object.create(null)},TY=($,f)=>{return aQ(()=>(W)=>{let J;if($){if(typeof $==="function")J=$(W)||(()=>{$(null)});else if($&&"current"in $)$.current=W,J=()=>{$.current=null}}let Z=f(W);return()=>{Z?.(),J?.()}},[$])},eQ,$I,a7=($,f,W,J,Z)=>{if(f?.itemProp)return{tag:$,props:f,type:$,ref:f.ref};let X=document.head,{onLoad:z,onError:w,precedence:G,blocking:Y,...L}=f,U=null,M=!1,q=kW[$],V=void 0;if(q.length>0){let y=X.querySelectorAll($);$:for(let F of y)for(let B of kW[$])if(F.getAttribute(B)===f[B]){U=F;break $}if(!U){let F=q.reduce((B,i)=>f[i]===void 0?B:`${B}-${i}-${f[i]}`,$);M=!$I[F],U=$I[F]||=(()=>{let B=document.createElement($);for(let i of q){if(f[i]!==void 0)B.setAttribute(i,f[i]);if(f.rel)B.setAttribute("rel",f.rel)}return B})()}}else V=X.querySelectorAll($);if(G=J?G??"":void 0,J)L[yW]=G;let Q=uW((y)=>{if(q.length>0){let F=!1;for(let B of X.querySelectorAll($)){if(F&&B.getAttribute(yW)!==G){X.insertBefore(y,B);return}if(B.getAttribute(yW)===G)F=!0}X.appendChild(y)}else if(V){let F=!1;for(let B of V)if(B===y){F=!0;break}if(!F)X.insertBefore(y,X.contains(V[0])?V[0]:X.querySelector($));V=void 0}},[G]),O=TY(f.ref,(y)=>{let F=q[0];if(W===2)y.innerHTML="";if(M||V)Q(y);if(!w&&!z)return;let B=eQ[y.getAttribute(F)]||=new Promise((i,w0)=>{y.addEventListener("load",i),y.addEventListener("error",w0)});if(z)B=B.then(z);if(w)B=B.catch(w);B.catch(()=>{})});if(Z&&Y==="render"){let y=kW[$][0];if(f[y]){let F=f[y],B=eQ[F]||=new Promise((i,w0)=>{Q(U),U.addEventListener("load",i),U.addEventListener("error",w0)});tQ(B)}}let x={tag:$,type:$,props:{...L,ref:O},ref:O};if(x.p=W,U)x.e=U;return im(x,X)},tm=($)=>{let f=gm();if((f&&f$(f))?.endsWith("svg"))return{tag:"title",props:$,type:"title",ref:$.ref};return a7("title",$,void 0,!1,!1)},am=($)=>{if(!$||["src","async"].some((f)=>!$[f]))return{tag:"script",props:$,type:"script",ref:$.ref};return a7("script",$,1,!1,!0)},om=($)=>{if(!$||!["href","precedence"].every((f)=>(f in $)))return{tag:"style",props:$,type:"style",ref:$.ref};return $["data-href"]=$.href,delete $.href,a7("style",$,2,!0,!0)},em=($)=>{if(!$||["onLoad","onError"].some((f)=>(f in $))||$.rel==="stylesheet"&&(!("precedence"in $)||("disabled"in $)))return{tag:"link",props:$,type:"link",ref:$.ref};return a7("link",$,1,"precedence"in $,!0)},$k=($)=>{return a7("meta",$,void 0,!1,!1)},fk,Wk=($)=>{let{action:f,...W}=$;if(typeof f!=="function")W.action=f;let[J,Z]=BY([null,!1]),X=uW(async(Y)=>{let L=Y.isTrusted?f:Y.detail[fk];if(typeof L!=="function")return;Y.preventDefault();let U=new FormData(Y.target);Z([U,!0]);let M=L(U);if(M instanceof Promise)sm(M),await M;Z([null,!0])},[]),z=TY($.ref,(Y)=>{return Y.addEventListener("submit",X),()=>{Y.removeEventListener("submit",X)}}),[w,G]=J;return J[1]=!1,{tag:nm,props:{value:{pending:w!==null,data:w,method:w?"post":null,action:w?f:null},children:{tag:"form",props:{...W,ref:z},type:"form",ref:z}},f:G}},Jk=($,{formAction:f,...W})=>{if(typeof f==="function"){let J=uW((Z)=>{Z.preventDefault(),Z.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[fk]:f}}))},[]);W.ref=TY(W.ref,(Z)=>{return Z.addEventListener("click",J),()=>{Z.removeEventListener("click",J)}})}return{tag:$,props:W,type:$,ref:W.ref}},Zk=($)=>Jk("input",$),Xk=($)=>Jk("button",$);var zk=K(()=>{c2();t7();OY();oQ();FY();eQ=Object.create(null),$I=Object.create(null),fk=Symbol();Object.assign(c7,{title:tm,script:am,style:om,link:em,meta:$k,form:Wk,input:Zk,button:Xk})});var fI=($,f,W)=>{if(typeof $==="string"&&PY[$])$=PY[$];return{tag:$,type:$,props:f,key:W,ref:f.ref}},CY=($)=>fI("",$,void 0);var WI=K(()=>{zk()});var wk=K(()=>{WI();WI()});var Gk=({children:$,fallback:f,fallbackRender:W,onError:J})=>{let Z=CY({children:$});return Z[l4]=(X)=>{if(X instanceof Promise)throw X;return J?.(X),W?.(X)||f},Z},Yk=({children:$,fallback:f})=>{let W=CY({children:$});return W[l4]=(J,Z)=>{if(!(J instanceof Promise))throw J;return J.finally(Z),f},W};var JI=K(()=>{e$();wk()});var ZI,Wf0=0,Lk=async({children:$,fallback:f})=>{if(!$)return f.toString();if(!Array.isArray($))$=[$];let W=f$(ZI)?.scriptNonce,J=[],Z={[v0]:[0,[]]},X=(z)=>{return d2.pop(),z};try{Z[v0][0]=0,d2.push([[],Z]),J=$.map((z)=>z==null||typeof z==="boolean"?"":z.toString())}catch(z){if(z instanceof Promise)J=[z.then(()=>{return Z[v0][0]=0,d2.push([[],Z]),EY($).then(X)})];else throw z}finally{X()}if(J.some((z)=>z instanceof Promise)){let z=Wf0++,w=await f.toString();return S0(`<template id="H:${z}"></template>${w}<!--/$-->`,[...w.callbacks||[],({phase:G,buffer:Y,context:L})=>{if(G===$2.BeforeStream)return;return Promise.all(J).then(async(U)=>{U=U.flat();let M=U.join("");if(Y)Y[0]=Y[0].replace(new RegExp(`<template id="H:${z}"></template>.*?<!--/\\$-->`),M);let q=Y?"":`<template data-hono-target="H:${z}">${M}</template><script${W?` nonce="${W}"`:""}>
((d,c,n) => {
c=d.currentScript.previousSibling
d=d.getElementById('H:${z}')
if(!d)return
do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')
d.replaceWith(c.content)
})(document)
</script>`,V=U.map((Q)=>Q.callbacks||[]).flat();if(!V.length)return q;if(G===$2.Stream)q=await M5(q,$2.BeforeStream,!0,L);return S0(q,V)})}])}else return S0(J.join(""))};var XI=K(()=>{g9();qW();F5();zI();e$();c2();JI();FY();ZI=u7(null);Lk[xf]=Yk});var Jf0=0,EY=async($)=>{try{return $.flat().map((f)=>f==null||typeof f==="boolean"?"":f.toString())}catch(f){if(f instanceof Promise)return await f,EY($);else throw f}},Kk=async({children:$,fallback:f,fallbackRender:W,onError:J})=>{if(!$)return S0("");if(!Array.isArray($))$=[$];let Z=f$(ZI)?.scriptNonce,X,z=(G)=>{return J?.(G),(X||W?.(G)||"").toString()},w=[];try{w=$.map((G)=>G==null||typeof G==="boolean"?"":G.toString())}catch(G){if(X=await f?.toString(),G instanceof Promise)w=[G.then(()=>EY($)).catch((Y)=>z(Y))];else w=[z(G)]}if(w.some((G)=>G instanceof Promise)){X||=await f?.toString();let G=Jf0++,Y=RegExp(`(<template id="E:${G}"></template>.*?)(.*?)(<!--E:${G}-->)`),L=!1,U=({error:V,buffer:Q})=>{if(L)return"";let O=z(V);if(Q)Q[0]=Q[0].replace(Y,O);return Q?"":`<template data-hono-target="E:${G}">${O}</template><script>
((d,c,n) => {
c=d.currentScript.previousSibling
d=d.getElementById('E:${G}')
if(!d)return
do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='E:${G}')
d.replaceWith(c.content)
})(document)
</script>`},M,q=Promise.all(w).catch((V)=>M=V);return S0(`<template id="E:${G}"></template><!--E:${G}-->`,[({phase:V,buffer:Q,context:O})=>{if(V===$2.BeforeStream)return;return q.then(async(x)=>{if(M)throw M;x=x.flat();let y=x.join(""),F=Q?"":`<template data-hono-target="E:${G}">${y}</template><script${Z?` nonce="${Z}"`:""}>
((d,c) => {
c=d.currentScript.previousSibling
d=d.getElementById('E:${G}')
if(!d)return
d.parentElement.insertBefore(c.content,d.nextSibling)
})(document)
</script>`;if(x.every((L0)=>!L0.callbacks?.length)){if(Q)Q[0]=Q[0].replace(Y,y);return F}if(Q)Q[0]=Q[0].replace(Y,(L0,K0,j,y1)=>`${K0}${y}${y1}`);let B=x.map((L0)=>L0.callbacks||[]).flat();if(V===$2.Stream)F=await M5(F,$2.BeforeStream,!0,O);let i=0,w0=B.map((L0)=>(...K0)=>L0(...K0)?.then((j)=>{if(i++,Q){if(i===B.length)Q[0]=Q[0].replace(Y,(y1,L2,n)=>n);return Q[0]+=j,S0("",j.callbacks)}return S0(j+(i!==B.length?"":`<script>
((d,c,n) => {
d=d.getElementById('E:${G}')
if(!d)return
n=d.nextSibling
while(n.nodeType!=8||n.nodeValue!='E:${G}'){n=n.nextSibling}
n.remove()
d.remove()
})(document)
</script>`),j.callbacks)}).catch((j)=>U({error:j,buffer:Q})));return S0(F,w0)}).catch((x)=>U({error:x,buffer:Q}))}])}else return S0(w.join(""))};var zI=K(()=>{g9();qW();e$();c2();JI();XI();Kk[xf]=Gk});var Hk=K(()=>{F5();AY();zI();c2();oQ();t7();XI()});var T5=":-hono-global",Zf0,hY="hono-css",c9,p1,E$,i2,DY,Uk,hp0,Rk=($)=>{let f=0,W=11;while(f<$.length)W=101*W+$.charCodeAt(f++)>>>0;return"css-"+W},Xf0,zf0,wf0=($)=>{return $.replace(zf0,(f,W,J,Z,X)=>W||J||Z||X||"")},Mk=($,f)=>{let W=[],J=[],Z=$[0].match(/^\s*\/\*(.*?)\*\//)?.[1]||"",X="";for(let z=0,w=$.length;z<w;z++){X+=$[z];let G=f[z];if(typeof G==="boolean"||G===null||G===void 0)continue;if(!Array.isArray(G))G=[G];for(let Y=0,L=G.length;Y<L;Y++){let U=G[Y];if(typeof U==="boolean"||U===null||U===void 0)continue;if(typeof U==="string")if(/([\\"'\/])/.test(U))X+=U.replace(/([\\"']|(?<=<)\/)/g,"\\$1");else X+=U;else if(typeof U==="number")X+=U;else if(U[Uk])X+=U[Uk];else if(U[p1].startsWith("@keyframes "))W.push(U),X+=` ${U[p1].substring(11)} `;else{if($[z+1]?.match(/^\s*{/))W.push(U),U=`.${U[p1]}`;else{W.push(...U[i2]),J.push(...U[DY]),U=U[E$];let M=U.length;if(M>0){let q=U[M-1];if(q!==";"&&q!=="}")U+=";"}}X+=`${U||""}`}}}return[Z,wf0(X),W,J]},cW=($,f)=>{let[W,J,Z,X]=Mk($,f),z=Zf0.exec(J);if(z)J=z[1];let w=(z?T5:"")+Rk(W+J),G=(z?Z.map((Y)=>Y[p1]):[w,...X]).join(" ");return{[c9]:w,[p1]:G,[E$]:J,[i2]:Z,[DY]:X}},vY=($)=>{for(let f=0,W=$.length;f<W;f++){let J=$[f];if(typeof J==="string")$[f]={[c9]:"",[p1]:"",[E$]:"",[i2]:[],[DY]:[J]}}return $},mY=($,...f)=>{let[W,J]=Mk($,f);return{[c9]:"",[p1]:`@keyframes ${Rk(W+J)}`,[E$]:J,[i2]:[],[DY]:[]}},Gf0=0,kY=($,f)=>{if(!$)$=[`/* h-v-t ${Gf0++} */`];let W=Array.isArray($)?cW($,f):$,J=W[p1],Z=cW(["view-transition-name:",""],[J]);return W[p1]=T5+W[p1],W[E$]=W[E$].replace(/(?<=::view-transition(?:[a-z-]*)\()(?=\))/g,J),Z[p1]=Z[c9]=J,Z[i2]=[...W[i2],W],Z};var o7=K(()=>{Zf0=new RegExp(`^${T5}{(.*)}$`),c9=Symbol(),p1=Symbol(),E$=Symbol(),i2=Symbol(),DY=Symbol(),Uk=Symbol(),hp0=Symbol(),Xf0=['"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"',"'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'"].join("|"),zf0=new RegExp(["("+Xf0+")","(?:"+["^\\s+","\\/\\*.*?\\*\\/\\s*","\\/\\/.*\\n\\s*","\\s+$"].join("|")+")","\\s*;\\s*(}|$)\\s*","\\s*([{};:,])\\s*","(\\s)\\s+"].join("|"),"g")});var Lf0=($)=>{let f=[],W=0,J=0;for(let Z=0,X=$.length;Z<X;Z++){let z=$[Z];if(z==="'"||z==='"'){let w=z;Z++;for(;Z<X;Z++){if($[Z]==="\\"){Z++;continue}if($[Z]===w)break}continue}if(z==="{"){J++;continue}if(z==="}"){if(J--,J===0)f.push($.slice(W,Z+1)),W=Z+1;continue}}return f},wI=({id:$})=>{let f=void 0,W=()=>{if(!f){if(f=document.querySelector(`style#${$}`)?.sheet,f)f.addedStyles=new Set}return f?[f,f.addedStyles]:[]},J=(z,w)=>{let[G,Y]=W();if(!G||!Y){Promise.resolve().then(()=>{if(!W()[0])throw new Error("style sheet not found");J(z,w)});return}if(!Y.has(z))Y.add(z),(z.startsWith(T5)?Lf0(w):[`${z[0]==="@"?"":"."}${z}{${w}}`]).forEach((L)=>{G.insertRule(L,G.cssRules.length)})};return[{toString(){let z=this[c9];return J(z,this[E$]),this[i2].forEach(({[p1]:w,[E$]:G})=>{J(w,G)}),this[p1]}},({children:z,nonce:w})=>({tag:"style",props:{id:$,nonce:w,children:z&&(Array.isArray(z)?z:[z]).map((G)=>G[E$])}})]},Kf0=({id:$})=>{let[f,W]=wI({id:$}),J=(G)=>{return G.toString=f.toString,G},Z=(G,...Y)=>{return J(cW(G,Y))};return{css:Z,cx:(...G)=>{return G=vY(G),Z(Array(G.length).fill(""),...G)},keyframes:mY,viewTransition:(G,...Y)=>{return J(kY(G,Y))},Style:W}},e7,kp0,yp0,jp0,gp0,bp0;var qk=K(()=>{o7();o7();e7=Kf0({id:hY}),kp0=e7.css,yp0=e7.cx,jp0=e7.keyframes,gp0=e7.viewTransition,bp0=e7.Style});var Hf0=({id:$})=>{let[f,W]=wI({id:$}),J=new WeakMap,Z=new WeakMap,X=new RegExp(`(<style id="${$}"(?: nonce="[^"]*")?>.*?)(</style>)`),z=(M)=>{let q=({buffer:x,context:y})=>{let[F,B]=J.get(y),i=Object.keys(F);if(!i.length)return;let w0="";if(i.forEach((j)=>{B[j]=!0,w0+=j.startsWith(T5)?F[j]:`${j[0]==="@"?"":"."}${j}{${F[j]}}`}),J.set(y,[{},B]),x&&X.test(x[0])){x[0]=x[0].replace(X,(j,y1,L2)=>`${y1}${w0}${L2}`);return}let L0=Z.get(y),K0=`<script${L0?` nonce="${L0}"`:""}>document.querySelector('#${$}').textContent+=${JSON.stringify(w0)}</script>`;if(x){x[0]=`${K0}${x[0]}`;return}return Promise.resolve(K0)},V=({context:x})=>{if(!J.has(x))J.set(x,[{},{}]);let[y,F]=J.get(x),B=!0;if(!F[M[c9]])B=!1,y[M[c9]]=M[E$];if(M[i2].forEach(({[p1]:i,[E$]:w0})=>{if(!F[i])B=!1,y[i]=w0}),B)return;return Promise.resolve(S0("",[q]))},Q=new String(M[p1]);Object.assign(Q,M),Q.isEscaped=!0,Q.callbacks=[V];let O=Promise.resolve(Q);return Object.assign(O,M),O.toString=f.toString,O},w=(M,...q)=>{return z(cW(M,q))},G=(...M)=>{return M=vY(M),w(Array(M.length).fill(""),...M)},Y=mY,L=(M,...q)=>{return z(kY(M,q))},U=({children:M,nonce:q}={})=>S0(`<style id="${$}"${q?` nonce="${q}"`:""}>${M?M[E$]:""}</style>`,[({context:V})=>{Z.set(V,q);return}]);return U[xf]=W,{css:w,cx:G,keyframes:Y,viewTransition:L,Style:U}},$X,GI,pp0,np0,sp0,Vk;var Qk=K(()=>{g9();e$();qk();o7();o7();$X=Hf0({id:hY}),GI=$X.css,pp0=$X.cx,np0=$X.keyframes,sp0=$X.viewTransition,Vk=$X.Style});function J1($,f,W){let J;if(!f||!("children"in f))J=NY($,f,[]);else{let Z=f.children;J=Array.isArray(Z)?NY($,f,Z):NY($,f,[Z])}return J.key=W,J}var YI=K(()=>{F5();F5()});var Ik=d(($n0,Uf0)=>{Uf0.exports={"_TextareaWidget-CZG2muYB.js":{file:"assets/TextareaWidget-CZG2muYB.js",name:"TextareaWidget",imports:["src/ui/main.tsx"]},"src/ui/components/code/CodeEditor.tsx":{file:"assets/CodeEditor-C3U4N43u.js",name:"CodeEditor",src:"src/ui/components/code/CodeEditor.tsx",isDynamicEntry:!0,imports:["src/ui/main.tsx"]},"src/ui/components/form/json-schema/JsonSchemaForm.tsx":{file:"assets/JsonSchemaForm-BRm6fUTZ.js",name:"JsonSchemaForm",src:"src/ui/components/form/json-schema/JsonSchemaForm.tsx",isDynamicEntry:!0,imports:["src/ui/main.tsx","_TextareaWidget-CZG2muYB.js"]},"src/ui/main.tsx":{file:"assets/main-CLGi5LHT.js",name:"main",src:"src/ui/main.tsx",isEntry:!0,dynamicImports:["src/ui/components/form/json-schema/JsonSchemaForm.tsx","src/ui/components/code/CodeEditor.tsx","src/ui/modules/data/components/canvas/DataSchemaCanvas.tsx","src/ui/components/code/CodeEditor.tsx","src/ui/routes/test/index.tsx"],css:["assets/main-BLjkA8xT.css"]},"src/ui/modules/data/components/canvas/DataSchemaCanvas.tsx":{file:"assets/DataSchemaCanvas-kSVOR3cq.js",name:"DataSchemaCanvas",src:"src/ui/modules/data/components/canvas/DataSchemaCanvas.tsx",isDynamicEntry:!0,imports:["src/ui/main.tsx"]},"src/ui/routes/test/index.tsx":{file:"assets/index-BK2vhgNc.js",name:"index",src:"src/ui/routes/test/index.tsx",isDynamicEntry:!0,imports:["src/ui/main.tsx","_TextareaWidget-CZG2muYB.js"]}}});var LI="<!-- BKND_CONTEXT -->",KI,Rf0,Mf0;var Ok=K(()=>{V$();vZ();_();YV();g9();Hk();Qk();_W();T7();YI();KI=class KI extends If{app;_options;constructor($,f={}){super();this.app=$;this._options=f}get ctx(){return this.app.modules.ctx()}get options(){return{...this._options,basepath:this._options.basepath??"/",adminBasepath:this._options.adminBasepath??"",assetsPath:this._options.assetsPath??pf.server.assets_path,logo_return_path:this._options.logoReturnPath??"/"}}get basepath(){return this.withAdminBasePath()}withBasePath($=""){return(this.options.basepath+$).replace(/(?<!:)\/+/g,"/")}withAdminBasePath($=""){return this.withBasePath(this.options.adminBasepath+$)}getController(){let{auth:$,permission:f}=this.middlewares,W=this.create().use($({})),J=this.app.module.auth,Z=this.app.modules.configs(),X=Z.auth.enabled,z={root:"/",success:Z.auth.cookie.pathSuccess??this.withAdminBasePath("/"),loggedOut:Z.auth.cookie.pathLoggedOut??this.withAdminBasePath("/"),login:this.withAdminBasePath("/auth/login"),register:this.withAdminBasePath("/auth/register"),logout:"/api/auth/logout"},w=["/","/data/*","/auth/*","/media/*","/flows/*","/settings/*"];if(Z1())w.push("/test/*");for(let G of w)W.get(G,f(aG,{onDenied:async(Y)=>{if(!G.startsWith("/auth"))return NW(Y,"You are not authorized to access the Admin UI","error"),A.log("redirecting",z.login),Y.redirect(z.login);return}}),f(CW,{onDenied:async(Y)=>{NW(Y,"You not allowed to read the schema","warning")}}),async(Y)=>{let L={user:Y.get("auth")?.user,logout_route:z.logout,admin_basepath:this.options.adminBasepath,theme:this.options.theme,logo_return_path:this.options.logoReturnPath},U=await this.getHtml(L);if(!U)return console.warn("Couldn't generate HTML for admin UI"),Y.notFound();return await J.authenticator?.requestCookieRefresh(Y),Y.html(U)});if(X){let G=[f([aG,CW],{onGranted:async(Y)=>{if(Y.get("auth")?.user)return A.log("redirecting to success"),Y.redirect(z.success)}}),async(Y)=>{return Y.html(Y.get("html"))}];W.get(z.login,...G),W.get(z.register,...G),W.get(z.logout,async(Y)=>{return await J.authenticator?.logout(Y),Y.redirect(z.loggedOut)})}return W}async getHtml($){let f=`window.__BKND__ = JSON.parse('${JSON.stringify($)}');`;if(this.options.html){if(this.options.html.includes(LI))return this.options.html.replace(LI,"<script>"+f+"</script>");return A.warn(`Custom HTML needs to include '${LI}' to inject BKND context`),this.options.html}let W=!Z1()&&!this.options.forceDev,J=typeof this.options.forceDev==="object"&&"mainPath"in this.options.forceDev?this.options.forceDev.mainPath:"/src/ui/main.tsx",Z={js:"main.js",css:"styles.css"};if(W){let z;if(this.options.assetsPath.startsWith("http"))z=await fetch(this.options.assetsPath+".vite/manifest.json",{headers:{Accept:"application/json"}}).then((w)=>w.json());else z=await Promise.resolve().then(() => q1(Ik(),1)).then((w)=>w.default);try{Z.js=z["src/ui/main.tsx"].file,Z.css=z["src/ui/main.tsx"].css[0]}catch(w){A.warn("Couldn't find assets in manifest",w)}}let X=W?this.options.assetsPath+"favicon.ico":"/favicon.ico";return J1(gW,{children:[b7`<!DOCTYPE html>`,J1("html",{lang:"en",children:[J1("head",{children:[J1("meta",{charset:"UTF-8"},void 0,!1,void 0,this),J1("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"},void 0,!1,void 0,this),J1("link",{rel:"icon",href:X,type:"image/x-icon"},void 0,!1,void 0,this),J1("title",{children:"BKND"},void 0,!1,void 0,this),this.options.debugRerenders&&J1("script",{crossOrigin:"anonymous",src:"//unpkg.com/react-scan/dist/auto.global.js"},void 0,!1,void 0,this),W?J1(gW,{children:[J1("script",{type:"module",src:this.options.assetsPath+Z?.js},void 0,!1,void 0,this),J1("link",{rel:"stylesheet",href:this.options.assetsPath+Z?.css},void 0,!1,void 0,this)]},void 0,!0,void 0,this):J1(gW,{children:[J1("script",{type:"module",dangerouslySetInnerHTML:{__html:`import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true`}},void 0,!1,void 0,this),J1("script",{type:"module",src:"/@vite/client"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J1("style",{dangerouslySetInnerHTML:{__html:"body { margin: 0; padding: 0; }"}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J1("body",{children:[J1("div",{id:"root",children:[J1(Vk,{},void 0,!1,void 0,this),J1("div",{id:"loading",className:Rf0,children:J1("span",{className:Mf0,children:"Initializing..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J1("script",{dangerouslySetInnerHTML:{__html:f}},void 0,!1,void 0,this),!W&&J1("script",{type:"module",src:J},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}};Rf0=GI`
margin: 0;
padding: 0;
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: rgb(9,9,11);
background-color: rgb(250,250,250);
@media (prefers-color-scheme: dark) {
color: rgb(250,250,250);
background-color: rgb(30,31,34);
}
`,Mf0=GI`
opacity: 0.3;
font-size: 14px;
font-family: monospace;
`});var Z0,Ak,qf0=($)=>{return Object.entries($).map(([W,J])=>{let Z=W;if(!Ak[Z]||J===void 0)return"";switch(Ak[Z]){case Z0.STRING:return`${Z}: '${J}'`;case Z0.STRING_ARRAY:if(!Array.isArray(J))return"";return`${Z}: [${J.map((X)=>`${X}`).join(",")}]`;case Z0.JSON_STRING:return`${Z}: ${JSON.stringify(J)}`;case Z0.RAW:return`${Z}: ${J}`;default:return""}}).filter((W)=>W!=="").join(",")},Vf0=({version:$})=>{let f=`https://cdn.jsdelivr.net/npm/swagger-ui-dist${$!==void 0?`@${$}`:""}`;return{css:[`${f}/swagger-ui.css`],js:[`${f}/swagger-ui-bundle.js`]}},Qf0=($)=>{let f=Vf0({version:$?.version});if(delete $.version,$.manuallySwaggerUIHtml)return $.manuallySwaggerUIHtml(f);let W=qf0($);return`
<div>
<div id="swagger-ui"></div>
${f.css.map((J)=>b7`<link rel="stylesheet" href="${J}" />`)}
${f.js.map((J)=>b7`<script src="${J}" crossorigin="anonymous"></script>`)}
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
dom_id: '#swagger-ui',${W},
})
}
</script>
</div>
`},xk=($)=>async(f)=>{let W=$?.title??"SwaggerUI";return f.html(`
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="SwaggerUI" />
<title>${W}</title>
</head>
<body>
${Qf0($)}
</body>
</html>
`)};var _k=K(()=>{g9();Z0={STRING_ARRAY:"string_array",STRING:"string",JSON_STRING:"json_string",RAW:"raw"},Ak={configUrl:Z0.STRING,deepLinking:Z0.RAW,presets:Z0.STRING_ARRAY,plugins:Z0.STRING_ARRAY,spec:Z0.JSON_STRING,url:Z0.STRING,urls:Z0.JSON_STRING,layout:Z0.STRING,docExpansion:Z0.STRING,maxDisplayedTags:Z0.RAW,operationsSorter:Z0.RAW,requestInterceptor:Z0.RAW,responseInterceptor:Z0.RAW,persistAuthorization:Z0.RAW,defaultModelsExpandDepth:Z0.RAW,defaultModelExpandDepth:Z0.RAW,defaultModelRendering:Z0.STRING,displayRequestDuration:Z0.RAW,filter:Z0.RAW,showExtensions:Z0.RAW,showCommonExtensions:Z0.RAW,queryConfigEnabled:Z0.RAW,displayOperationId:Z0.RAW,tagsSorter:Z0.RAW,onComplete:Z0.RAW,syntaxHighlight:Z0.JSON_STRING,tryItOutEnabled:Z0.RAW,requestSnippetsEnabled:Z0.RAW,requestSnippets:Z0.JSON_STRING,oauth2RedirectUrl:Z0.STRING,showMutabledRequest:Z0.RAW,request:Z0.JSON_STRING,supportedSubmitMethods:Z0.JSON_STRING,validatorUrl:Z0.STRING,withCredentials:Z0.RAW,modelPropertyMacro:Z0.RAW,parameterMacro:Z0.RAW}});var HI;var Nk=K(()=>{_();_W();jz();_k();g7();T7();V$();HI=class HI extends If{app;constructor($){super();this.app=$}get ctx(){return this.app.modules.ctx()}registerConfigController($){let{permission:f}=this.middlewares,W=this.create();W.use(f(oG)),W.get("/raw",G0({summary:"Get the raw config",tags:["system"]}),f([B7]),async(Z)=>{return Z.json(await this.app.modules.fetch())}),W.get("/:module?",G0({summary:"Get the config for a module",tags:["system"]}),W0("param",R.object({module:R.string({enum:xm}).optional()})),W0("query",R.object({secrets:R.boolean().optional()})),async(Z)=>{let{secrets:X}=Z.req.valid("query"),{module:z}=Z.req.valid("param");X&&this.ctx.guard.throwUnlessGranted(B7,Z);let w=this.app.toJSON(X);return Z.json(z?{version:this.app.version(),module:z,config:w[z]}:w)});async function J(Z,X){try{return Z.json(await X(),{status:202})}catch(z){if(A.error("config update error",z),z instanceof G9)return Z.json({success:!1,type:"type-invalid",errors:z.errors},{status:400});if(z instanceof Error)return Z.json({success:!1,type:"error",error:z.message},{status:500});return Z.json({success:!1,type:"unknown"},{status:500})}}W.post("/set/:module",f(_5),W0("query",R.object({force:R.boolean().optional()}),{skipOpenAPI:!0}),async(Z)=>{let X=Z.req.param("module"),{force:z}=Z.req.valid("query"),w=await Z.req.json();return await J(Z,async()=>{if(z===!0){let G={...this.app.module[X].config,...w};await this.app.mutateConfig(X).set(G)}else await this.app.mutateConfig(X).patch("",w);return{success:!0,module:X,config:this.app.module[X].config}})}),W.post("/add/:module/:path",f(_5),async(Z)=>{let X=Z.req.param("module"),z=await Z.req.json(),w=Z.req.param("path");if(this.app.modules.get(X).schema().has(w))return Z.json({success:!1,path:w,error:"Path already exists"},{status:400});return await J(Z,async()=>{return await this.app.mutateConfig(X).patch(w,z),{success:!0,module:X,config:this.app.module[X].config}})}),W.patch("/patch/:module/:path",f(_5),async(Z)=>{let X=Z.req.param("module"),z=await Z.req.json(),w=Z.req.param("path");return await J(Z,async()=>{return await this.app.mutateConfig(X).patch(w,z),{success:!0,module:X,config:this.app.module[X].config}})}),W.put("/overwrite/:module/:path",f(_5),async(Z)=>{let X=Z.req.param("module"),z=await Z.req.json(),w=Z.req.param("path");return await J(Z,async()=>{return await this.app.mutateConfig(X).overwrite(w,z),{success:!0,module:X,config:this.app.module[X].config}})}),W.delete("/remove/:module/:path",f(_5),async(Z)=>{let X=Z.req.param("module"),z=Z.req.param("path");return await J(Z,async()=>{return await this.app.mutateConfig(X).remove(z),{success:!0,module:X,config:this.app.module[X].config}})}),$.route("/config",W)}getController(){let{permission:$,auth:f}=this.middlewares,W=this.create().use(f());return this.registerConfigController(W),W.get("/schema/:module?",G0({summary:"Get the schema for a module",tags:["system"]}),$(CW),W0("query",R.object({config:R.boolean(),secrets:R.boolean(),fresh:R.boolean()}).partial()),async(J)=>{let Z=J.req.param("module"),{config:X,secrets:z,fresh:w}=J.req.valid("query");X&&this.ctx.guard.throwUnlessGranted(oG,J),z&&this.ctx.guard.throwUnlessGranted(B7,J);let{version:G,...Y}=this.app.getSchema();if(w)await this.app.build({fetch:!0});if(Z)return J.json({module:Z,version:G,schema:Y[Z],config:X?this.app.module[Z].toJSON(z):void 0});return J.json({module:Z,version:G,schema:Y,config:X?this.app.toJSON(z):void 0,permissions:this.app.modules.ctx().guard.getPermissionNames()})}),W.post("/build",G0({summary:"Build the app",tags:["system"]}),W0("query",R.object({sync:R.boolean().optional(),fetch:R.boolean().optional()})),async(J)=>{let Z=J.req.valid("query");return this.ctx.guard.throwUnlessGranted(XQ,J),await this.app.build(Z),J.json({success:!0,options:Z})}),W.get("/ping",G0({summary:"Ping the server",tags:["system"]}),(J)=>J.json({pong:!0})),W.get("/info",G0({summary:"Get the server info",tags:["system"]}),(J)=>J.json({version:J.get("app")?.version(),runtime:nK(),connection:{name:this.app.em.connection.name,supports:this.app.em.connection.supported},timezone:{name:Y_(),offset:G_(),local:fz(),utc:w_()},origin:new URL(J.req.raw.url).origin,plugins:Array.from(this.app.plugins.keys()),walk:{auth:[...J.get("app").getSchema().auth.walk({data:J.get("app").toJSON(!0).auth})].filter((Z)=>Z.schema instanceof $8).map((Z)=>({...Z,schema:Z.schema.constructor.name}))}})),W.get("/openapi.json",yz(this.ctx.server,{info:{title:"bknd API",version:L_()}})),W.get("/swagger",xk({url:"/api/system/openapi.json"})),W}}});class r2{_options;fetcher;constructor($={},f){this._options=$;this.fetcher=f??fetch}getDefaultOptions(){return{}}get options(){return{host:"http://localhost",token:void 0,...this.getDefaultOptions(),...this._options}}key(){return this.options.basepath??""}getUrl($){let f=this.options.basepath??"";return this.options.host+(f+"/"+$).replace(/\/{2,}/g,"/").replace(/\/$/,"")}request($,f,W){let J=W?.method??"GET",Z=Array.isArray($)?$.join("/"):$,X=this.getUrl(Z);if(f instanceof URLSearchParams)X+="?"+f.toString();else if(typeof f==="object"){if(Object.keys(f).length>0)X+="?"+S_(f)}let z=new Headers(this.options.headers??{});for(let[Y,L]of Object.entries(W?.headers??{}))z.set(Y,L);if(!z.has("Accept"))z.set("Accept","application/json");if(this.options.token&&this.options.token_transport==="header")z.set("Authorization",`Bearer ${this.options.token}`);let w=W?.body;if(W&&"body"in W&&["POST","PATCH","PUT"].includes(J)){let Y=z.get("Content-Type")??void 0;if(!Y||Y.startsWith("application/json")||gK(w))w=JSON.stringify(W.body),z.set("Content-Type","application/json")}let G=new Request(X,{...W,method:J,body:w,headers:z});return new UI(G,{fetcher:this.fetcher,verbose:this.options.verbose})}get($,f,W){return this.request($,f,{...W,method:"GET"})}post($,f,W){return this.request($,void 0,{...W,body:f,method:"POST"})}patch($,f,W){return this.request($,void 0,{...W,body:f,method:"PATCH"})}put($,f,W){return this.request($,void 0,{...W,body:f,method:"PUT"})}delete($,f,W){return this.request($,void 0,{...W,body:f,method:"DELETE"})}}function If0($,f,W){let J=typeof W!=="undefined"?W:f,Z=["raw","body","ok","status","res","data","toJSON"];if(typeof J!=="object")J={};return new Proxy(J,{get(X,z,w){if(z==="raw"||z==="res")return $;if(z==="body")return f;if(z==="data")return W;if(z==="ok")return $.ok;if(z==="status")return $.status;if(z==="toJSON")return()=>X;return Reflect.get(X,z,w)},has(X,z){if(Z.includes(z))return!0;return Reflect.has(X,z)},ownKeys(X){return Array.from(new Set([...Reflect.ownKeys(X),...Z]))},getOwnPropertyDescriptor(X,z){if(Z.includes(z))return{configurable:!0,enumerable:!0,value:Reflect.get({raw:$,body:f,ok:$.ok,status:$.status},z)};return Reflect.getOwnPropertyDescriptor(X,z)}})}var UI;var fX=K(()=>{_();V$();UI=class UI{request;options;refineData;[Symbol.toStringTag];constructor($,f,W){this.request=$;this.options=f;this.refineData=W}get verbose(){return this.options?.verbose??!1}refine($){return new UI(this.request,this.options,$)}async execute(){Z1()&&await new Promise((X)=>setTimeout(X,200));let $=this.options?.fetcher??fetch;if(this.verbose)A.debug("[FetchPromise] Request",{method:this.request.method,url:this.request.url});let f=await $(this.request);if(this.verbose)A.debug("[FetchPromise] Response",{res:f,ok:f.ok,status:f.status});let W,J,Z=f.headers.get("Content-Type")??"";if(Z.startsWith("application/json")){if(W=await f.json(),typeof W==="object")J="data"in W?W.data:W}else if(Z.startsWith("text"))W=await f.text();else W=f.body;if(this.refineData)try{J=this.refineData(J)}catch(X){console.warn("[FetchPromise] Error in refineData",X),J=void 0}return If0(f,W,J)}then($,f){return this.execute().then($,f)}catch($){return this.then(void 0,$)}finally($){return this.then((f)=>{return $?.(),f},(f)=>{throw $?.(),f})}path(){return new URL(this.request.url).pathname}key($){let f=new URL(this.request.url);return $?.search!==!1?this.path()+f.search:this.path()}keyArray($){let f=new URL(this.request.url),W=this.path().split("/");return($?.search!==!1?[...W,f.searchParams.toString()]:W).filter(Boolean)}toString(){return this.key({search:!0})}toJSON(){return{url:this.request.url,method:this.request.method}}}});var RI;var Sk=K(()=>{fX();RI=class RI extends r2{getDefaultOptions(){return{basepath:"/api/auth",credentials:"include"}}async login($,f){let W=await this.post([$,"login"],f,{credentials:this.options.credentials});if(W.ok&&W.body.token)await this.options.onTokenUpdate?.(W.body.token);return W}async register($,f){let W=await this.post([$,"register"],f,{credentials:this.options.credentials});if(W.ok&&W.body.token)await this.options.onTokenUpdate?.(W.body.token);return W}async actionSchema($,f){return this.get([$,"actions",f,"schema.json"])}async action($,f,W){return this.post([$,"actions",f],W)}async loginWithPassword($){return this.login("password",$)}async registerWithPassword($){return this.register("password",$)}me(){return this.get(["me"])}strategies(){return this.get(["strategies"])}async logout(){await this.options.onTokenUpdate?.(void 0)}}});var Fk=K(()=>{fX()});var MI;var Bk=K(()=>{Fk();MI=class MI extends r2{getDefaultOptions(){return{basepath:"/api/data",queryLengthLimit:1000,defaultQuery:{limit:10}}}requireObjectSet($,f){if(!$||typeof $!=="object"||Object.keys($).length===0)throw new Error(f??"object is required")}readOne($,f,W={}){return this.get(["entity",$,f],W)}readOneBy($,f={}){return this.readMany($,{...f,limit:1,offset:0}).refine((W)=>W[0])}readMany($,f={}){let W=f??this.options.defaultQuery,J=this.get(["entity",$],W);if(J.request.url.length<=this.options.queryLengthLimit)return J;return this.post(["entity",$,"query"],W)}readManyByReference($,f,W,J={}){return this.get(["entity",$,f,W],J??this.options.defaultQuery)}createOne($,f){return this.post(["entity",$],f)}createMany($,f){if(!f||!Array.isArray(f)||f.length===0)throw new Error("input is required");return this.post(["entity",$],f)}updateOne($,f,W){if(!f)throw new Error("ID is required");return this.patch(["entity",$,f],W)}updateMany($,f,W){return this.requireObjectSet(f),this.patch(["entity",$],{update:W,where:f})}deleteOne($,f){if(!f)throw new Error("ID is required");return this.delete(["entity",$,f])}deleteMany($,f){return this.requireObjectSet(f),this.delete(["entity",$],f)}count($,f={}){return this.post(["entity",$,"fn","count"],f)}exists($,f={}){return this.post(["entity",$,"fn","exists"],f)}}});var qI;var Tk=K(()=>{fX();qI=class qI extends r2{getDefaultOptions(){return{basepath:"/api/media",upload_fetcher:fetch,init:{}}}listFiles(){return this.get(["files"])}getFile($){return this.get(["file",$],void 0,{headers:{Accept:"*/*"}})}async getFileStream($){let{res:f}=await this.getFile($);if(!f.ok||!f.body)throw new Error("Failed to fetch file");return f.body}async download($){let{res:f}=await this.getFile($);if(!f.ok||!f.body)throw new Error("Failed to fetch file");return await f.blob()}getFileUploadUrl($){if(!$)return this.getUrl("/upload");return this.getUrl(`/upload/${$.path}`)}getEntityUploadUrl($,f,W){return this.getUrl(`/entity/${$}/${f}/${W}`)}getUploadHeaders(){if(this.options.token_transport==="header"&&this.options.token)return new Headers({Authorization:`Bearer ${this.options.token}`});return new Headers}uploadFile($,f){let W={"Content-Type":"application/octet-stream",...f?._init?.headers||{}},J=f?.filename||"";try{if(typeof $.type!=="undefined")W["Content-Type"]=$.type;if(!f?.filename)J=$.name}catch(X){}if(J&&J.length>0&&J.includes("/"))J=J.split("/").pop()||"";let Z={...this.options.init,...f?._init||{},headers:W};if(f?.path)return this.post(f.path,$,Z);if(!J||J.length===0)throw new Error("Invalid filename");return this.post(f?.path??["upload",J],$,Z)}async upload($,f={}){if($ instanceof Request||typeof $==="string"){let J=await(f.fetcher??this.options.upload_fetcher)($);if(!J.ok||!J.body)throw new Error("Failed to fetch file");return this.uploadFile(J.body,f)}else if($ instanceof Response){if(!$.body)throw new Error("Invalid response");return this.uploadFile($.body,{...f??{},_init:{...f._init??{},headers:{...f._init?.headers??{},"Content-Type":$.headers.get("Content-Type")||"application/octet-stream"}}})}return this.uploadFile($,f)}async uploadToEntity($,f,W,J,Z){return this.upload(J,{...Z,path:["entity",$,f,W]})}deleteFile($){return this.delete(["file",$])}}});var VI;var Pk=K(()=>{fX();VI=class VI extends r2{getDefaultOptions(){return{basepath:"/api/system"}}readConfig(){return this.get("config")}readSchema($){return this.get("schema",{config:$?.config?1:0,secrets:$?.secrets?1:0,fresh:$?.fresh?1:0})}setConfig($,f,W){return this.post(["config","set",$].join("/")+`?force=${W?1:0}`,f)}addConfig($,f,W){return this.post(["config","add",$,f],W)}patchConfig($,f,W){return this.patch(["config","patch",$,f],W)}overwriteConfig($,f,W){return this.put(["config","overwrite",$,f],W)}removeConfig($,f){return this.delete(["config","remove",$,f])}}});class yY{options;token;user;verified=!1;token_transport="header";system;data;auth;media;constructor($={}){this.options=$;if(this.verified=$.verified===!0,"request"in $&&$.request)this.options.host=$.host??new URL($.request.url).origin,this.options.headers=$.headers??$.request.headers,this.extractToken();else if("token"in $&&$.token)this.token_transport="header",this.updateToken($.token,{trigger:!1});else if("user"in $&&$.user)this.token_transport="none",this.user=$.user,this.verified=$.verified!==!1;else this.extractToken();this.buildApis()}get fetcher(){return this.options.fetcher??fetch}get baseUrl(){return this.options.host??"http://localhost"}get tokenKey(){return this.options.key??"auth"}extractToken(){if(this.verified=!1,this.options.headers){let $=Of0(this.options.headers.get("cookie"),"auth");if($){this.token_transport="cookie",this.updateToken($);return}let f=this.options.headers.get("authorization")?.replace("Bearer ","");if(f){this.token_transport="header",this.updateToken(f);return}}else if(this.storage)this.storage.getItem(this.tokenKey).then(($)=>{this.token_transport="header",this.updateToken($?String($):void 0)})}get storage(){if(!this.options.storage)return null;return{getItem:async($)=>{return await this.options.storage.getItem($)},setItem:async($,f)=>{return await this.options.storage.setItem($,f)},removeItem:async($)=>{return await this.options.storage.removeItem($)}}}updateToken($,f){if(this.token=$,this.verified=!1,$)this.user=s1(NV($).payload,["iat","iss","exp"]);else this.user=void 0;if(this.storage){let W=this.tokenKey;if($)this.storage.setItem(W,$).then(()=>{this.options.onAuthStateChange?.(this.getAuthState())});else this.storage.removeItem(W).then(()=>{this.options.onAuthStateChange?.(this.getAuthState())})}else if(f?.trigger!==!1)this.options.onAuthStateChange?.(this.getAuthState());if(f?.rebuild)this.buildApis()}markAuthVerified($){return this.verified=$,this}isAuthVerified(){return this.verified}getAuthState(){return{token:this.token,user:this.user,verified:this.verified}}isAuthenticated(){let{token:$,user:f}=this.getAuthState();return!!$&&!!f}async getVerifiedAuthState(){return await this.verifyAuth(),this.getAuthState()}async verifyAuth(){if(!this.token){this.markAuthVerified(!1);return}try{let{ok:$,data:f}=await this.auth.me(),W=f?.user;if(!$||!W)throw new Error;this.user=W,this.markAuthVerified(!0)}catch($){this.markAuthVerified(!1),this.updateToken(void 0)}}getUser(){return this.user||null}getParams(){return Object.freeze({host:this.baseUrl,token:this.token,headers:this.options.headers,token_transport:this.token_transport,verbose:this.options.verbose})}buildApis(){let $=this.getParams(),f=this.options.fetcher;this.system=new VI($,f),this.data=new MI({...$,...this.options.data},f),this.auth=new RI({...$,credentials:this.options.storage?"omit":"include",...this.options.auth,onTokenUpdate:(W)=>{this.updateToken(W,{rebuild:!0}),this.options.auth?.onTokenUpdate?.(W)}},f),this.media=new qI({...$,...this.options.media},f)}}function Of0($,f){if(!$)return null;for(let W of $.split("; ")){let[J,Z]=W.split("=");if(J===f&&Z)return decodeURIComponent(Z)}return null}var Ck=K(()=>{Sk();Bk();FV();Tk();Pk();_()});function jY($={}){if(!$.connection||!F$.isConnection($.connection))throw new Error("Invalid connection");return new iW($.connection,$.initialConfig,$.options)}var dW,II,OI,AI,xI,_I,QI,iW;var NI=K(()=>{_();M2();J5();g7();T7();Ok();Nk();Ck();dW=class dW extends s0{};II=class II extends dW{static slug="app-config-updated"};OI=class OI extends dW{static slug="app-built"};AI=class AI extends dW{static slug="app-first-boot"};xI=class xI extends dW{static slug="app-request"};_I=class _I extends dW{static slug="app-before-response"};QI={AppConfigUpdatedEvent:II,AppBuiltEvent:OI,AppFirstBoot:AI,AppRequest:xI,AppBeforeResponse:_I};iW=class iW{connection;options;static Events=QI;modules;adminController;_id=crypto.randomUUID();plugins=new Map;drivers={};trigger_first_boot=!1;_building=!1;constructor($,f,W){this.connection=$;this.options=W;this.drivers=W?.drivers??{};for(let J of W?.plugins??[]){let Z=J(this);if(this.plugins.has(Z.name))throw new Error(`Plugin ${Z.name} already registered`);this.plugins.set(Z.name,Z)}this.runPlugins("onBoot"),this.modules=new mQ($,{...W?.manager??{},initial:f,onUpdated:this.onUpdated.bind(this),onFirstBoot:this.onFirstBoot.bind(this),onServerInit:this.onServerInit.bind(this),onModulesBuilt:this.onModulesBuilt.bind(this)}),this.modules.ctx().emgr.registerEvents(QI)}get emgr(){return this.modules.ctx().emgr}async runPlugins($,...f){let W=[];for(let[J,Z]of this.plugins)try{if($ in Z&&Z[$]){let X=Z[$];if(X&&typeof X==="function"){A.debug(`[Plugin:${J}] ${$}`);let z=await X(...f);W.push({name:J,result:z})}}}catch(X){A.warn(`[Plugin:${J}] error running "${$}"`,String(X))}return W}async build($){if(this._building){while(this._building)await new Promise((J)=>setTimeout(J,10));if(!$?.forceBuild)return}if(await this.runPlugins("beforeBuild"),this._building=!0,$?.sync)this.modules.ctx().flags.sync_required=!0;await this.modules.build({fetch:$?.fetch});let{guard:f,server:W}=this.modules.ctx();if(f.registerPermissions(Object.values(EW)),W.route("/api/system",new HI(this).getController()),A.log("App built"),await this.emgr.emit(new OI({app:this})),await this.runPlugins("onBuilt"),this.trigger_first_boot)this.trigger_first_boot=!1,await this.emgr.emit(new AI({app:this})),await this.options?.seed?.({...this.modules.ctx(),app:this});this._building=!1}mutateConfig($){return this.modules.mutateConfigSafe($)}get server(){return this.modules.server}get em(){return this.modules.ctx().em}get fetch(){return this.server.fetch}get module(){return new Proxy({},{get:($,f)=>{return this.modules.get(f)}})}getSchema(){return this.modules.getSchema()}version(){return this.modules.version()}isBuilt(){return this.modules.isBuilt()}registerAdminController($){return this.adminController=new KI(this,$),this.modules.server.route(this.adminController.basepath,this.adminController.getController()),this}toJSON($){return this.modules.toJSON($)}static create($){return jY($)}async createUser($){return this.module.auth.createUser($)}getApi($){let f=this.server.request;if($&&$ instanceof Request)return new yY({request:$,headers:$.headers,fetcher:f});return new yY({host:"http://localhost",...$??{},fetcher:f})}async onUpdated($,f){if(!this.emgr.enabled){A.warn("App config updated, but event manager is disabled, skip.");return}A.log("App config updated",$),await this.build({sync:!0}),await this.emgr.emit(new II({app:this,module:$,config:f}))}async onFirstBoot(){A.log("App first boot"),this.trigger_first_boot=!0,await this.runPlugins("onFirstBoot")}async onServerInit($){if($.use(async(f,W)=>{f.set("app",this),await this.emgr.emit(new xI({app:this,request:f.req.raw})),await W();try{f.res.headers.set("X-bknd-id",this._id)}catch(J){}switch(await this.emgr.emit(new _I({app:this,request:f.req.raw,response:f.res})),this.options?.asyncEventsMode??"async"){case"sync":await this.emgr.executeAsyncs();break;case"async":this.emgr.executeAsyncs();break}}),this.options?.manager?.onServerInit)this.options.manager.onServerInit($);await this.runPlugins("onServerInit",$)}async onModulesBuilt($){let f=await this.runPlugins("schema");if(f.length>0){for(let{name:W,result:J}of f)if(J)A.log(`[Plugin:${W}] schema`),$.helper.ensureSchema(J)}}}});var Ek=()=>{};async function SI($,f,W,J,Z){await W.executeQuery(Z(E0.createWithChildren([E0.createWithSql(`${$} `),p.create(J)]),f()))}function TI($){return async(f,W,J)=>{let Z=await $.all(W,J);return f||Z.length?{rows:Z}:{rows:[],...await $.run("select 1")}}}function PI($){return $===void 0||$===null?void 0:BigInt($)}var FI=class{constructor($){this.createDriver=$}createDriver;createQueryCompiler(){return new v8}createAdapter(){return new k8}createIntrospector($){return new m8($)}},Af0=class{promise;resolve;async lock(){while(this.promise)await this.promise;this.promise=new Promise(($)=>{this.resolve=$})}unlock(){let $=this.resolve;this.promise=void 0,this.resolve=void 0,$?.()}},BI=class{mutex=new Af0;conn;savepoint;releaseSavepoint;rollbackToSavepoint;init;constructor($){this.init=()=>Promise.resolve().then(() => (T2(),oF)).then(({createQueryId:f})=>{if(f)this.savepoint=SI.bind(null,"savepoint",f),this.releaseSavepoint=SI.bind(null,"release",f),this.rollbackToSavepoint=SI.bind(null,"rollback to",f)}).then($)}async acquireConnection(){return await this.mutex.lock(),this.conn}async beginTransaction($){await $.executeQuery(G1.raw("begin"))}async commitTransaction($){await $.executeQuery(G1.raw("commit"))}async rollbackTransaction($){await $.executeQuery(G1.raw("rollback"))}async releaseConnection(){this.mutex.unlock()}};var CI=K(()=>{T2()});var xf0,_f0=class{constructor($){this.db=$}async*streamQuery({parameters:$,query:f,sql:W}){if(!this.db.iterator)throw new Error("streamQuery() is not supported.");let J=this.db.iterator(Y0.is(f),W,$);for await(let Z of J)yield{rows:[Z]}}async executeQuery({parameters:$,query:f,sql:W}){return await this.db.query(Y0.is(f),W,$)}},hk;var Dk=K(()=>{CI();CI();T2();xf0=class extends BI{db;constructor($,f){super(async()=>{this.db=await $(),this.conn=new _f0(this.db),await f?.(this.conn)})}async destroy(){await this.db?.close()}},hk=class extends FI{constructor($,f){super(()=>new xf0($,f))}}});function vk($,f){let W=[];for(let{selection:J}of $.selections??[])if(V2.is(J)&&z0.is(J.column))W.push(EI(J.column.column.name),hI(f,J.column.column.name));else if(z0.is(J))W.push(EI(J.column.name),hI(f,J.column.name));else if(I1.is(J)&&p.is(J.alias))W.push(EI(J.alias.name),hI(f,J.alias.name));else throw new Error("can't extract column names from the select query node");return W}function EI($){return new H0(U1.createImmediate($))}function hI($,f){return new H0(V2.create(z0.create(f),t1.create($)))}var mk=K(()=>{u6();vf();u1();i0();lJ();_6();I2()});function kk($){return J0`(select coalesce(json_group_array(json_object(${J0.join(gk($.toOperationNode(),"agg"))})), '[]') from ${$} as agg)`}function yk($){return J0`(select json_object(${J0.join(gk($.toOperationNode(),"obj"))}) from ${$} as obj)`}function jk($){return J0`json_object(${J0.join(Object.keys($).flatMap((f)=>[J0.lit(f),$[f]]))})`}function gk($,f){try{return vk($,f)}catch{throw new Error("SQLite jsonArrayFrom and jsonObjectFrom functions can only handle explicit selections due to limitations of the json_object function. selectAll() is not allowed in the subquery.")}}var bk=K(()=>{B9();mk()});class gY{db;_excludeTables=[];_plugins;constructor($,f={}){this.db=$;this._excludeTables=f.excludeTables??[],this._plugins=f.plugins??[new j8]}getExcludedTableNames(){return[...this._excludeTables,S$,l$]}async executeWithPlugins($){let f=await $.execute(this.db);return await new TZ(this._plugins??[]).transformResultRows(f.rows)}async getMetadata($){return{tables:await this.getTables($)}}async getIndices($){return(await this.getSchemaSpec()).flatMap((W)=>W.indices).filter((W)=>!$||W.table===$)}async getTables($={withInternalKyselyTables:!1}){return(await this.getSchemaSpec()).map((W)=>({name:W.name,isView:W.isView,columns:W.columns}))}}var uk=K(()=>{T2()});var DI;var ck=K(()=>{T2();uk();DI=class DI extends gY{async getSchemas(){return[]}async getSchemaSpec(){let $=this.getExcludedTableNames().map((J)=>`'${J}'`).join(", "),f=J0`
SELECT m.name, m.type, m.sql,
(SELECT json_group_array(
json_object(
'name', p.name,
'type', p.type,
'notnull', p."notnull",
'default', p.dflt_value,
'primary_key', p.pk
)) FROM pragma_table_info(m.name) p) AS columns,
(SELECT json_group_array(
json_object(
'name', i.name,
'origin', i.origin,
'partial', i.partial,
'sql', im.sql,
'columns', (SELECT json_group_array(
json_object(
'name', ii.name,
'seqno', ii.seqno
)) FROM pragma_index_info(i.name) ii)
)) FROM pragma_index_list(m.name) i
LEFT JOIN sqlite_master im ON im.name = i.name
AND im.type = 'index'
) AS indices
FROM sqlite_master m
WHERE m.type IN ('table', 'view')
and m.name not like 'sqlite_%'
and m.name not in (${J0.raw($)})
`;return(await this.executeWithPlugins(f)).map((J)=>({name:J.name,isView:J.type==="view",columns:J.columns?.map((Z)=>{let X=J.sql?.split(/[\(\),]/)?.find((z)=>z.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,"");return{name:Z.name,dataType:Z.type,isNullable:!Z.notnull,isAutoIncrementing:Z.name===X,hasDefaultValue:Z.dflt_value!=null,comment:void 0}})??[],indices:J.indices?.map((Z)=>({name:Z.name,table:J.name,isUnique:Z.sql?.match(/unique/i)!=null,columns:Z.columns.map((X)=>({name:X.name,order:X.seqno}))}))??[]}))}}});var vI;var dk=K(()=>{T2();bk();J5();J5();ck();vI=class vI extends F${name="sqlite";constructor($){let{excludeTables:f,dialect:W,dialectArgs:J=[],additionalPlugins:Z}=$,X=[new j8,...Z??[]],z=new N2({dialect:Ow(W,DI,{excludeTables:f,plugins:X}).create(...J),plugins:X});super(z,{jsonArrayFrom:kk,jsonObjectFrom:yk,jsonBuildObject:jk,...$.customFn??{}},X)}getFieldSchema($){this.validateFieldSpecType($.type);let f=$.type;switch($.type){case"json":f="text";break}return[$.name,f,(W)=>{if($.primary){if($.type==="integer")return W.primaryKey().notNull().autoIncrement();return W.primaryKey().notNull()}if($.references){let J=W.references($.references);if($.onDelete)J=J.onDelete($.onDelete);if($.onUpdate)J=J.onUpdate($.onUpdate);return J}return W}]}toDriver($,f){if(f.type==="boolean")return $?1:0;if(typeof $==="undefined")return null;return $}fromDriver($,f){if(f.type==="boolean"&&typeof $==="number")return $===1;return $}}});function mI($,f,W,J){return new ik(f,()=>W(rk),{name:$,...J})}var ik,rk;var lk=K(()=>{Dk();dk();ik=class ik extends vI{db;executor;name="generic-sqlite";#$;constructor($,f,W){super({dialect:hk,dialectArgs:[f,W?.onCreateConnection],additionalPlugins:W?.additionalPlugins,excludeTables:W?.excludeTables});this.db=$;this.executor=f;if(this.client=$,W?.name)this.name=W.name;if(W?.supports){for(let[J,Z]of Object.entries(W.supports))if(Z!==void 0)this.supported[J]=Z}}async getExecutor(){if(!this.#$)this.#$=await this.executor();return this.#$}async executeQueries(...$){let f=await this.getExecutor();if(!f.batch)return super.executeQueries(...$);let J=this.getCompiled(...$).map((X)=>{return{sql:X.sql,parameters:X.parameters}}),Z=await f.batch(J);return this.withTransformedRows(Z)}};rk={parseBigInt:PI,buildQueryFn:TI}});class kI{em;_options;constructor($,f={}){this.em=$;this._options=f}get options(){return{...this._options,indentWidth:2,indentChar:" ",entityCommentMultiline:!0,fieldCommentMultiline:!1}}toTypes(){return this.em.entities.map(($)=>$.toTypes())}getTab($=1){return this.options.indentChar.repeat(this.options.indentWidth).repeat($)}collectImports($,f={}){for(let[,W]of Object.entries($.fields))for(let J of W.import??[]){let{name:Z,package:X}=J;if(!f[X])f[X]=[];if(!f[X].includes(Z))f[X].push(Z)}return f}typeName($){return R_($)}fieldTypesToString($,f){let W="",J=this.options.fieldCommentMultiline,Z=f?.indent??1;for(let[X,z]of Object.entries($.fields)){if(f?.ignore_fields?.includes(X))continue;let w="";w+=this.commentString(z.comment,Z,J),w+=`${this.getTab(Z)}${X}${z.required?"":"?"}: `,w+=z.type+";",w+=`
`,W+=w}return W}relationToFieldType($,f){let W=$.other(f),J=$.isListableFor(f),X=this.typeName(W.entity.name);if(W.entity.type==="system")X=`DB["${W.entity.name}"]`;return{fields:{[W.reference]:{required:!1,type:`${X}${J?"[]":""}`}}}}importsToString($){let f=[];for(let[W,J]of Object.entries($))f.push(`import type { ${J.join(", ")} } from "${W}";`);return f}commentString($,f=0,W=!0){if(!$)return"";let J=this.getTab(f);if(!W)return`${J}// ${$}
`;return`${J}/**
${J} * ${$}
${J} */
`}entityToTypeString($,f){let W=$.toTypes(),J=this.typeName(W.name),Z=f?.indent??1,X=Math.max(0,Z-1),z=this.commentString(W.comment,X,this.options.entityCommentMultiline);z+=`${f?.export?"export ":""}interface ${J} {
`,z+=this.fieldTypesToString(W,f);let G=this.em.relations.relationsOf($).map((Y)=>this.relationToFieldType(Y,$));for(let Y of G)z+=this.fieldTypesToString(Y,{indent:Z});return z+=`${this.getTab(X)}}`,z}toString(){let $=[],f={},W={bknd:["DB"],kysely:["Insertable","Selectable","Updateable","Generated"]},J=`declare global {
`;J+=`${this.getTab(1)}type BkndEntity<T extends keyof DB> = Selectable<DB[T]>;
`,J+=`${this.getTab(1)}type BkndEntityCreate<T extends keyof DB> = Insertable<DB[T]>;
`,J+=`${this.getTab(1)}type BkndEntityUpdate<T extends keyof DB> = Updateable<DB[T]>;
`,J+="}",$.push(J);let Z=this.em.entities.filter((G)=>G.type==="system");for(let G of this.em.entities){if(Z.includes(G))continue;let Y=G.toTypes();if(!Y)continue;this.collectImports(Y,W),f[Y.name]=this.typeName(Y.name);let L=this.entityToTypeString(G,{export:!0});$.push(L)}let X=`interface Database {
`;for(let[G,Y]of Object.entries(f))X+=`${this.getTab(1)}${G}: ${Y};
`;X+="}",$.push(X);let z=`declare module "bknd" {
`;for(let G of Z){let Y=Object.keys(Nf0[G.name]);if(G.fields.filter((U)=>!Y.includes(U.name)&&U.type!=="primary").map((U)=>U.name).length===0)continue;z+=`${this.getTab(1)}${this.entityToTypeString(G,{ignore_fields:["id",...Y],indent:2})}
`}return z+=`${this.getTab(1)}interface DB extends Database {}
}`,$.push(z),[this.importsToString(W).join(`
`),$.join(`
`)].join(`
`)}}var Nf0;var pk=K(()=>{_();JQ();EQ();Nf0={users:tG,media:MY}});var nk=K(()=>{J5()});var bs0,cs0;var P5=K(()=>{NI();wV();V$();vZ();Ek();bG();LY();HY();TJ();UY();PZ();xW();lk();p$();B$();nk();try{let{emitWarning:$}=process;process.emitWarning=(f,...W)=>{if(f.includes("SQLite is an experimental feature"))return;return $(f,...W)}}catch($){}bs0={...DW},cs0={...T9,...g8}});var tk=d((Zt0,Pf0)=>{Pf0.exports={name:"dotenv",version:"16.4.7",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var $y=d((Xt0,d9)=>{var jI=u("fs"),gI=u("path"),Cf0=u("os"),Ef0=u("crypto"),hf0=tk(),bI=hf0.version,Df0=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function vf0($){let f={},W=$.toString();W=W.replace(/\r\n?/mg,`
`);let J;while((J=Df0.exec(W))!=null){let Z=J[1],X=J[2]||"";X=X.trim();let z=X[0];if(X=X.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),z==='"')X=X.replace(/\\n/g,`
`),X=X.replace(/\\r/g,"\r");f[Z]=X}return f}function mf0($){let f=ek($),W=S1.configDotenv({path:f});if(!W.parsed){let z=new Error(`MISSING_DATA: Cannot parse ${f} for an unknown reason`);throw z.code="MISSING_DATA",z}let J=ok($).split(","),Z=J.length,X;for(let z=0;z<Z;z++)try{let w=J[z].trim(),G=jf0(W,w);X=S1.decrypt(G.ciphertext,G.key);break}catch(w){if(z+1>=Z)throw w}return S1.parse(X)}function kf0($){console.log(`[dotenv@${bI}][INFO] ${$}`)}function yf0($){console.log(`[dotenv@${bI}][WARN] ${$}`)}function uY($){console.log(`[dotenv@${bI}][DEBUG] ${$}`)}function ok($){if($&&$.DOTENV_KEY&&$.DOTENV_KEY.length>0)return $.DOTENV_KEY;if(process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0)return process.env.DOTENV_KEY;return""}function jf0($,f){let W;try{W=new URL(f)}catch(w){if(w.code==="ERR_INVALID_URL"){let G=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw G.code="INVALID_DOTENV_KEY",G}throw w}let J=W.password;if(!J){let w=new Error("INVALID_DOTENV_KEY: Missing key part");throw w.code="INVALID_DOTENV_KEY",w}let Z=W.searchParams.get("environment");if(!Z){let w=new Error("INVALID_DOTENV_KEY: Missing environment part");throw w.code="INVALID_DOTENV_KEY",w}let X=`DOTENV_VAULT_${Z.toUpperCase()}`,z=$.parsed[X];if(!z){let w=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${X} in your .env.vault file.`);throw w.code="NOT_FOUND_DOTENV_ENVIRONMENT",w}return{ciphertext:z,key:J}}function ek($){let f=null;if($&&$.path&&$.path.length>0)if(Array.isArray($.path)){for(let W of $.path)if(jI.existsSync(W))f=W.endsWith(".vault")?W:`${W}.vault`}else f=$.path.endsWith(".vault")?$.path:`${$.path}.vault`;else f=gI.resolve(process.cwd(),".env.vault");if(jI.existsSync(f))return f;return null}function ak($){return $[0]==="~"?gI.join(Cf0.homedir(),$.slice(1)):$}function gf0($){kf0("Loading env from encrypted .env.vault");let f=S1._parseVault($),W=process.env;if($&&$.processEnv!=null)W=$.processEnv;return S1.populate(W,f,$),{parsed:f}}function bf0($){let f=gI.resolve(process.cwd(),".env"),W="utf8",J=Boolean($&&$.debug);if($&&$.encoding)W=$.encoding;else if(J)uY("No encoding is specified. UTF-8 is used by default");let Z=[f];if($&&$.path)if(!Array.isArray($.path))Z=[ak($.path)];else{Z=[];for(let G of $.path)Z.push(ak(G))}let X,z={};for(let G of Z)try{let Y=S1.parse(jI.readFileSync(G,{encoding:W}));S1.populate(z,Y,$)}catch(Y){if(J)uY(`Failed to load ${G} ${Y.message}`);X=Y}let w=process.env;if($&&$.processEnv!=null)w=$.processEnv;if(S1.populate(w,z,$),X)return{parsed:z,error:X};else return{parsed:z}}function uf0($){if(ok($).length===0)return S1.configDotenv($);let f=ek($);if(!f)return yf0(`You set DOTENV_KEY but you are missing a .env.vault file at ${f}. Did you forget to build it?`),S1.configDotenv($);return S1._configVault($)}function cf0($,f){let W=Buffer.from(f.slice(-64),"hex"),J=Buffer.from($,"base64"),Z=J.subarray(0,12),X=J.subarray(-16);J=J.subarray(12,-16);try{let z=Ef0.createDecipheriv("aes-256-gcm",W,Z);return z.setAuthTag(X),`${z.update(J)}${z.final()}`}catch(z){let w=z instanceof RangeError,G=z.message==="Invalid key length",Y=z.message==="Unsupported state or unable to authenticate data";if(w||G){let L=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw L.code="INVALID_DOTENV_KEY",L}else if(Y){let L=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw L.code="DECRYPTION_FAILED",L}else throw z}}function df0($,f,W={}){let J=Boolean(W&&W.debug),Z=Boolean(W&&W.override);if(typeof f!=="object"){let X=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw X.code="OBJECT_REQUIRED",X}for(let X of Object.keys(f))if(Object.prototype.hasOwnProperty.call($,X)){if(Z===!0)$[X]=f[X];if(J)if(Z===!0)uY(`"${X}" is already defined and WAS overwritten`);else uY(`"${X}" is already defined and was NOT overwritten`)}else $[X]=f[X]}var S1={configDotenv:bf0,_configVault:gf0,_parseVault:mf0,config:uf0,decrypt:cf0,parse:vf0,populate:df0};Xt0.configDotenv=S1.configDotenv;Xt0._configVault=S1._configVault;Xt0._parseVault=S1._parseVault;Xt0.config=S1.config;Xt0.decrypt=S1.decrypt;Xt0.parse=S1.parse;Xt0.populate=S1.populate;d9.exports=S1});var dY=($)=>{let f=$.filename,W=$.defaultDocument||"index.html";if(f.endsWith("/"))f=f.concat(W);else if(!f.match(/\.[a-zA-Z0-9_-]+$/))f=f.concat("/"+W);return nW({root:$.root,filename:f})},nW=($)=>{let f=$.root||"",W=$.filename;if(/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(W))return;W=W.replace(/^\.?[\/\\]/,""),W=W.replace(/\\/,"/"),f=f.replace(/\/$/,"");let J=f?f+"/"+W:W;if(J=J.replace(/^\.?\//,""),f[0]!=="/"&&J[0]==="/")return;return J};var WO=()=>{};var XX=($,f=JO)=>{let W=/\.([a-zA-Z0-9]+?)$/,J=$.match(W);if(!J)return;let Z=f[J[1]];if(Z&&Z.startsWith("text"))Z+="; charset=utf-8";return Z},My=($)=>{for(let f in JO)if(JO[f]===$)return f},T20,JO;var iY=K(()=>{T20={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},JO=T20});var Iy={};V1(Iy,{serveStatic:()=>h20});import{createReadStream as qy,lstatSync as P20}from"fs";var C20,XO,E20,Vy=($)=>{return new ReadableStream({start(W){$.on("data",(J)=>{W.enqueue(J)}),$.on("end",()=>{W.close()})},cancel(){$.destroy()}})},Qy=($)=>{return`./${$}`},ZO=($)=>{let f;try{f=P20($)}catch{}return f},h20=($={root:""})=>{return async(f,W)=>{if(f.finalized)return W();let J;try{J=$.path??decodeURIComponent(f.req.path)}catch{return await $.onNotFound?.(f.req.path,f),W()}let Z=nW({filename:$.rewriteRequestPath?$.rewriteRequestPath(J):J,root:$.root});if(Z)Z=Qy(Z);else return W();let X=ZO(Z);if(X&&X.isDirectory()){if(Z=dY({filename:$.rewriteRequestPath?$.rewriteRequestPath(J):J,root:$.root,defaultDocument:$.index??"index.html"}),Z)Z=Qy(Z);else return W();X=ZO(Z)}if(!X)return await $.onNotFound?.(Z,f),W();await $.onFound?.(Z,f);let z=XX(Z);if(f.header("Content-Type",z||"application/octet-stream"),$.precompressed&&(!z||C20.test(z))){let V=new Set(f.req.header("Accept-Encoding")?.split(",").map((Q)=>Q.trim()));for(let Q of E20){if(!V.has(Q))continue;let O=ZO(Z+XO[Q]);if(O){f.header("Content-Encoding",Q),f.header("Vary","Accept-Encoding",{append:!0}),X=O,Z=Z+XO[Q];break}}}let w=X.size;if(f.req.method=="HEAD"||f.req.method=="OPTIONS")return f.header("Content-Length",w.toString()),f.status(200),f.body(null);let G=f.req.header("range")||"";if(!G)return f.header("Content-Length",w.toString()),f.body(Vy(qy(Z)),200);f.header("Accept-Ranges","bytes"),f.header("Date",X.birthtime.toUTCString());let Y=G.replace(/bytes=/,"").split("-",2),L=Y[0]?parseInt(Y[0],10):0,U=Y[1]?parseInt(Y[1],10):X.size-1;if(w<U-L+1)U=w-1;let M=U-L+1,q=qy(Z,{start:L,end:U});return f.header("Content-Length",M.toString()),f.header("Content-Range",`bytes ${L}-${U}/${X.size}`),f.body(Vy(q),206)}};var Oy=K(()=>{WO();iY();C20=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,XO={br:".br",zstd:".zst",gzip:".gz"},E20=Object.keys(XO)});var Ay;var xy=K(()=>{Ay=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i});var _y,D20,v20="index.html",m20=($)=>$,Ny=($)=>{let f=!1,W;if($.root)if($.root.startsWith("/"))f=!0,W=new URL(`file://${$.root}`).pathname;else W=$.root;return async(J,Z)=>{if(J.finalized){await Z();return}let X=$.path??decodeURI(J.req.path);if(X=$.rewriteRequestPath?$.rewriteRequestPath(X):X,!X.endsWith("/")&&$.isDir){let L=nW({filename:X,root:W});if(L&&await $.isDir(L))X+="/"}let z=dY({filename:X,root:W,defaultDocument:v20});if(!z)return await Z();if(f)z="/"+z;let w=$.getContent,G=$.pathResolve??m20;z=G(z);let Y=await w(z,J);if(!Y){let L=nW({filename:X,root:W});if(!L)return await Z();if(L=G(L),L!==z){if(Y=await w(L,J),Y)z=L}}if(Y instanceof Response)return J.newResponse(Y.body,Y);if(Y){let L=$.mimes&&XX(z,$.mimes)||XX(z);if(J.header("Content-Type",L||"application/octet-stream"),$.precompressed&&(!L||Ay.test(L))){let U=new Set(J.req.header("Accept-Encoding")?.split(",").map((M)=>M.trim()));for(let M of D20){if(!U.has(M))continue;let q=await w(z+_y[M],J);if(q){Y=q,J.header("Content-Encoding",M),J.header("Vary","Accept-Encoding",{append:!0});break}}}return await $.onFound?.(z,J),J.body(Y)}await $.onNotFound?.(z,J),await Z();return}};var Sy=K(()=>{xy();WO();iY();_y={br:".br",zstd:".zst",gzip:".gz"},D20=Object.keys(_y)});import{stat as k20}from"node:fs/promises";var Fy=($)=>{return async function f(W,J){return Ny({...$,getContent:async(w)=>{w=w.startsWith("/")?w:`./${w}`;let G=Bun.file(w);return await G.exists()?G:null},pathResolve:(w)=>{return w.startsWith("/")?w:`./${w}`},isDir:async(w)=>{let G;try{G=(await k20(w)).isDirectory()}catch{}return G}})(W,J)}};var By=K(()=>{Sy()});var Ty=($,f)=>{for(let[W,J]of Object.entries(f)){let Z=new RegExp("/:"+W+"(?:{[^/]+})?\\??");$=$.replace(Z,J?`/${J}`:"")}return $};var Py=()=>{};var y20=1024,Cy=({concurrency:$,interval:f}={})=>{if($||=y20,$===1/0)return{run:async(Z)=>Z()};let W=new Set,J=async(Z,X,z)=>{if(W.size>=$)return X||=new Promise((Y)=>z=Y),setTimeout(()=>J(Z,X,z)),X;let w={};W.add(w);let G=await Z();if(f)setTimeout(()=>W.delete(w),f);else W.delete(w);if(z)return z(G),X;else return G};return{run:J}};var Ey=()=>{};var hy="HONO_SSG_CONTEXT",rY="x-hono-disable-ssg",qa0;var zO=K(()=>{qa0=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[rY]:"true"}})}catch{return null}})()});var zX=($)=>$.length>1,wX=($)=>{return $[Y7]?wX($[Y7]):$};var wO=K(()=>{rq()});var Dy=($)=>{return $.split(/[\/\\]/).slice(0,-1).join("/")},j20=($)=>{return $.replace(/(\\)/g,"/").replace(/\/$/g,"")},g20=($,f)=>{if($.length===0||f)$.push("..");else $.pop()},b20=($,f)=>{if($=$.replace(/^\.(?!.)/,""),$!=="")f.push($)},u20=($,f)=>{let W=!1;for(let J of $)if(J==="..")g20(f,W),W=!0;else b20(J,f),W=!1},GX=(...$)=>{$=$.map(j20);let f=[];return u20($.join("/").split("/"),f),($[0][0]==="/"?"/":"")+f.join("/")},vy=($)=>{return $.routes.reduce((f,{method:W,handler:J,path:Z})=>{let X=wX(J);if(["GET",e0].includes(W)&&!zX(X))f.push({path:Z});return f},[])};var my=K(()=>{VW();wO()});var c20=2,d20="text/plain",i20="./static",r20=($,f,W,J)=>{let Z=n20(W,J);if($.endsWith(`.${Z}`))return GX(f,$);if($==="/")return GX(f,`index.${Z}`);if($.endsWith("/"))return GX(f,$,`index.${Z}`);return GX(f,`${$}.${Z}`)},l20=async($)=>{let f=$.headers.get("Content-Type");try{if(f?.includes("text")||f?.includes("json"))return await $.text();else return await $.arrayBuffer()}catch(W){throw new Error(`Error processing response: ${W instanceof Error?W.message:"Unknown error"}`)}},p20,n20=($,f)=>{let W=f||p20;if($ in W)return W[$];return My($)||"html"},s20=($)=>{if(!Array.isArray($))return $;return async(f)=>{let W=f;for(let J of $){let Z=await J(W);if(Z===!1)return!1;if(Z instanceof Request)W=Z}return W}},t20=($)=>{if(!Array.isArray($))return $;return async(f)=>{let W=f;for(let J of $){let Z=await J(W);if(Z===!1)return!1;if(Z instanceof Response)W=Z}return W}},a20=($,f,W)=>{if(!Array.isArray($))return $;return async(J)=>{for(let Z of $)await Z(J,f,W)}},o20=function*($,f,W,J){let X=Cy({concurrency:J});for(let z of vy($)){let w=new URL(z.path,"http://localhost").toString(),G=new Request(w);yield new Promise(async(Y,L)=>{try{if(f){let M=await f(G);if(!M){Y(void 0);return}G=M}if(await X.run(()=>$.fetch(G)),!G.ssgParams){if(e20(z.path)){Y(void 0);return}G.ssgParams=[{}]}let U={method:G.method,headers:G.headers};Y(function*(){for(let M of G.ssgParams)yield new Promise(async(q,V)=>{try{let Q=Ty(z.path,M),O=await X.run(()=>$.request(Q,U,{[hy]:!0}));if(O.headers.get(rY)){q(void 0);return}if(W){let F=await W(O);if(!F){q(void 0);return}O=F}let x=O.headers.get("Content-Type")?.split(";")[0]||d20,y=await l20(O);q({routePath:Q,mimeType:x,content:y})}catch(Q){V(Q)}})}())}catch(U){L(U)}})}},e20=($)=>{return $.split("/").some((f)=>f.startsWith(":")||f.includes("*"))},ky,$90=async($,f,W,J)=>{let Z=await $;if(!Z)return;let{routePath:X,content:z,mimeType:w}=Z,G=r20(X,W,w,J),Y=Dy(G);if(!ky.has(Y))await f.mkdir(Y,{recursive:!0}),ky.add(Y);if(typeof z==="string")await f.writeFile(G,z);else if(z instanceof ArrayBuffer)await f.writeFile(G,new Uint8Array(z));return G},yy=async($,f,W)=>{let J,Z=[],X=[],z=W?.plugins||[],w=[],G=[],Y=[];if(W?.beforeRequestHook)w.push(...Array.isArray(W.beforeRequestHook)?W.beforeRequestHook:[W.beforeRequestHook]);if(W?.afterResponseHook)G.push(...Array.isArray(W.afterResponseHook)?W.afterResponseHook:[W.afterResponseHook]);if(W?.afterGenerateHook)Y.push(...Array.isArray(W.afterGenerateHook)?W.afterGenerateHook:[W.afterGenerateHook]);for(let L of z){if(L.beforeRequestHook)w.push(...Array.isArray(L.beforeRequestHook)?L.beforeRequestHook:[L.beforeRequestHook]);if(L.afterResponseHook)G.push(...Array.isArray(L.afterResponseHook)?L.afterResponseHook:[L.afterResponseHook]);if(L.afterGenerateHook)Y.push(...Array.isArray(L.afterGenerateHook)?L.afterGenerateHook:[L.afterGenerateHook])}try{let L=W?.dir??i20,U=W?.concurrency??c20,M=s20(w.length>0?w:[(O)=>O]),q=t20(G.length>0?G:[(O)=>O]),V=o20($,M,q,U);for(let O of V)Z.push(O.then((x)=>{if(!x)return;for(let y of x)X.push($90(y,f,L,W?.extensionMap).catch((F)=>F))}));await Promise.all(Z);let Q=[];for(let O of X){let x=await O;if(typeof x==="string")Q.push(x);else if(x)throw x}J={success:!0,files:Q}}catch(L){let U=L instanceof Error?L:new Error(String(L));J={success:!1,files:[],error:U}}if(Y.length>0)await a20(Y,f,W)(J,f,W);return J};var jy=K(()=>{Py();Ey();iY();zO();my();p20={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},ky=new Set});var gy=K(()=>{jy();zO()});var f90,GO,by=async($,f)=>{return yy($,GO,f)};var uy=K(()=>{gy();({write:f90}=Bun),GO={writeFile:async($,f)=>{await f90($,f)},mkdir:async()=>{}}});var cy=class{#$;constructor($){this.#$=$,this.raw=$.raw,this.url=$.url?new URL($.url):null,this.protocol=$.protocol??null}send($,f){this.#$.send($,f??{})}raw;binaryType="arraybuffer";get readyState(){return this.#$.readyState}url;protocol;close($,f){this.#$.close($,f)}},dy=($)=>{return new MessageEvent("message",{data:$})},iy=($)=>{return(...f)=>{if(typeof f[0]==="function"){let[W,J]=f;return async function Z(X,z){let w=await W(X),G=await $(X,w,J);if(G)return G;await z()}}else{let[W,J,Z]=f;return(async()=>{let X=await $(W,J,Z);if(!X)throw new Error("Failed to upgrade WebSocket");return X})()}}};var ry=()=>{};var lY=($)=>("server"in $.env)?$.env.server:$.env;var YO=()=>{};var LO=($)=>{return new cy({send:(f,W)=>{$.send(f,W?.compress)},raw:$,readyState:$.readyState,url:$.data.url,protocol:$.data.protocol,close(f,W){$.close(f,W)}})},ly=()=>{return{upgradeWebSocket:iy((W,J)=>{let Z=lY(W);if(!Z)throw new TypeError("env has to include the 2nd argument of fetch.");if(Z.upgrade(W.req.raw,{data:{events:J,url:new URL(W.req.url),protocol:W.req.url}}))return new Response(null);return}),websocket:{open(W){let J=W.data.events;if(J.onOpen)J.onOpen(new Event("open"),LO(W))},close(W,J,Z){let X=W.data.events;if(X.onClose)X.onClose(new CloseEvent("close",{code:J,reason:Z}),LO(W))},message(W,J){let Z=W.data.events;if(Z.onMessage){let X=typeof J==="string"?J:J.buffer;Z.onMessage(dy(X),LO(W))}}}}};var py=K(()=>{ry();YO()});var ny=($)=>{let f=lY($);if(!f)throw new TypeError("env has to include the 2nd argument of fetch.");if(typeof f.requestIP!=="function")throw new TypeError("server.requestIP is not a function.");let W=f.requestIP($.req.raw);return{remote:{address:W.address,addressType:W.family==="IPv6"||W.family==="IPv4"?W.family:void 0,port:W.port}}};var sy=K(()=>{YO()});var ty={};V1(ty,{toSSG:()=>by,serveStatic:()=>Fy,getConnInfo:()=>ny,createBunWebSocket:()=>ly,bunFileSystemModule:()=>GO});var ay=K(()=>{By();uy();py();sy()});var Xj={};V1(Xj,{serve:()=>V90,getRequestListener:()=>Jj,createAdaptorServer:()=>Zj,RequestError:()=>s4});import{createServer as W90}from"http";import{Http2ServerRequest as KO}from"http2";import{Readable as J90}from"stream";import K90 from"crypto";function ey($,f){if($.locked)throw new TypeError("ReadableStream is locked.");else if(f.destroyed){$.cancel();return}let W=$.getReader();return f.on("close",J),f.on("error",J),W.read().then(X,J),W.closed.finally(()=>{f.off("close",J),f.off("error",J)});function J(z){if(W.cancel(z).catch(()=>{}),z)f.destroy(z)}function Z(){W.read().then(X,J)}function X({done:z,value:w}){try{if(z)f.end();else if(!f.write(w))f.once("drain",Z);else return W.read().then(X,J)}catch(G){J(G)}}}var s4,Z90=($)=>{if($ instanceof s4)return $;return new s4($.message,{cause:$})},X90,YX,z90=($,f,W,J)=>{let Z=[],X=W.rawHeaders;for(let w=0;w<X.length;w+=2){let{[w]:G,[w+1]:Y}=X;if(G.charCodeAt(0)!==58)Z.push([G,Y])}let z={method:$,headers:Z,signal:J.signal};if($==="TRACE"){z.method="GET";let w=new YX(f,z);return Object.defineProperty(w,"method",{get(){return"TRACE"}}),w}if(!($==="GET"||$==="HEAD"))if("rawBody"in W&&W.rawBody instanceof Buffer)z.body=new ReadableStream({start(w){w.enqueue(W.rawBody),w.close()}});else z.body=J90.toWeb(W);return new YX(f,z)},aW,w90,HO,pY,tW,G90,nY,Y90=($,f)=>{let W=Object.create(nY);W[HO]=$;let J=$.url||"";if(J[0]!=="/"&&(J.startsWith("http://")||J.startsWith("https://"))){if($ instanceof KO)throw new s4("Absolute URL for :path is not allowed in HTTP/2");try{let w=new URL(J);W[pY]=w.href}catch(w){throw new s4("Invalid absolute URL",{cause:w})}return W}let Z=($ instanceof KO?$.authority:$.headers.host)||f;if(!Z)throw new s4("Missing host header");let X;if($ instanceof KO){if(X=$.scheme,!(X==="http"||X==="https"))throw new s4("Unsupported scheme")}else X=$.socket&&$.socket.encrypted?"https":"http";let z=new URL(`${X}://${Z}${J}`);if(z.hostname.length!==Z.length&&z.hostname!==Z.replace(/:\d+$/,""))throw new s4("Invalid host header");return W[pY]=z.href,W},oy,sW,h5,RO,LX,$j=($)=>{let f={};if(!($ instanceof Headers))$=new Headers($??void 0);let W=[];for(let[J,Z]of $)if(J==="set-cookie")W.push(Z);else f[J]=Z;if(W.length>0)f["set-cookie"]=W;return f["content-type"]??="text/plain; charset=UTF-8",f},L90="x-hono-already-sent",H90,U90,R90,M90=()=>new Response(null,{status:400}),fj=($)=>new Response(null,{status:$ instanceof Error&&($.name==="TimeoutError"||$.constructor.name==="TimeoutError")?504:500}),UO=($,f)=>{let W=$ instanceof Error?$:new Error("unknown error",{cause:$});if(W.code==="ERR_STREAM_PREMATURE_CLOSE")console.info("The user aborted a request.");else{if(console.error($),!f.headersSent)f.writeHead(500,{"Content-Type":"text/plain"});f.end(`Error: ${W.message}`),f.destroy(W)}},Wj=async($,f)=>{let[W,J,Z]=$[h5];if(Z instanceof Headers)Z=$j(Z);if(typeof J==="string")Z["Content-Length"]=Buffer.byteLength(J);else if(J instanceof Uint8Array)Z["Content-Length"]=J.byteLength;else if(J instanceof Blob)Z["Content-Length"]=J.size;if(f.writeHead(W,Z),typeof J==="string"||J instanceof Uint8Array)f.end(J);else if(J instanceof Blob)f.end(new Uint8Array(await J.arrayBuffer()));else return ey(J,f)?.catch((X)=>UO(X,f))},q90=async($,f,W={})=>{if($ instanceof Promise)if(W.errorHandler)try{$=await $}catch(Z){let X=await W.errorHandler(Z);if(!X)return;$=X}else $=await $.catch(fj);if(h5 in $)return Wj($,f);let J=$j($.headers);if($.body){let{"transfer-encoding":Z,"content-encoding":X,"content-length":z,"x-accel-buffering":w,"content-type":G}=J;if(Z||X||z||w&&U90.test(w)||!R90.test(G))f.writeHead($.status,J),await ey($.body,f);else{let Y=await $.arrayBuffer();J["content-length"]=Y.byteLength,f.writeHead($.status,J),f.end(new Uint8Array(Y))}}else if(J[L90]);else f.writeHead($.status,J),f.end()},Jj=($,f={})=>{if(f.overrideGlobalObjects!==!1&&global.Request!==YX)Object.defineProperty(global,"Request",{value:YX}),Object.defineProperty(global,"Response",{value:LX});return async(W,J)=>{let Z,X;try{if(X=Y90(W,f.hostname),J.on("close",()=>{if(!X[tW])return;if(W.errored)X[tW].abort(W.errored.toString());else if(!J.writableFinished)X[tW].abort("Client connection prematurely closed.")}),Z=$(X,{incoming:W,outgoing:J}),h5 in Z)return Wj(Z,J)}catch(z){if(!Z)if(f.errorHandler){if(Z=await f.errorHandler(X?z:Z90(z)),!Z)return}else if(!X)Z=M90();else Z=fj(z);else return UO(z,J)}try{return await q90(Z,J,f)}catch(z){return UO(z,J)}}},Zj=($)=>{let f=$.fetch,W=Jj(f,{hostname:$.hostname,overrideGlobalObjects:$.overrideGlobalObjects});return($.createServer||W90)($.serverOptions||{},W)},V90=($,f)=>{let W=Zj($);return W.listen($?.port??3000,$.hostname,()=>{let J=W.address();f&&f(J)}),W};var zj=K(()=>{s4=class extends Error{constructor($,f){super($,f);this.name="RequestError"}},X90=global.Request,YX=class extends X90{constructor($,f){if(typeof $==="object"&&aW in $)$=$[aW]();if(typeof f?.body?.getReader!=="undefined")f.duplex??="half";super($,f)}},aW=Symbol("getRequestCache"),w90=Symbol("requestCache"),HO=Symbol("incomingKey"),pY=Symbol("urlKey"),tW=Symbol("abortControllerKey"),G90=Symbol("getAbortController"),nY={get method(){return this[HO].method||"GET"},get url(){return this[pY]},[G90](){return this[aW](),this[tW]},[aW](){return this[tW]||=new AbortController,this[w90]||=z90(this.method,this[pY],this[HO],this[tW])}};["body","bodyUsed","cache","credentials","destination","headers","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(($)=>{Object.defineProperty(nY,$,{get(){return this[aW]()[$]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(($)=>{Object.defineProperty(nY,$,{value:function(){return this[aW]()[$]()}})});Object.setPrototypeOf(nY,YX.prototype);oy=Symbol("responseCache"),sW=Symbol("getResponseCache"),h5=Symbol("cache"),RO=global.Response,LX=class ${#$;#f;[sW](){return delete this[h5],this[oy]||=new RO(this.#$,this.#f)}constructor(f,W){let J;if(this.#$=f,W instanceof $){let Z=W[oy];if(Z){this.#f=Z,this[sW]();return}else this.#f=W.#f,J=new Headers(W.#f.headers)}else this.#f=W;if(typeof f==="string"||typeof f?.getReader!=="undefined"||f instanceof Blob||f instanceof Uint8Array)J||=W?.headers||{"content-type":"text/plain; charset=UTF-8"},this[h5]=[W?.status||200,f,J]}get headers(){let f=this[h5];if(f){if(!(f[2]instanceof Headers))f[2]=new Headers(f[2]);return f[2]}return this[sW]().headers}get status(){return this[h5]?.[0]??this[sW]().status}get ok(){let f=this.status;return f>=200&&f<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(($)=>{Object.defineProperty(LX.prototype,$,{get(){return this[sW]()[$]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(($)=>{Object.defineProperty(LX.prototype,$,{value:function(){return this[sW]()[$]()}})});Object.setPrototypeOf(LX,RO);Object.setPrototypeOf(LX.prototype,RO.prototype);H90=global.fetch;if(typeof global.crypto==="undefined")global.crypto=K90;global.fetch=($,f)=>{return f={compress:!1,...f},H90($,f)};U90=/^no$/i,R90=/^(application\/json\b|text\/(?!event-stream\b))/i});var Hj={};V1(Hj,{sqlite:()=>I90});import{DatabaseSync as Kj}from"node:sqlite";function Q90($){let f;return $?"database"in $?f=$.database:f=new Kj($.url):f=new Kj(":memory:"),mI("node-sqlite",f,(W)=>{let J=(Z)=>f.prepare(Z);return{db:f,query:W.buildQueryFn({all:(Z,X=[])=>J(Z).all(...X),run:(Z,X=[])=>{let{changes:z,lastInsertRowid:w}=J(Z).run(...X);return{insertId:W.parseBigInt(w),numAffectedRows:W.parseBigInt(z)}}}),close:()=>f.close(),iterator:(Z,X,z=[])=>{if(!Z)throw new Error("Only support select in stream()");return J(X).iterate(...z)}}},{supports:{batching:!1}})}function I90($){return Q90($)}var Uj=K(()=>{P5()});var IO=d((Do0,Nj)=>{var QO={to($,f){if(!f)return`\x1B[${$+1}G`;return`\x1B[${f+1};${$+1}H`},move($,f){let W="";if($<0)W+=`\x1B[${-$}D`;else if($>0)W+=`\x1B[${$}C`;if(f<0)W+=`\x1B[${-f}A`;else if(f>0)W+=`\x1B[${f}B`;return W},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},P90={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},C90={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let f="";for(let W=0;W<$;W++)f+=this.line+(W<$-1?QO.up():"");if($)f+=QO.left;return f}};Nj.exports={cursor:QO,scroll:P90,erase:C90,beep:"\x07"}});var oW=d((Xe0,ej)=>{var oj=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"]]);ej.exports=($)=>$?Object.keys($).map((f)=>[oj.has(f)?oj.get(f):f,$[f]]).reduce((f,W)=>(f[W[0]]=W[1],f),Object.create(null)):{}});var YL=d((q40)=>{var $g=typeof process==="object"&&process?process:{stdout:null,stderr:null},K40=u("events"),fg=u("stream"),H40=u("string_decoder"),Wg=H40.StringDecoder,r9=Symbol("EOF"),l9=Symbol("maybeEmitEnd"),a4=Symbol("emittedEnd"),ZL=Symbol("emittingEnd"),qX=Symbol("emittedError"),XL=Symbol("closed"),Jg=Symbol("read"),zL=Symbol("flush"),Zg=Symbol("flushChunk"),h$=Symbol("encoding"),p9=Symbol("decoder"),wL=Symbol("flowing"),VX=Symbol("paused"),eW=Symbol("resume"),L1=Symbol("buffer"),l2=Symbol("pipes"),D1=Symbol("bufferLength"),yO=Symbol("bufferPush"),jO=Symbol("bufferShift"),n1=Symbol("objectMode"),K1=Symbol("destroyed"),gO=Symbol("error"),bO=Symbol("emitData"),Xg=Symbol("emitEnd"),uO=Symbol("emitEnd2"),n9=Symbol("async"),cO=Symbol("abort"),GL=Symbol("aborted"),k5=Symbol("signal"),QX=($)=>Promise.resolve().then($),Gg=global._MP_NO_ITERATOR_SYMBOLS_!=="1",zg=Gg&&Symbol.asyncIterator||Symbol("asyncIterator not implemented"),wg=Gg&&Symbol.iterator||Symbol("iterator not implemented"),U40=($)=>$==="end"||$==="finish"||$==="prefinish",R40=($)=>$ instanceof ArrayBuffer||typeof $==="object"&&$.constructor&&$.constructor.name==="ArrayBuffer"&&$.byteLength>=0,M40=($)=>!Buffer.isBuffer($)&&ArrayBuffer.isView($);class dO{constructor($,f,W){this.src=$,this.dest=f,this.opts=W,this.ondrain=()=>$[eW](),f.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(){}end(){if(this.unpipe(),this.opts.end)this.dest.end()}}class Yg extends dO{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor($,f,W){super($,f,W);this.proxyErrors=(J)=>f.emit("error",J),$.on("error",this.proxyErrors)}}class iO extends fg{constructor($){super();if(this[wL]=!1,this[VX]=!1,this[l2]=[],this[L1]=[],this[n1]=$&&$.objectMode||!1,this[n1])this[h$]=null;else this[h$]=$&&$.encoding||null;if(this[h$]==="buffer")this[h$]=null;if(this[n9]=$&&!!$.async||!1,this[p9]=this[h$]?new Wg(this[h$]):null,this[r9]=!1,this[a4]=!1,this[ZL]=!1,this[XL]=!1,this[qX]=null,this.writable=!0,this.readable=!0,this[D1]=0,this[K1]=!1,$&&$.debugExposeBuffer===!0)Object.defineProperty(this,"buffer",{get:()=>this[L1]});if($&&$.debugExposePipes===!0)Object.defineProperty(this,"pipes",{get:()=>this[l2]});if(this[k5]=$&&$.signal,this[GL]=!1,this[k5]){if(this[k5].addEventListener("abort",()=>this[cO]()),this[k5].aborted)this[cO]()}}get bufferLength(){return this[D1]}get encoding(){return this[h$]}set encoding($){if(this[n1])throw new Error("cannot set encoding in objectMode");if(this[h$]&&$!==this[h$]&&(this[p9]&&this[p9].lastNeed||this[D1]))throw new Error("cannot change encoding");if(this[h$]!==$){if(this[p9]=$?new Wg($):null,this[L1].length)this[L1]=this[L1].map((f)=>this[p9].write(f))}this[h$]=$}setEncoding($){this.encoding=$}get objectMode(){return this[n1]}set objectMode($){this[n1]=this[n1]||!!$}get["async"](){return this[n9]}set["async"]($){this[n9]=this[n9]||!!$}[cO](){this[GL]=!0,this.emit("abort",this[k5].reason),this.destroy(this[k5].reason)}get aborted(){return this[GL]}set aborted($){}write($,f,W){if(this[GL])return!1;if(this[r9])throw new Error("write after end");if(this[K1])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;if(typeof f==="function")W=f,f="utf8";if(!f)f="utf8";let J=this[n9]?QX:(Z)=>Z();if(!this[n1]&&!Buffer.isBuffer($)){if(M40($))$=Buffer.from($.buffer,$.byteOffset,$.byteLength);else if(R40($))$=Buffer.from($);else if(typeof $!=="string")this.objectMode=!0}if(this[n1]){if(this.flowing&&this[D1]!==0)this[zL](!0);if(this.flowing)this.emit("data",$);else this[yO]($);if(this[D1]!==0)this.emit("readable");if(W)J(W);return this.flowing}if(!$.length){if(this[D1]!==0)this.emit("readable");if(W)J(W);return this.flowing}if(typeof $==="string"&&!(f===this[h$]&&!this[p9].lastNeed))$=Buffer.from($,f);if(Buffer.isBuffer($)&&this[h$])$=this[p9].write($);if(this.flowing&&this[D1]!==0)this[zL](!0);if(this.flowing)this.emit("data",$);else this[yO]($);if(this[D1]!==0)this.emit("readable");if(W)J(W);return this.flowing}read($){if(this[K1])return null;if(this[D1]===0||$===0||$>this[D1])return this[l9](),null;if(this[n1])$=null;if(this[L1].length>1&&!this[n1])if(this.encoding)this[L1]=[this[L1].join("")];else this[L1]=[Buffer.concat(this[L1],this[D1])];let f=this[Jg]($||null,this[L1][0]);return this[l9](),f}[Jg]($,f){if($===f.length||$===null)this[jO]();else this[L1][0]=f.slice($),f=f.slice(0,$),this[D1]-=$;if(this.emit("data",f),!this[L1].length&&!this[r9])this.emit("drain");return f}end($,f,W){if(typeof $==="function")W=$,$=null;if(typeof f==="function")W=f,f="utf8";if($)this.write($,f);if(W)this.once("end",W);if(this[r9]=!0,this.writable=!1,this.flowing||!this[VX])this[l9]();return this}[eW](){if(this[K1])return;if(this[VX]=!1,this[wL]=!0,this.emit("resume"),this[L1].length)this[zL]();else if(this[r9])this[l9]();else this.emit("drain")}resume(){return this[eW]()}pause(){this[wL]=!1,this[VX]=!0}get destroyed(){return this[K1]}get flowing(){return this[wL]}get paused(){return this[VX]}[yO]($){if(this[n1])this[D1]+=1;else this[D1]+=$.length;this[L1].push($)}[jO](){if(this[n1])this[D1]-=1;else this[D1]-=this[L1][0].length;return this[L1].shift()}[zL]($){do;while(this[Zg](this[jO]())&&this[L1].length);if(!$&&!this[L1].length&&!this[r9])this.emit("drain")}[Zg]($){return this.emit("data",$),this.flowing}pipe($,f){if(this[K1])return;let W=this[a4];if(f=f||{},$===$g.stdout||$===$g.stderr)f.end=!1;else f.end=f.end!==!1;if(f.proxyErrors=!!f.proxyErrors,W){if(f.end)$.end()}else if(this[l2].push(!f.proxyErrors?new dO(this,$,f):new Yg(this,$,f)),this[n9])QX(()=>this[eW]());else this[eW]();return $}unpipe($){let f=this[l2].find((W)=>W.dest===$);if(f)this[l2].splice(this[l2].indexOf(f),1),f.unpipe()}addListener($,f){return this.on($,f)}on($,f){let W=super.on($,f);if($==="data"&&!this[l2].length&&!this.flowing)this[eW]();else if($==="readable"&&this[D1]!==0)super.emit("readable");else if(U40($)&&this[a4])super.emit($),this.removeAllListeners($);else if($==="error"&&this[qX])if(this[n9])QX(()=>f.call(this,this[qX]));else f.call(this,this[qX]);return W}get emittedEnd(){return this[a4]}[l9](){if(!this[ZL]&&!this[a4]&&!this[K1]&&this[L1].length===0&&this[r9]){if(this[ZL]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[XL])this.emit("close");this[ZL]=!1}}emit($,f,...W){if($!=="error"&&$!=="close"&&$!==K1&&this[K1])return;else if($==="data")return!this[n1]&&!f?!1:this[n9]?QX(()=>this[bO](f)):this[bO](f);else if($==="end")return this[Xg]();else if($==="close"){if(this[XL]=!0,!this[a4]&&!this[K1])return;let Z=super.emit("close");return this.removeAllListeners("close"),Z}else if($==="error"){this[qX]=f,super.emit(gO,f);let Z=!this[k5]||this.listeners("error").length?super.emit("error",f):!1;return this[l9](),Z}else if($==="resume"){let Z=super.emit("resume");return this[l9](),Z}else if($==="finish"||$==="prefinish"){let Z=super.emit($);return this.removeAllListeners($),Z}let J=super.emit($,f,...W);return this[l9](),J}[bO]($){for(let W of this[l2])if(W.dest.write($)===!1)this.pause();let f=super.emit("data",$);return this[l9](),f}[Xg](){if(this[a4])return;if(this[a4]=!0,this.readable=!1,this[n9])QX(()=>this[uO]());else this[uO]()}[uO](){if(this[p9]){let f=this[p9].end();if(f){for(let W of this[l2])W.dest.write(f);super.emit("data",f)}}for(let f of this[l2])f.end();let $=super.emit("end");return this.removeAllListeners("end"),$}collect(){let $=[];if(!this[n1])$.dataLength=0;let f=this.promise();return this.on("data",(W)=>{if($.push(W),!this[n1])$.dataLength+=W.length}),f.then(()=>$)}concat(){return this[n1]?Promise.reject(new Error("cannot concat in objectMode")):this.collect().then(($)=>this[n1]?Promise.reject(new Error("cannot concat in objectMode")):this[h$]?$.join(""):Buffer.concat($,$.dataLength))}promise(){return new Promise(($,f)=>{this.on(K1,()=>f(new Error("stream destroyed"))),this.on("error",(W)=>f(W)),this.on("end",()=>$())})}[zg](){let $=!1,f=()=>{return this.pause(),$=!0,Promise.resolve({done:!0})};return{next:()=>{if($)return f();let J=this.read();if(J!==null)return Promise.resolve({done:!1,value:J});if(this[r9])return f();let Z=null,X=null,z=(L)=>{this.removeListener("data",w),this.removeListener("end",G),this.removeListener(K1,Y),f(),X(L)},w=(L)=>{this.removeListener("error",z),this.removeListener("end",G),this.removeListener(K1,Y),this.pause(),Z({value:L,done:!!this[r9]})},G=()=>{this.removeListener("error",z),this.removeListener("data",w),this.removeListener(K1,Y),f(),Z({done:!0})},Y=()=>z(new Error("stream destroyed"));return new Promise((L,U)=>{X=U,Z=L,this.once(K1,Y),this.once("error",z),this.once("end",G),this.once("data",w)})},throw:f,return:f,[zg](){return this}}}[wg](){let $=!1,f=()=>{return this.pause(),this.removeListener(gO,f),this.removeListener(K1,f),this.removeListener("end",f),$=!0,{done:!0}},W=()=>{if($)return f();let J=this.read();return J===null?f():{value:J}};return this.once("end",f),this.once(gO,f),this.once(K1,f),{next:W,throw:f,return:f,[wg](){return this}}}destroy($){if(this[K1]){if($)this.emit("error",$);else this.emit(K1);return this}if(this[K1]=!0,this[L1].length=0,this[D1]=0,typeof this.close==="function"&&!this[XL])this.close();if($)this.emit("error",$);else this.emit(K1);return this}static isStream($){return!!$&&($ instanceof iO||$ instanceof fg||$ instanceof K40&&(typeof $.pipe==="function"||typeof $.write==="function"&&typeof $.end==="function"))}}q40.Minipass=iO});var Kg=d((we0,Lg)=>{var Q40=u("zlib").constants||{ZLIB_VERNUM:4736};Lg.exports=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Q40))});var Ag=d((Ge0,Og)=>{var Hg=typeof process==="object"&&process?process:{stdout:null,stderr:null},I40=u("events"),Ug=u("stream"),Rg=u("string_decoder").StringDecoder,s9=Symbol("EOF"),t9=Symbol("maybeEmitEnd"),o4=Symbol("emittedEnd"),LL=Symbol("emittingEnd"),IX=Symbol("emittedError"),KL=Symbol("closed"),Mg=Symbol("read"),HL=Symbol("flush"),qg=Symbol("flushChunk"),D$=Symbol("encoding"),a9=Symbol("decoder"),UL=Symbol("flowing"),OX=Symbol("paused"),$J=Symbol("resume"),v1=Symbol("bufferLength"),rO=Symbol("bufferPush"),lO=Symbol("bufferShift"),J$=Symbol("objectMode"),Z$=Symbol("destroyed"),pO=Symbol("emitData"),Vg=Symbol("emitEnd"),nO=Symbol("emitEnd2"),o9=Symbol("async"),AX=($)=>Promise.resolve().then($),Qg=global._MP_NO_ITERATOR_SYMBOLS_!=="1",O40=Qg&&Symbol.asyncIterator||Symbol("asyncIterator not implemented"),A40=Qg&&Symbol.iterator||Symbol("iterator not implemented"),x40=($)=>$==="end"||$==="finish"||$==="prefinish",_40=($)=>$ instanceof ArrayBuffer||typeof $==="object"&&$.constructor&&$.constructor.name==="ArrayBuffer"&&$.byteLength>=0,N40=($)=>!Buffer.isBuffer($)&&ArrayBuffer.isView($);class sO{constructor($,f,W){this.src=$,this.dest=f,this.opts=W,this.ondrain=()=>$[$J](),f.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(){}end(){if(this.unpipe(),this.opts.end)this.dest.end()}}class Ig extends sO{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor($,f,W){super($,f,W);this.proxyErrors=(J)=>f.emit("error",J),$.on("error",this.proxyErrors)}}Og.exports=class $ extends Ug{constructor(f){super();if(this[UL]=!1,this[OX]=!1,this.pipes=[],this.buffer=[],this[J$]=f&&f.objectMode||!1,this[J$])this[D$]=null;else this[D$]=f&&f.encoding||null;if(this[D$]==="buffer")this[D$]=null;this[o9]=f&&!!f.async||!1,this[a9]=this[D$]?new Rg(this[D$]):null,this[s9]=!1,this[o4]=!1,this[LL]=!1,this[KL]=!1,this[IX]=null,this.writable=!0,this.readable=!0,this[v1]=0,this[Z$]=!1}get bufferLength(){return this[v1]}get encoding(){return this[D$]}set encoding(f){if(this[J$])throw new Error("cannot set encoding in objectMode");if(this[D$]&&f!==this[D$]&&(this[a9]&&this[a9].lastNeed||this[v1]))throw new Error("cannot change encoding");if(this[D$]!==f){if(this[a9]=f?new Rg(f):null,this.buffer.length)this.buffer=this.buffer.map((W)=>this[a9].write(W))}this[D$]=f}setEncoding(f){this.encoding=f}get objectMode(){return this[J$]}set objectMode(f){this[J$]=this[J$]||!!f}get["async"](){return this[o9]}set["async"](f){this[o9]=this[o9]||!!f}write(f,W,J){if(this[s9])throw new Error("write after end");if(this[Z$])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;if(typeof W==="function")J=W,W="utf8";if(!W)W="utf8";let Z=this[o9]?AX:(X)=>X();if(!this[J$]&&!Buffer.isBuffer(f)){if(N40(f))f=Buffer.from(f.buffer,f.byteOffset,f.byteLength);else if(_40(f))f=Buffer.from(f);else if(typeof f!=="string")this.objectMode=!0}if(this[J$]){if(this.flowing&&this[v1]!==0)this[HL](!0);if(this.flowing)this.emit("data",f);else this[rO](f);if(this[v1]!==0)this.emit("readable");if(J)Z(J);return this.flowing}if(!f.length){if(this[v1]!==0)this.emit("readable");if(J)Z(J);return this.flowing}if(typeof f==="string"&&!(W===this[D$]&&!this[a9].lastNeed))f=Buffer.from(f,W);if(Buffer.isBuffer(f)&&this[D$])f=this[a9].write(f);if(this.flowing&&this[v1]!==0)this[HL](!0);if(this.flowing)this.emit("data",f);else this[rO](f);if(this[v1]!==0)this.emit("readable");if(J)Z(J);return this.flowing}read(f){if(this[Z$])return null;if(this[v1]===0||f===0||f>this[v1])return this[t9](),null;if(this[J$])f=null;if(this.buffer.length>1&&!this[J$])if(this.encoding)this.buffer=[this.buffer.join("")];else this.buffer=[Buffer.concat(this.buffer,this[v1])];let W=this[Mg](f||null,this.buffer[0]);return this[t9](),W}[Mg](f,W){if(f===W.length||f===null)this[lO]();else this.buffer[0]=W.slice(f),W=W.slice(0,f),this[v1]-=f;if(this.emit("data",W),!this.buffer.length&&!this[s9])this.emit("drain");return W}end(f,W,J){if(typeof f==="function")J=f,f=null;if(typeof W==="function")J=W,W="utf8";if(f)this.write(f,W);if(J)this.once("end",J);if(this[s9]=!0,this.writable=!1,this.flowing||!this[OX])this[t9]();return this}[$J](){if(this[Z$])return;if(this[OX]=!1,this[UL]=!0,this.emit("resume"),this.buffer.length)this[HL]();else if(this[s9])this[t9]();else this.emit("drain")}resume(){return this[$J]()}pause(){this[UL]=!1,this[OX]=!0}get destroyed(){return this[Z$]}get flowing(){return this[UL]}get paused(){return this[OX]}[rO](f){if(this[J$])this[v1]+=1;else this[v1]+=f.length;this.buffer.push(f)}[lO](){if(this.buffer.length)if(this[J$])this[v1]-=1;else this[v1]-=this.buffer[0].length;return this.buffer.shift()}[HL](f){do;while(this[qg](this[lO]()));if(!f&&!this.buffer.length&&!this[s9])this.emit("drain")}[qg](f){return f?(this.emit("data",f),this.flowing):!1}pipe(f,W){if(this[Z$])return;let J=this[o4];if(W=W||{},f===Hg.stdout||f===Hg.stderr)W.end=!1;else W.end=W.end!==!1;if(W.proxyErrors=!!W.proxyErrors,J){if(W.end)f.end()}else if(this.pipes.push(!W.proxyErrors?new sO(this,f,W):new Ig(this,f,W)),this[o9])AX(()=>this[$J]());else this[$J]();return f}unpipe(f){let W=this.pipes.find((J)=>J.dest===f);if(W)this.pipes.splice(this.pipes.indexOf(W),1),W.unpipe()}addListener(f,W){return this.on(f,W)}on(f,W){let J=super.on(f,W);if(f==="data"&&!this.pipes.length&&!this.flowing)this[$J]();else if(f==="readable"&&this[v1]!==0)super.emit("readable");else if(x40(f)&&this[o4])super.emit(f),this.removeAllListeners(f);else if(f==="error"&&this[IX])if(this[o9])AX(()=>W.call(this,this[IX]));else W.call(this,this[IX]);return J}get emittedEnd(){return this[o4]}[t9](){if(!this[LL]&&!this[o4]&&!this[Z$]&&this.buffer.length===0&&this[s9]){if(this[LL]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[KL])this.emit("close");this[LL]=!1}}emit(f,W,...J){if(f!=="error"&&f!=="close"&&f!==Z$&&this[Z$])return;else if(f==="data")return!W?!1:this[o9]?AX(()=>this[pO](W)):this[pO](W);else if(f==="end")return this[Vg]();else if(f==="close"){if(this[KL]=!0,!this[o4]&&!this[Z$])return;let X=super.emit("close");return this.removeAllListeners("close"),X}else if(f==="error"){this[IX]=W;let X=super.emit("error",W);return this[t9](),X}else if(f==="resume"){let X=super.emit("resume");return this[t9](),X}else if(f==="finish"||f==="prefinish"){let X=super.emit(f);return this.removeAllListeners(f),X}let Z=super.emit(f,W,...J);return this[t9](),Z}[pO](f){for(let J of this.pipes)if(J.dest.write(f)===!1)this.pause();let W=super.emit("data",f);return this[t9](),W}[Vg](){if(this[o4])return;if(this[o4]=!0,this.readable=!1,this[o9])AX(()=>this[nO]());else this[nO]()}[nO](){if(this[a9]){let W=this[a9].end();if(W){for(let J of this.pipes)J.dest.write(W);super.emit("data",W)}}for(let W of this.pipes)W.end();let f=super.emit("end");return this.removeAllListeners("end"),f}collect(){let f=[];if(!this[J$])f.dataLength=0;let W=this.promise();return this.on("data",(J)=>{if(f.push(J),!this[J$])f.dataLength+=J.length}),W.then(()=>f)}concat(){return this[J$]?Promise.reject(new Error("cannot concat in objectMode")):this.collect().then((f)=>this[J$]?Promise.reject(new Error("cannot concat in objectMode")):this[D$]?f.join(""):Buffer.concat(f,f.dataLength))}promise(){return new Promise((f,W)=>{this.on(Z$,()=>W(new Error("stream destroyed"))),this.on("error",(J)=>W(J)),this.on("end",()=>f())})}[O40](){return{next:()=>{let W=this.read();if(W!==null)return Promise.resolve({done:!1,value:W});if(this[s9])return Promise.resolve({done:!0});let J=null,Z=null,X=(Y)=>{this.removeListener("data",z),this.removeListener("end",w),Z(Y)},z=(Y)=>{this.removeListener("error",X),this.removeListener("end",w),this.pause(),J({value:Y,done:!!this[s9]})},w=()=>{this.removeListener("error",X),this.removeListener("data",z),J({done:!0})},G=()=>X(new Error("stream destroyed"));return new Promise((Y,L)=>{Z=L,J=Y,this.once(Z$,G),this.once("error",X),this.once("end",w),this.once("data",z)})}}}[A40](){return{next:()=>{let W=this.read();return{value:W,done:W===null}}}}destroy(f){if(this[Z$]){if(f)this.emit("error",f);else this.emit(Z$);return this}if(this[Z$]=!0,this.buffer.length=0,this[v1]=0,typeof this.close==="function"&&!this[KL])this.close();if(f)this.emit("error",f);else this.emit(Z$);return this}static isStream(f){return!!f&&(f instanceof $||f instanceof Ug||f instanceof I40&&(typeof f.pipe==="function"||typeof f.write==="function"&&typeof f.end==="function"))}}});var ZA=d((P40)=>{var $A=u("assert"),e4=u("buffer").Buffer,Ng=u("zlib"),y5=P40.constants=Kg(),B40=Ag(),xg=e4.concat,j5=Symbol("_superWrite");class _X extends Error{constructor($){super("zlib: "+$.message);if(this.code=$.code,this.errno=$.errno,!this.code)this.code="ZLIB_ERROR";this.message="zlib: "+$.message,Error.captureStackTrace(this,this.constructor)}get name(){return"ZlibError"}}var T40=Symbol("opts"),xX=Symbol("flushFlag"),_g=Symbol("finishFlushFlag"),fA=Symbol("fullFlushFlag"),u0=Symbol("handle"),RL=Symbol("onError"),fJ=Symbol("sawError"),tO=Symbol("level"),aO=Symbol("strategy"),oO=Symbol("ended"),Ye0=Symbol("_defaultFullFlush");class WA extends B40{constructor($,f){if(!$||typeof $!=="object")throw new TypeError("invalid options for ZlibBase constructor");super($);this[fJ]=!1,this[oO]=!1,this[T40]=$,this[xX]=$.flush,this[_g]=$.finishFlush;try{this[u0]=new Ng[f]($)}catch(W){throw new _X(W)}this[RL]=(W)=>{if(this[fJ])return;this[fJ]=!0,this.close(),this.emit("error",W)},this[u0].on("error",(W)=>this[RL](new _X(W))),this.once("end",()=>this.close)}close(){if(this[u0])this[u0].close(),this[u0]=null,this.emit("close")}reset(){if(!this[fJ])return $A(this[u0],"zlib binding closed"),this[u0].reset()}flush($){if(this.ended)return;if(typeof $!=="number")$=this[fA];this.write(Object.assign(e4.alloc(0),{[xX]:$}))}end($,f,W){if($)this.write($,f);return this.flush(this[_g]),this[oO]=!0,super.end(null,null,W)}get ended(){return this[oO]}write($,f,W){if(typeof f==="function")W=f,f="utf8";if(typeof $==="string")$=e4.from($,f);if(this[fJ])return;$A(this[u0],"zlib binding closed");let J=this[u0]._handle,Z=J.close;J.close=()=>{};let X=this[u0].close;this[u0].close=()=>{},e4.concat=(G)=>G;let z;try{let G=typeof $[xX]==="number"?$[xX]:this[xX];z=this[u0]._processChunk($,G),e4.concat=xg}catch(G){e4.concat=xg,this[RL](new _X(G))}finally{if(this[u0])this[u0]._handle=J,J.close=Z,this[u0].close=X,this[u0].removeAllListeners("error")}if(this[u0])this[u0].on("error",(G)=>this[RL](new _X(G)));let w;if(z)if(Array.isArray(z)&&z.length>0){w=this[j5](e4.from(z[0]));for(let G=1;G<z.length;G++)w=this[j5](z[G])}else w=this[j5](e4.from(z));if(W)W();return w}[j5]($){return super.write($)}}class $6 extends WA{constructor($,f){$=$||{},$.flush=$.flush||y5.Z_NO_FLUSH,$.finishFlush=$.finishFlush||y5.Z_FINISH;super($,f);this[fA]=y5.Z_FULL_FLUSH,this[tO]=$.level,this[aO]=$.strategy}params($,f){if(this[fJ])return;if(!this[u0])throw new Error("cannot switch params when binding is closed");if(!this[u0].params)throw new Error("not supported in this implementation");if(this[tO]!==$||this[aO]!==f){this.flush(y5.Z_SYNC_FLUSH),$A(this[u0],"zlib binding closed");let W=this[u0].flush;this[u0].flush=(J,Z)=>{this.flush(J),Z()};try{this[u0].params($,f)}finally{this[u0].flush=W}if(this[u0])this[tO]=$,this[aO]=f}}}class Sg extends $6{constructor($){super($,"Deflate")}}class Fg extends $6{constructor($){super($,"Inflate")}}var eO=Symbol("_portable");class Bg extends $6{constructor($){super($,"Gzip");this[eO]=$&&!!$.portable}[j5]($){if(!this[eO])return super[j5]($);return this[eO]=!1,$[9]=255,super[j5]($)}}class Tg extends $6{constructor($){super($,"Gunzip")}}class Pg extends $6{constructor($){super($,"DeflateRaw")}}class Cg extends $6{constructor($){super($,"InflateRaw")}}class Eg extends $6{constructor($){super($,"Unzip")}}class JA extends WA{constructor($,f){$=$||{},$.flush=$.flush||y5.BROTLI_OPERATION_PROCESS,$.finishFlush=$.finishFlush||y5.BROTLI_OPERATION_FINISH;super($,f);this[fA]=y5.BROTLI_OPERATION_FLUSH}}class hg extends JA{constructor($){super($,"BrotliCompress")}}class Dg extends JA{constructor($){super($,"BrotliDecompress")}}P40.Deflate=Sg;P40.Inflate=Fg;P40.Gzip=Bg;P40.Gunzip=Tg;P40.DeflateRaw=Pg;P40.InflateRaw=Cg;P40.Unzip=Eg;if(typeof Ng.BrotliCompress==="function")P40.BrotliCompress=hg,P40.BrotliDecompress=Dg;else P40.BrotliCompress=P40.BrotliDecompress=class{constructor(){throw new Error("Brotli is not supported in this version of Node.js")}}});var WJ=d((Ue0,vg)=>{var y40=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;vg.exports=y40!=="win32"?($)=>$:($)=>$&&$.replace(/\\/g,"/")});var ML=d((Re0,mg)=>{var{Minipass:j40}=YL(),XA=WJ(),zA=Symbol("slurp");mg.exports=class $ extends j40{constructor(f,W,J){super();switch(this.pause(),this.extended=W,this.globalExtended=J,this.header=f,this.startBlockSize=512*Math.ceil(f.size/512),this.blockRemain=this.startBlockSize,this.remain=f.size,this.type=f.type,this.meta=!1,this.ignore=!1,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(this.path=XA(f.path),this.mode=f.mode,this.mode)this.mode=this.mode&4095;if(this.uid=f.uid,this.gid=f.gid,this.uname=f.uname,this.gname=f.gname,this.size=f.size,this.mtime=f.mtime,this.atime=f.atime,this.ctime=f.ctime,this.linkpath=XA(f.linkpath),this.uname=f.uname,this.gname=f.gname,W)this[zA](W);if(J)this[zA](J,!0)}write(f){let W=f.length;if(W>this.blockRemain)throw new Error("writing more to entry than is appropriate");let J=this.remain,Z=this.blockRemain;if(this.remain=Math.max(0,J-W),this.blockRemain=Math.max(0,Z-W),this.ignore)return!0;if(J>=W)return super.write(f);return super.write(f.slice(0,J))}[zA](f,W){for(let J in f)if(f[J]!==null&&f[J]!==void 0&&!(W&&J==="path"))this[J]=J==="path"||J==="linkpath"?XA(f[J]):f[J]}}});var wA=d((g40)=>{g40.name=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]);g40.code=new Map(Array.from(g40.name).map(($)=>[$[1],$[0]]))});var bg=d((qe0,gg)=>{var u40=($,f)=>{if(!Number.isSafeInteger($))throw Error("cannot encode number outside of javascript safe integer range");else if($<0)d40($,f);else c40($,f);return f},c40=($,f)=>{f[0]=128;for(var W=f.length;W>1;W--)f[W-1]=$&255,$=Math.floor($/256)},d40=($,f)=>{f[0]=255;var W=!1;$=$*-1;for(var J=f.length;J>1;J--){var Z=$&255;if($=Math.floor($/256),W)f[J-1]=yg(Z);else if(Z===0)f[J-1]=0;else W=!0,f[J-1]=jg(Z)}},i40=($)=>{let f=$[0],W=f===128?l40($.slice(1,$.length)):f===255?r40($):null;if(W===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(W))throw Error("parsed number outside of javascript safe integer range");return W},r40=($)=>{var f=$.length,W=0,J=!1;for(var Z=f-1;Z>-1;Z--){var X=$[Z],z;if(J)z=yg(X);else if(X===0)z=X;else J=!0,z=jg(X);if(z!==0)W-=z*Math.pow(256,f-Z-1)}return W},l40=($)=>{var f=$.length,W=0;for(var J=f-1;J>-1;J--){var Z=$[J];if(Z!==0)W+=Z*Math.pow(256,f-J-1)}return W},yg=($)=>(255^$)&255,jg=($)=>(255^$)+1&255;gg.exports={encode:u40,parse:i40}});var ZJ=d((Ve0,dg)=>{var GA=wA(),JJ=u("path").posix,ug=bg(),YA=Symbol("slurp"),Wf=Symbol("type");class cg{constructor($,f,W,J){if(this.cksumValid=!1,this.needPax=!1,this.nullBlock=!1,this.block=null,this.path=null,this.mode=null,this.uid=null,this.gid=null,this.size=null,this.mtime=null,this.cksum=null,this[Wf]="0",this.linkpath=null,this.uname=null,this.gname=null,this.devmaj=0,this.devmin=0,this.atime=null,this.ctime=null,Buffer.isBuffer($))this.decode($,f||0,W,J);else if($)this.set($)}decode($,f,W,J){if(!f)f=0;if(!$||!($.length>=f+512))throw new Error("need 512 bytes for header");if(this.path=g5($,f,100),this.mode=f6($,f+100,8),this.uid=f6($,f+108,8),this.gid=f6($,f+116,8),this.size=f6($,f+124,12),this.mtime=LA($,f+136,12),this.cksum=f6($,f+148,12),this[YA](W),this[YA](J,!0),this[Wf]=g5($,f+156,1),this[Wf]==="")this[Wf]="0";if(this[Wf]==="0"&&this.path.slice(-1)==="/")this[Wf]="5";if(this[Wf]==="5")this.size=0;if(this.linkpath=g5($,f+157,100),$.slice(f+257,f+265).toString()==="ustar\x0000")if(this.uname=g5($,f+265,32),this.gname=g5($,f+297,32),this.devmaj=f6($,f+329,8),this.devmin=f6($,f+337,8),$[f+475]!==0){let X=g5($,f+345,155);this.path=X+"/"+this.path}else{let X=g5($,f+345,130);if(X)this.path=X+"/"+this.path;this.atime=LA($,f+476,12),this.ctime=LA($,f+488,12)}let Z=256;for(let X=f;X<f+148;X++)Z+=$[X];for(let X=f+156;X<f+512;X++)Z+=$[X];if(this.cksumValid=Z===this.cksum,this.cksum===null&&Z===256)this.nullBlock=!0}[YA]($,f){for(let W in $)if($[W]!==null&&$[W]!==void 0&&!(f&&W==="path"))this[W]=$[W]}encode($,f){if(!$)$=this.block=Buffer.alloc(512),f=0;if(!f)f=0;if(!($.length>=f+512))throw new Error("need 512 bytes for header");let W=this.ctime||this.atime?130:155,J=p40(this.path||"",W),Z=J[0],X=J[1];if(this.needPax=J[2],this.needPax=b5($,f,100,Z)||this.needPax,this.needPax=W6($,f+100,8,this.mode)||this.needPax,this.needPax=W6($,f+108,8,this.uid)||this.needPax,this.needPax=W6($,f+116,8,this.gid)||this.needPax,this.needPax=W6($,f+124,12,this.size)||this.needPax,this.needPax=KA($,f+136,12,this.mtime)||this.needPax,$[f+156]=this[Wf].charCodeAt(0),this.needPax=b5($,f+157,100,this.linkpath)||this.needPax,$.write("ustar\x0000",f+257,8),this.needPax=b5($,f+265,32,this.uname)||this.needPax,this.needPax=b5($,f+297,32,this.gname)||this.needPax,this.needPax=W6($,f+329,8,this.devmaj)||this.needPax,this.needPax=W6($,f+337,8,this.devmin)||this.needPax,this.needPax=b5($,f+345,W,X)||this.needPax,$[f+475]!==0)this.needPax=b5($,f+345,155,X)||this.needPax;else this.needPax=b5($,f+345,130,X)||this.needPax,this.needPax=KA($,f+476,12,this.atime)||this.needPax,this.needPax=KA($,f+488,12,this.ctime)||this.needPax;let z=256;for(let w=f;w<f+148;w++)z+=$[w];for(let w=f+156;w<f+512;w++)z+=$[w];return this.cksum=z,W6($,f+148,8,this.cksum),this.cksumValid=!0,this.needPax}set($){for(let f in $)if($[f]!==null&&$[f]!==void 0)this[f]=$[f]}get type(){return GA.name.get(this[Wf])||this[Wf]}get typeKey(){return this[Wf]}set type($){if(GA.code.has($))this[Wf]=GA.code.get($);else this[Wf]=$}}var p40=($,f)=>{let J=$,Z="",X,z=JJ.parse($).root||".";if(Buffer.byteLength(J)<100)X=[J,Z,!1];else{Z=JJ.dirname(J),J=JJ.basename(J);do if(Buffer.byteLength(J)<=100&&Buffer.byteLength(Z)<=f)X=[J,Z,!1];else if(Buffer.byteLength(J)>100&&Buffer.byteLength(Z)<=f)X=[J.slice(0,99),Z,!0];else J=JJ.join(JJ.basename(Z),J),Z=JJ.dirname(Z);while(Z!==z&&!X);if(!X)X=[$.slice(0,99),"",!0]}return X},g5=($,f,W)=>$.slice(f,f+W).toString("utf8").replace(/\0.*/,""),LA=($,f,W)=>n40(f6($,f,W)),n40=($)=>$===null?null:new Date($*1000),f6=($,f,W)=>$[f]&128?ug.parse($.slice(f,f+W)):t40($,f,W),s40=($)=>isNaN($)?null:$,t40=($,f,W)=>s40(parseInt($.slice(f,f+W).toString("utf8").replace(/\0.*$/,"").trim(),8)),a40={12:8589934591,8:2097151},W6=($,f,W,J)=>J===null?!1:J>a40[W]||J<0?(ug.encode(J,$.slice(f,f+W)),!0):(o40($,f,W,J),!1),o40=($,f,W,J)=>$.write(e40(J,W),f,W,"ascii"),e40=($,f)=>$60(Math.floor($).toString(8),f),$60=($,f)=>($.length===f-1?$:new Array(f-$.length-1).join("0")+$+" ")+"\x00",KA=($,f,W,J)=>J===null?!1:W6($,f,W,J.getTime()/1000),f60=new Array(156).join("\x00"),b5=($,f,W,J)=>J===null?!1:($.write(J+f60,f,W,"utf8"),J.length!==Buffer.byteLength(J)||J.length>W);dg.exports=cg});var VL=d((Qe0,ig)=>{var W60=ZJ(),J60=u("path");class qL{constructor($,f){this.atime=$.atime||null,this.charset=$.charset||null,this.comment=$.comment||null,this.ctime=$.ctime||null,this.gid=$.gid||null,this.gname=$.gname||null,this.linkpath=$.linkpath||null,this.mtime=$.mtime||null,this.path=$.path||null,this.size=$.size||null,this.uid=$.uid||null,this.uname=$.uname||null,this.dev=$.dev||null,this.ino=$.ino||null,this.nlink=$.nlink||null,this.global=f||!1}encode(){let $=this.encodeBody();if($==="")return null;let f=Buffer.byteLength($),W=512*Math.ceil(1+f/512),J=Buffer.allocUnsafe(W);for(let Z=0;Z<512;Z++)J[Z]=0;new W60({path:("PaxHeader/"+J60.basename(this.path)).slice(0,99),mode:this.mode||420,uid:this.uid||null,gid:this.gid||null,size:f,mtime:this.mtime||null,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime||null,ctime:this.ctime||null}).encode(J),J.write($,512,f,"utf8");for(let Z=f+512;Z<J.length;Z++)J[Z]=0;return J}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField($){if(this[$]===null||this[$]===void 0)return"";let f=this[$]instanceof Date?this[$].getTime()/1000:this[$],W=" "+($==="dev"||$==="ino"||$==="nlink"?"SCHILY.":"")+$+"="+f+`
`,J=Buffer.byteLength(W),Z=Math.floor(Math.log(J)/Math.log(10))+1;if(J+Z>=Math.pow(10,Z))Z+=1;return Z+J+W}}qL.parse=($,f,W)=>new qL(Z60(X60($),f),W);var Z60=($,f)=>f?Object.keys($).reduce((W,J)=>(W[J]=$[J],W),f):$,X60=($)=>$.replace(/\n$/,"").split(`
`).reduce(z60,Object.create(null)),z60=($,f)=>{let W=parseInt(f,10);if(W!==Buffer.byteLength(f)+1)return $;f=f.slice((W+" ").length);let J=f.split("="),Z=J.shift().replace(/^SCHILY\.(dev|ino|nlink)/,"$1");if(!Z)return $;let X=J.join("=");return $[Z]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(Z)?new Date(X*1000):/^[0-9]+$/.test(X)?+X:X,$};ig.exports=qL});var XJ=d((Ie0,rg)=>{rg.exports=($)=>{let f=$.length-1,W=-1;while(f>-1&&$.charAt(f)==="/")W=f,f--;return W===-1?$:$.slice(0,W)}});var QL=d((Oe0,lg)=>{lg.exports=($)=>class extends ${warn(f,W,J={}){if(this.file)J.file=this.file;if(this.cwd)J.cwd=this.cwd;if(J.code=W instanceof Error&&W.code||f,J.tarCode=f,!this.strict&&J.recoverable!==!1){if(W instanceof Error)J=Object.assign(W,J),W=W.message;this.emit("warn",J.tarCode,W,J)}else if(W instanceof Error)this.emit("error",Object.assign(W,J));else this.emit("error",Object.assign(new Error(`${f}: ${W}`),J))}}});var UA=d((xe0,pg)=>{var IL=["|","<",">","?",":"],HA=IL.map(($)=>String.fromCharCode(61440+$.charCodeAt(0))),w60=new Map(IL.map(($,f)=>[$,HA[f]])),G60=new Map(HA.map(($,f)=>[$,IL[f]]));pg.exports={encode:($)=>IL.reduce((f,W)=>f.split(W).join(w60.get(W)),$),decode:($)=>HA.reduce((f,W)=>f.split(W).join(G60.get(W)),$)}});var RA=d((_e0,sg)=>{var{isAbsolute:Y60,parse:ng}=u("path").win32;sg.exports=($)=>{let f="",W=ng($);while(Y60($)||W.root){let J=$.charAt(0)==="/"&&$.slice(0,4)!=="//?/"?"/":W.root;$=$.slice(J.length),f+=J,W=ng($)}return[f,$]}});var ag=d((Ne0,tg)=>{tg.exports=($,f,W)=>{if($&=4095,W)$=($|384)&-19;if(f){if($&256)$|=64;if($&32)$|=8;if($&4)$|=1}return $}});var _A=d((Se0,Hb)=>{var{Minipass:Zb}=YL(),Xb=VL(),zb=ZJ(),n2=u("fs"),og=u("path"),p2=WJ(),L60=XJ(),wb=($,f)=>{if(!f)return p2($);return $=p2($).replace(/^\.(\/|$)/,""),L60(f)+"/"+$},eg=Symbol("process"),$b=Symbol("file"),fb=Symbol("directory"),qA=Symbol("symlink"),Wb=Symbol("hardlink"),NX=Symbol("header"),OL=Symbol("read"),VA=Symbol("lstat"),AL=Symbol("onlstat"),QA=Symbol("onread"),IA=Symbol("onreadlink"),OA=Symbol("openfile"),AA=Symbol("onopenfile"),J6=Symbol("close"),xL=Symbol("mode"),xA=Symbol("awaitDrain"),MA=Symbol("ondrain"),s2=Symbol("prefix"),Jb=Symbol("hadError"),Gb=QL(),K60=UA(),Yb=RA(),Lb=ag(),_L=Gb(class $ extends Zb{constructor(f,W){W=W||{};super(W);if(typeof f!=="string")throw new TypeError("path is required");if(this.path=p2(f),this.portable=!!W.portable,this.myuid=process.getuid&&process.getuid()||0,this.myuser=process.env.USER||"",this.maxReadSize=W.maxReadSize||16777216,this.linkCache=W.linkCache||new Map,this.statCache=W.statCache||new Map,this.preservePaths=!!W.preservePaths,this.cwd=p2(W.cwd||process.cwd()),this.strict=!!W.strict,this.noPax=!!W.noPax,this.noMtime=!!W.noMtime,this.mtime=W.mtime||null,this.prefix=W.prefix?p2(W.prefix):null,this.fd=null,this.blockLen=null,this.blockRemain=null,this.buf=null,this.offset=null,this.length=null,this.pos=null,this.remain=null,typeof W.onwarn==="function")this.on("warn",W.onwarn);let J=!1;if(!this.preservePaths){let[Z,X]=Yb(this.path);if(Z)this.path=X,J=Z}if(this.win32=!!W.win32||process.platform==="win32",this.win32)this.path=K60.decode(this.path.replace(/\\/g,"/")),f=f.replace(/\\/g,"/");if(this.absolute=p2(W.absolute||og.resolve(this.cwd,f)),this.path==="")this.path="./";if(J)this.warn("TAR_ENTRY_INFO",`stripping ${J} from absolute path`,{entry:this,path:J+this.path});if(this.statCache.has(this.absolute))this[AL](this.statCache.get(this.absolute));else this[VA]()}emit(f,...W){if(f==="error")this[Jb]=!0;return super.emit(f,...W)}[VA](){n2.lstat(this.absolute,(f,W)=>{if(f)return this.emit("error",f);this[AL](W)})}[AL](f){if(this.statCache.set(this.absolute,f),this.stat=f,!f.isFile())f.size=0;this.type=U60(f),this.emit("stat",f),this[eg]()}[eg](){switch(this.type){case"File":return this[$b]();case"Directory":return this[fb]();case"SymbolicLink":return this[qA]();default:return this.end()}}[xL](f){return Lb(f,this.type==="Directory",this.portable)}[s2](f){return wb(f,this.prefix)}[NX](){if(this.type==="Directory"&&this.portable)this.noMtime=!0;if(this.header=new zb({path:this[s2](this.path),linkpath:this.type==="Link"?this[s2](this.linkpath):this.linkpath,mode:this[xL](this.stat.mode),uid:this.portable?null:this.stat.uid,gid:this.portable?null:this.stat.gid,size:this.stat.size,mtime:this.noMtime?null:this.mtime||this.stat.mtime,type:this.type,uname:this.portable?null:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?null:this.stat.atime,ctime:this.portable?null:this.stat.ctime}),this.header.encode()&&!this.noPax)super.write(new Xb({atime:this.portable?null:this.header.atime,ctime:this.portable?null:this.header.ctime,gid:this.portable?null:this.header.gid,mtime:this.noMtime?null:this.mtime||this.header.mtime,path:this[s2](this.path),linkpath:this.type==="Link"?this[s2](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?null:this.header.uid,uname:this.portable?null:this.header.uname,dev:this.portable?null:this.stat.dev,ino:this.portable?null:this.stat.ino,nlink:this.portable?null:this.stat.nlink}).encode());super.write(this.header.block)}[fb](){if(this.path.slice(-1)!=="/")this.path+="/";this.stat.size=0,this[NX](),this.end()}[qA](){n2.readlink(this.absolute,(f,W)=>{if(f)return this.emit("error",f);this[IA](W)})}[IA](f){this.linkpath=p2(f),this[NX](),this.end()}[Wb](f){this.type="Link",this.linkpath=p2(og.relative(this.cwd,f)),this.stat.size=0,this[NX](),this.end()}[$b](){if(this.stat.nlink>1){let f=this.stat.dev+":"+this.stat.ino;if(this.linkCache.has(f)){let W=this.linkCache.get(f);if(W.indexOf(this.cwd)===0)return this[Wb](W)}this.linkCache.set(f,this.absolute)}if(this[NX](),this.stat.size===0)return this.end();this[OA]()}[OA](){n2.open(this.absolute,"r",(f,W)=>{if(f)return this.emit("error",f);this[AA](W)})}[AA](f){if(this.fd=f,this[Jb])return this[J6]();this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let W=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(W),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[OL]()}[OL](){let{fd:f,buf:W,offset:J,length:Z,pos:X}=this;n2.read(f,W,J,Z,X,(z,w)=>{if(z)return this[J6](()=>this.emit("error",z));this[QA](w)})}[J6](f){n2.close(this.fd,f)}[QA](f){if(f<=0&&this.remain>0){let Z=new Error("encountered unexpected EOF");return Z.path=this.absolute,Z.syscall="read",Z.code="EOF",this[J6](()=>this.emit("error",Z))}if(f>this.remain){let Z=new Error("did not encounter expected EOF");return Z.path=this.absolute,Z.syscall="read",Z.code="EOF",this[J6](()=>this.emit("error",Z))}if(f===this.remain)for(let Z=f;Z<this.length&&f<this.blockRemain;Z++)this.buf[Z+this.offset]=0,f++,this.remain++;let W=this.offset===0&&f===this.buf.length?this.buf:this.buf.slice(this.offset,this.offset+f);if(!this.write(W))this[xA](()=>this[MA]());else this[MA]()}[xA](f){this.once("drain",f)}write(f){if(this.blockRemain<f.length){let W=new Error("writing more data than expected");return W.path=this.absolute,this.emit("error",W)}return this.remain-=f.length,this.blockRemain-=f.length,this.pos+=f.length,this.offset+=f.length,super.write(f)}[MA](){if(!this.remain){if(this.blockRemain)super.write(Buffer.alloc(this.blockRemain));return this[J6]((f)=>f?this.emit("error",f):this.end())}if(this.offset>=this.length)this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0;this.length=this.buf.length-this.offset,this[OL]()}});class Kb extends _L{[VA](){this[AL](n2.lstatSync(this.absolute))}[qA](){this[IA](n2.readlinkSync(this.absolute))}[OA](){this[AA](n2.openSync(this.absolute,"r"))}[OL](){let $=!0;try{let{fd:f,buf:W,offset:J,length:Z,pos:X}=this,z=n2.readSync(f,W,J,Z,X);this[QA](z),$=!1}finally{if($)try{this[J6](()=>{})}catch(f){}}}[xA]($){$()}[J6]($){n2.closeSync(this.fd),$()}}var H60=Gb(class $ extends Zb{constructor(f,W){W=W||{};super(W);if(this.preservePaths=!!W.preservePaths,this.portable=!!W.portable,this.strict=!!W.strict,this.noPax=!!W.noPax,this.noMtime=!!W.noMtime,this.readEntry=f,this.type=f.type,this.type==="Directory"&&this.portable)this.noMtime=!0;if(this.prefix=W.prefix||null,this.path=p2(f.path),this.mode=this[xL](f.mode),this.uid=this.portable?null:f.uid,this.gid=this.portable?null:f.gid,this.uname=this.portable?null:f.uname,this.gname=this.portable?null:f.gname,this.size=f.size,this.mtime=this.noMtime?null:W.mtime||f.mtime,this.atime=this.portable?null:f.atime,this.ctime=this.portable?null:f.ctime,this.linkpath=p2(f.linkpath),typeof W.onwarn==="function")this.on("warn",W.onwarn);let J=!1;if(!this.preservePaths){let[Z,X]=Yb(this.path);if(Z)this.path=X,J=Z}if(this.remain=f.size,this.blockRemain=f.startBlockSize,this.header=new zb({path:this[s2](this.path),linkpath:this.type==="Link"?this[s2](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?null:this.uid,gid:this.portable?null:this.gid,size:this.size,mtime:this.noMtime?null:this.mtime,type:this.type,uname:this.portable?null:this.uname,atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime}),J)this.warn("TAR_ENTRY_INFO",`stripping ${J} from absolute path`,{entry:this,path:J+this.path});if(this.header.encode()&&!this.noPax)super.write(new Xb({atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime,gid:this.portable?null:this.gid,mtime:this.noMtime?null:this.mtime,path:this[s2](this.path),linkpath:this.type==="Link"?this[s2](this.linkpath):this.linkpath,size:this.size,uid:this.portable?null:this.uid,uname:this.portable?null:this.uname,dev:this.portable?null:this.readEntry.dev,ino:this.portable?null:this.readEntry.ino,nlink:this.portable?null:this.readEntry.nlink}).encode());super.write(this.header.block),f.pipe(this)}[s2](f){return wb(f,this.prefix)}[xL](f){return Lb(f,this.type==="Directory",this.portable)}write(f){let W=f.length;if(W>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=W,super.write(f)}end(){if(this.blockRemain)super.write(Buffer.alloc(this.blockRemain));return super.end()}});_L.Sync=Kb;_L.Tar=H60;var U60=($)=>$.isFile()?"File":$.isDirectory()?"Directory":$.isSymbolicLink()?"SymbolicLink":"Unsupported";Hb.exports=_L});var Rb=d((Fe0,Ub)=>{Ub.exports=function($){$.prototype[Symbol.iterator]=function*(){for(let f=this.head;f;f=f.next)yield f.value}}});var NA=d((Be0,Mb)=>{Mb.exports=I0;I0.Node=u5;I0.create=I0;function I0($){var f=this;if(!(f instanceof I0))f=new I0;if(f.tail=null,f.head=null,f.length=0,$&&typeof $.forEach==="function")$.forEach(function(Z){f.push(Z)});else if(arguments.length>0)for(var W=0,J=arguments.length;W<J;W++)f.push(arguments[W]);return f}I0.prototype.removeNode=function($){if($.list!==this)throw new Error("removing node which does not belong to this list");var{next:f,prev:W}=$;if(f)f.prev=W;if(W)W.next=f;if($===this.head)this.head=f;if($===this.tail)this.tail=W;return $.list.length--,$.next=null,$.prev=null,$.list=null,f};I0.prototype.unshiftNode=function($){if($===this.head)return;if($.list)$.list.removeNode($);var f=this.head;if($.list=this,$.next=f,f)f.prev=$;if(this.head=$,!this.tail)this.tail=$;this.length++};I0.prototype.pushNode=function($){if($===this.tail)return;if($.list)$.list.removeNode($);var f=this.tail;if($.list=this,$.prev=f,f)f.next=$;if(this.tail=$,!this.head)this.head=$;this.length++};I0.prototype.push=function(){for(var $=0,f=arguments.length;$<f;$++)M60(this,arguments[$]);return this.length};I0.prototype.unshift=function(){for(var $=0,f=arguments.length;$<f;$++)q60(this,arguments[$]);return this.length};I0.prototype.pop=function(){if(!this.tail)return;var $=this.tail.value;if(this.tail=this.tail.prev,this.tail)this.tail.next=null;else this.head=null;return this.length--,$};I0.prototype.shift=function(){if(!this.head)return;var $=this.head.value;if(this.head=this.head.next,this.head)this.head.prev=null;else this.tail=null;return this.length--,$};I0.prototype.forEach=function($,f){f=f||this;for(var W=this.head,J=0;W!==null;J++)$.call(f,W.value,J,this),W=W.next};I0.prototype.forEachReverse=function($,f){f=f||this;for(var W=this.tail,J=this.length-1;W!==null;J--)$.call(f,W.value,J,this),W=W.prev};I0.prototype.get=function($){for(var f=0,W=this.head;W!==null&&f<$;f++)W=W.next;if(f===$&&W!==null)return W.value};I0.prototype.getReverse=function($){for(var f=0,W=this.tail;W!==null&&f<$;f++)W=W.prev;if(f===$&&W!==null)return W.value};I0.prototype.map=function($,f){f=f||this;var W=new I0;for(var J=this.head;J!==null;)W.push($.call(f,J.value,this)),J=J.next;return W};I0.prototype.mapReverse=function($,f){f=f||this;var W=new I0;for(var J=this.tail;J!==null;)W.push($.call(f,J.value,this)),J=J.prev;return W};I0.prototype.reduce=function($,f){var W,J=this.head;if(arguments.length>1)W=f;else if(this.head)J=this.head.next,W=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var Z=0;J!==null;Z++)W=$(W,J.value,Z),J=J.next;return W};I0.prototype.reduceReverse=function($,f){var W,J=this.tail;if(arguments.length>1)W=f;else if(this.tail)J=this.tail.prev,W=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var Z=this.length-1;J!==null;Z--)W=$(W,J.value,Z),J=J.prev;return W};I0.prototype.toArray=function(){var $=new Array(this.length);for(var f=0,W=this.head;W!==null;f++)$[f]=W.value,W=W.next;return $};I0.prototype.toArrayReverse=function(){var $=new Array(this.length);for(var f=0,W=this.tail;W!==null;f++)$[f]=W.value,W=W.prev;return $};I0.prototype.slice=function($,f){if(f=f||this.length,f<0)f+=this.length;if($=$||0,$<0)$+=this.length;var W=new I0;if(f<$||f<0)return W;if($<0)$=0;if(f>this.length)f=this.length;for(var J=0,Z=this.head;Z!==null&&J<$;J++)Z=Z.next;for(;Z!==null&&J<f;J++,Z=Z.next)W.push(Z.value);return W};I0.prototype.sliceReverse=function($,f){if(f=f||this.length,f<0)f+=this.length;if($=$||0,$<0)$+=this.length;var W=new I0;if(f<$||f<0)return W;if($<0)$=0;if(f>this.length)f=this.length;for(var J=this.length,Z=this.tail;Z!==null&&J>f;J--)Z=Z.prev;for(;Z!==null&&J>$;J--,Z=Z.prev)W.push(Z.value);return W};I0.prototype.splice=function($,f,...W){if($>this.length)$=this.length-1;if($<0)$=this.length+$;for(var J=0,Z=this.head;Z!==null&&J<$;J++)Z=Z.next;var X=[];for(var J=0;Z&&J<f;J++)X.push(Z.value),Z=this.removeNode(Z);if(Z===null)Z=this.tail;if(Z!==this.head&&Z!==this.tail)Z=Z.prev;for(var J=0;J<W.length;J++)Z=R60(this,Z,W[J]);return X};I0.prototype.reverse=function(){var $=this.head,f=this.tail;for(var W=$;W!==null;W=W.prev){var J=W.prev;W.prev=W.next,W.next=J}return this.head=f,this.tail=$,this};function R60($,f,W){var J=f===$.head?new u5(W,null,f,$):new u5(W,f,f.next,$);if(J.next===null)$.tail=J;if(J.prev===null)$.head=J;return $.length++,J}function M60($,f){if($.tail=new u5(f,$.tail,null,$),!$.head)$.head=$.tail;$.length++}function q60($,f){if($.head=new u5(f,null,$.head,$),!$.tail)$.tail=$.head;$.length++}function u5($,f,W,J){if(!(this instanceof u5))return new u5($,f,W,J);if(this.list=J,this.value=$,f)f.next=this,this.prev=f;else this.prev=null;if(W)W.prev=this,this.next=W;else this.next=null}try{Rb()(I0)}catch($){}});var EL=d((Te0,Nb)=>{class PA{constructor($,f){this.path=$||"./",this.absolute=f,this.entry=null,this.stat=null,this.readdir=null,this.pending=!1,this.ignore=!1,this.piped=!1}}var{Minipass:V60}=YL(),qb=ZA(),Q60=ML(),DA=_A(),I60=DA.Sync,O60=DA.Tar,A60=NA(),Vb=Buffer.alloc(1024),FL=Symbol("onStat"),NL=Symbol("ended"),t2=Symbol("queue"),zJ=Symbol("current"),c5=Symbol("process"),SL=Symbol("processing"),Qb=Symbol("processJob"),a2=Symbol("jobs"),SA=Symbol("jobDone"),BL=Symbol("addFSEntry"),Ib=Symbol("addTarEntry"),CA=Symbol("stat"),EA=Symbol("readdir"),TL=Symbol("onreaddir"),PL=Symbol("pipe"),Ob=Symbol("entry"),FA=Symbol("entryOpt"),hA=Symbol("writeEntryClass"),xb=Symbol("write"),BA=Symbol("ondrain"),CL=u("fs"),Ab=u("path"),x60=QL(),TA=WJ(),vA=x60(class $ extends V60{constructor(f){super(f);if(f=f||Object.create(null),this.opt=f,this.file=f.file||"",this.cwd=f.cwd||process.cwd(),this.maxReadSize=f.maxReadSize,this.preservePaths=!!f.preservePaths,this.strict=!!f.strict,this.noPax=!!f.noPax,this.prefix=TA(f.prefix||""),this.linkCache=f.linkCache||new Map,this.statCache=f.statCache||new Map,this.readdirCache=f.readdirCache||new Map,this[hA]=DA,typeof f.onwarn==="function")this.on("warn",f.onwarn);if(this.portable=!!f.portable,this.zip=null,f.gzip||f.brotli){if(f.gzip&&f.brotli)throw new TypeError("gzip and brotli are mutually exclusive");if(f.gzip){if(typeof f.gzip!=="object")f.gzip={};if(this.portable)f.gzip.portable=!0;this.zip=new qb.Gzip(f.gzip)}if(f.brotli){if(typeof f.brotli!=="object")f.brotli={};this.zip=new qb.BrotliCompress(f.brotli)}this.zip.on("data",(W)=>super.write(W)),this.zip.on("end",(W)=>super.end()),this.zip.on("drain",(W)=>this[BA]()),this.on("resume",(W)=>this.zip.resume())}else this.on("drain",this[BA]);this.noDirRecurse=!!f.noDirRecurse,this.follow=!!f.follow,this.noMtime=!!f.noMtime,this.mtime=f.mtime||null,this.filter=typeof f.filter==="function"?f.filter:(W)=>!0,this[t2]=new A60,this[a2]=0,this.jobs=+f.jobs||4,this[SL]=!1,this[NL]=!1}[xb](f){return super.write(f)}add(f){return this.write(f),this}end(f){if(f)this.write(f);return this[NL]=!0,this[c5](),this}write(f){if(this[NL])throw new Error("write after end");if(f instanceof Q60)this[Ib](f);else this[BL](f);return this.flowing}[Ib](f){let W=TA(Ab.resolve(this.cwd,f.path));if(!this.filter(f.path,f))f.resume();else{let J=new PA(f.path,W,!1);J.entry=new O60(f,this[FA](J)),J.entry.on("end",(Z)=>this[SA](J)),this[a2]+=1,this[t2].push(J)}this[c5]()}[BL](f){let W=TA(Ab.resolve(this.cwd,f));this[t2].push(new PA(f,W)),this[c5]()}[CA](f){f.pending=!0,this[a2]+=1;let W=this.follow?"stat":"lstat";CL[W](f.absolute,(J,Z)=>{if(f.pending=!1,this[a2]-=1,J)this.emit("error",J);else this[FL](f,Z)})}[FL](f,W){if(this.statCache.set(f.absolute,W),f.stat=W,!this.filter(f.path,W))f.ignore=!0;this[c5]()}[EA](f){f.pending=!0,this[a2]+=1,CL.readdir(f.absolute,(W,J)=>{if(f.pending=!1,this[a2]-=1,W)return this.emit("error",W);this[TL](f,J)})}[TL](f,W){this.readdirCache.set(f.absolute,W),f.readdir=W,this[c5]()}[c5](){if(this[SL])return;this[SL]=!0;for(let f=this[t2].head;f!==null&&this[a2]<this.jobs;f=f.next)if(this[Qb](f.value),f.value.ignore){let W=f.next;this[t2].removeNode(f),f.next=W}if(this[SL]=!1,this[NL]&&!this[t2].length&&this[a2]===0)if(this.zip)this.zip.end(Vb);else super.write(Vb),super.end()}get[zJ](){return this[t2]&&this[t2].head&&this[t2].head.value}[SA](f){this[t2].shift(),this[a2]-=1,this[c5]()}[Qb](f){if(f.pending)return;if(f.entry){if(f===this[zJ]&&!f.piped)this[PL](f);return}if(!f.stat)if(this.statCache.has(f.absolute))this[FL](f,this.statCache.get(f.absolute));else this[CA](f);if(!f.stat)return;if(f.ignore)return;if(!this.noDirRecurse&&f.stat.isDirectory()&&!f.readdir){if(this.readdirCache.has(f.absolute))this[TL](f,this.readdirCache.get(f.absolute));else this[EA](f);if(!f.readdir)return}if(f.entry=this[Ob](f),!f.entry){f.ignore=!0;return}if(f===this[zJ]&&!f.piped)this[PL](f)}[FA](f){return{onwarn:(W,J,Z)=>this.warn(W,J,Z),noPax:this.noPax,cwd:this.cwd,absolute:f.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix}}[Ob](f){this[a2]+=1;try{return new this[hA](f.path,this[FA](f)).on("end",()=>this[SA](f)).on("error",(W)=>this.emit("error",W))}catch(W){this.emit("error",W)}}[BA](){if(this[zJ]&&this[zJ].entry)this[zJ].entry.resume()}[PL](f){if(f.piped=!0,f.readdir)f.readdir.forEach((Z)=>{let X=f.path,z=X==="./"?"":X.replace(/\/*$/,"/");this[BL](z+Z)});let W=f.entry,J=this.zip;if(J)W.on("data",(Z)=>{if(!J.write(Z))W.pause()});else W.on("data",(Z)=>{if(!super.write(Z))W.pause()})}pause(){if(this.zip)this.zip.pause();return super.pause()}});class _b extends vA{constructor($){super($);this[hA]=I60}pause(){}resume(){}[CA]($){let f=this.follow?"statSync":"lstatSync";this[FL]($,CL[f]($.absolute))}[EA]($,f){this[TL]($,CL.readdirSync($.absolute))}[PL]($){let f=$.entry,W=this.zip;if($.readdir)$.readdir.forEach((J)=>{let Z=$.path,X=Z==="./"?"":Z.replace(/\/*$/,"/");this[BL](X+J)});if(W)f.on("data",(J)=>{W.write(J)});else f.on("data",(J)=>{super[xb](J)})}}vA.Sync=_b;Nb.exports=vA});var vb=d((Pe0,Db)=>{var Sb=typeof process==="object"&&process?process:{stdout:null,stderr:null},_60=u("events"),Fb=u("stream"),Bb=u("string_decoder").StringDecoder,e9=Symbol("EOF"),$4=Symbol("maybeEmitEnd"),Z6=Symbol("emittedEnd"),hL=Symbol("emittingEnd"),SX=Symbol("emittedError"),DL=Symbol("closed"),Tb=Symbol("read"),vL=Symbol("flush"),Pb=Symbol("flushChunk"),v$=Symbol("encoding"),f4=Symbol("decoder"),mL=Symbol("flowing"),FX=Symbol("paused"),wJ=Symbol("resume"),m1=Symbol("bufferLength"),mA=Symbol("bufferPush"),kA=Symbol("bufferShift"),X$=Symbol("objectMode"),z$=Symbol("destroyed"),yA=Symbol("emitData"),Cb=Symbol("emitEnd"),jA=Symbol("emitEnd2"),W4=Symbol("async"),BX=($)=>Promise.resolve().then($),Eb=global._MP_NO_ITERATOR_SYMBOLS_!=="1",N60=Eb&&Symbol.asyncIterator||Symbol("asyncIterator not implemented"),S60=Eb&&Symbol.iterator||Symbol("iterator not implemented"),F60=($)=>$==="end"||$==="finish"||$==="prefinish",B60=($)=>$ instanceof ArrayBuffer||typeof $==="object"&&$.constructor&&$.constructor.name==="ArrayBuffer"&&$.byteLength>=0,T60=($)=>!Buffer.isBuffer($)&&ArrayBuffer.isView($);class gA{constructor($,f,W){this.src=$,this.dest=f,this.opts=W,this.ondrain=()=>$[wJ](),f.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(){}end(){if(this.unpipe(),this.opts.end)this.dest.end()}}class hb extends gA{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor($,f,W){super($,f,W);this.proxyErrors=(J)=>f.emit("error",J),$.on("error",this.proxyErrors)}}Db.exports=class $ extends Fb{constructor(f){super();if(this[mL]=!1,this[FX]=!1,this.pipes=[],this.buffer=[],this[X$]=f&&f.objectMode||!1,this[X$])this[v$]=null;else this[v$]=f&&f.encoding||null;if(this[v$]==="buffer")this[v$]=null;this[W4]=f&&!!f.async||!1,this[f4]=this[v$]?new Bb(this[v$]):null,this[e9]=!1,this[Z6]=!1,this[hL]=!1,this[DL]=!1,this[SX]=null,this.writable=!0,this.readable=!0,this[m1]=0,this[z$]=!1}get bufferLength(){return this[m1]}get encoding(){return this[v$]}set encoding(f){if(this[X$])throw new Error("cannot set encoding in objectMode");if(this[v$]&&f!==this[v$]&&(this[f4]&&this[f4].lastNeed||this[m1]))throw new Error("cannot change encoding");if(this[v$]!==f){if(this[f4]=f?new Bb(f):null,this.buffer.length)this.buffer=this.buffer.map((W)=>this[f4].write(W))}this[v$]=f}setEncoding(f){this.encoding=f}get objectMode(){return this[X$]}set objectMode(f){this[X$]=this[X$]||!!f}get["async"](){return this[W4]}set["async"](f){this[W4]=this[W4]||!!f}write(f,W,J){if(this[e9])throw new Error("write after end");if(this[z$])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;if(typeof W==="function")J=W,W="utf8";if(!W)W="utf8";let Z=this[W4]?BX:(X)=>X();if(!this[X$]&&!Buffer.isBuffer(f)){if(T60(f))f=Buffer.from(f.buffer,f.byteOffset,f.byteLength);else if(B60(f))f=Buffer.from(f);else if(typeof f!=="string")this.objectMode=!0}if(this[X$]){if(this.flowing&&this[m1]!==0)this[vL](!0);if(this.flowing)this.emit("data",f);else this[mA](f);if(this[m1]!==0)this.emit("readable");if(J)Z(J);return this.flowing}if(!f.length){if(this[m1]!==0)this.emit("readable");if(J)Z(J);return this.flowing}if(typeof f==="string"&&!(W===this[v$]&&!this[f4].lastNeed))f=Buffer.from(f,W);if(Buffer.isBuffer(f)&&this[v$])f=this[f4].write(f);if(this.flowing&&this[m1]!==0)this[vL](!0);if(this.flowing)this.emit("data",f);else this[mA](f);if(this[m1]!==0)this.emit("readable");if(J)Z(J);return this.flowing}read(f){if(this[z$])return null;if(this[m1]===0||f===0||f>this[m1])return this[$4](),null;if(this[X$])f=null;if(this.buffer.length>1&&!this[X$])if(this.encoding)this.buffer=[this.buffer.join("")];else this.buffer=[Buffer.concat(this.buffer,this[m1])];let W=this[Tb](f||null,this.buffer[0]);return this[$4](),W}[Tb](f,W){if(f===W.length||f===null)this[kA]();else this.buffer[0]=W.slice(f),W=W.slice(0,f),this[m1]-=f;if(this.emit("data",W),!this.buffer.length&&!this[e9])this.emit("drain");return W}end(f,W,J){if(typeof f==="function")J=f,f=null;if(typeof W==="function")J=W,W="utf8";if(f)this.write(f,W);if(J)this.once("end",J);if(this[e9]=!0,this.writable=!1,this.flowing||!this[FX])this[$4]();return this}[wJ](){if(this[z$])return;if(this[FX]=!1,this[mL]=!0,this.emit("resume"),this.buffer.length)this[vL]();else if(this[e9])this[$4]();else this.emit("drain")}resume(){return this[wJ]()}pause(){this[mL]=!1,this[FX]=!0}get destroyed(){return this[z$]}get flowing(){return this[mL]}get paused(){return this[FX]}[mA](f){if(this[X$])this[m1]+=1;else this[m1]+=f.length;this.buffer.push(f)}[kA](){if(this.buffer.length)if(this[X$])this[m1]-=1;else this[m1]-=this.buffer[0].length;return this.buffer.shift()}[vL](f){do;while(this[Pb](this[kA]()));if(!f&&!this.buffer.length&&!this[e9])this.emit("drain")}[Pb](f){return f?(this.emit("data",f),this.flowing):!1}pipe(f,W){if(this[z$])return;let J=this[Z6];if(W=W||{},f===Sb.stdout||f===Sb.stderr)W.end=!1;else W.end=W.end!==!1;if(W.proxyErrors=!!W.proxyErrors,J){if(W.end)f.end()}else if(this.pipes.push(!W.proxyErrors?new gA(this,f,W):new hb(this,f,W)),this[W4])BX(()=>this[wJ]());else this[wJ]();return f}unpipe(f){let W=this.pipes.find((J)=>J.dest===f);if(W)this.pipes.splice(this.pipes.indexOf(W),1),W.unpipe()}addListener(f,W){return this.on(f,W)}on(f,W){let J=super.on(f,W);if(f==="data"&&!this.pipes.length&&!this.flowing)this[wJ]();else if(f==="readable"&&this[m1]!==0)super.emit("readable");else if(F60(f)&&this[Z6])super.emit(f),this.removeAllListeners(f);else if(f==="error"&&this[SX])if(this[W4])BX(()=>W.call(this,this[SX]));else W.call(this,this[SX]);return J}get emittedEnd(){return this[Z6]}[$4](){if(!this[hL]&&!this[Z6]&&!this[z$]&&this.buffer.length===0&&this[e9]){if(this[hL]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[DL])this.emit("close");this[hL]=!1}}emit(f,W,...J){if(f!=="error"&&f!=="close"&&f!==z$&&this[z$])return;else if(f==="data")return!W?!1:this[W4]?BX(()=>this[yA](W)):this[yA](W);else if(f==="end")return this[Cb]();else if(f==="close"){if(this[DL]=!0,!this[Z6]&&!this[z$])return;let X=super.emit("close");return this.removeAllListeners("close"),X}else if(f==="error"){this[SX]=W;let X=super.emit("error",W);return this[$4](),X}else if(f==="resume"){let X=super.emit("resume");return this[$4](),X}else if(f==="finish"||f==="prefinish"){let X=super.emit(f);return this.removeAllListeners(f),X}let Z=super.emit(f,W,...J);return this[$4](),Z}[yA](f){for(let J of this.pipes)if(J.dest.write(f)===!1)this.pause();let W=super.emit("data",f);return this[$4](),W}[Cb](){if(this[Z6])return;if(this[Z6]=!0,this.readable=!1,this[W4])BX(()=>this[jA]());else this[jA]()}[jA](){if(this[f4]){let W=this[f4].end();if(W){for(let J of this.pipes)J.dest.write(W);super.emit("data",W)}}for(let W of this.pipes)W.end();let f=super.emit("end");return this.removeAllListeners("end"),f}collect(){let f=[];if(!this[X$])f.dataLength=0;let W=this.promise();return this.on("data",(J)=>{if(f.push(J),!this[X$])f.dataLength+=J.length}),W.then(()=>f)}concat(){return this[X$]?Promise.reject(new Error("cannot concat in objectMode")):this.collect().then((f)=>this[X$]?Promise.reject(new Error("cannot concat in objectMode")):this[v$]?f.join(""):Buffer.concat(f,f.dataLength))}promise(){return new Promise((f,W)=>{this.on(z$,()=>W(new Error("stream destroyed"))),this.on("error",(J)=>W(J)),this.on("end",()=>f())})}[N60](){return{next:()=>{let W=this.read();if(W!==null)return Promise.resolve({done:!1,value:W});if(this[e9])return Promise.resolve({done:!0});let J=null,Z=null,X=(Y)=>{this.removeListener("data",z),this.removeListener("end",w),Z(Y)},z=(Y)=>{this.removeListener("error",X),this.removeListener("end",w),this.pause(),J({value:Y,done:!!this[e9]})},w=()=>{this.removeListener("error",X),this.removeListener("data",z),J({done:!0})},G=()=>X(new Error("stream destroyed"));return new Promise((Y,L)=>{Z=L,J=Y,this.once(z$,G),this.once("error",X),this.once("end",w),this.once("data",z)})}}}[S60](){return{next:()=>{let W=this.read();return{value:W,done:W===null}}}}destroy(f){if(this[z$]){if(f)this.emit("error",f);else this.emit(z$);return this}if(this[z$]=!0,this.buffer.length=0,this[m1]=0,typeof this.close==="function"&&!this[DL])this.close();if(f)this.emit("error",f);else this.emit(z$);return this}static isStream(f){return!!f&&(f instanceof $||f instanceof Fb||f instanceof _60&&(typeof f.pipe==="function"||typeof f.write==="function"&&typeof f.end==="function"))}}});var MJ=d((E60)=>{var P60=vb(),C60=u("events").EventEmitter,m$=u("fs"),cA=m$.writev;if(!cA){let $=process.binding("fs"),f=$.FSReqWrap||$.FSReqCallback;cA=(W,J,Z,X)=>{let z=(G,Y)=>X(G,Y,J),w=new f;w.oncomplete=z,$.writeBuffers(W,J,Z,w)}}var UJ=Symbol("_autoClose"),w2=Symbol("_close"),TX=Symbol("_ended"),m0=Symbol("_fd"),mb=Symbol("_finished"),z6=Symbol("_flags"),bA=Symbol("_flush"),dA=Symbol("_handleChunk"),iA=Symbol("_makeBuf"),bL=Symbol("_mode"),kL=Symbol("_needDrain"),KJ=Symbol("_onerror"),RJ=Symbol("_onopen"),uA=Symbol("_onread"),YJ=Symbol("_onwrite"),w6=Symbol("_open"),J4=Symbol("_path"),d5=Symbol("_pos"),o2=Symbol("_queue"),LJ=Symbol("_read"),kb=Symbol("_readSize"),X6=Symbol("_reading"),yL=Symbol("_remain"),yb=Symbol("_size"),jL=Symbol("_write"),GJ=Symbol("_writing"),gL=Symbol("_defaultFlag"),HJ=Symbol("_errored");class rA extends P60{constructor($,f){f=f||{};super(f);if(this.readable=!0,this.writable=!1,typeof $!=="string")throw new TypeError("path must be a string");if(this[HJ]=!1,this[m0]=typeof f.fd==="number"?f.fd:null,this[J4]=$,this[kb]=f.readSize||16777216,this[X6]=!1,this[yb]=typeof f.size==="number"?f.size:1/0,this[yL]=this[yb],this[UJ]=typeof f.autoClose==="boolean"?f.autoClose:!0,typeof this[m0]==="number")this[LJ]();else this[w6]()}get fd(){return this[m0]}get path(){return this[J4]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[w6](){m$.open(this[J4],"r",($,f)=>this[RJ]($,f))}[RJ]($,f){if($)this[KJ]($);else this[m0]=f,this.emit("open",f),this[LJ]()}[iA](){return Buffer.allocUnsafe(Math.min(this[kb],this[yL]))}[LJ](){if(!this[X6]){this[X6]=!0;let $=this[iA]();if($.length===0)return process.nextTick(()=>this[uA](null,0,$));m$.read(this[m0],$,0,$.length,null,(f,W,J)=>this[uA](f,W,J))}}[uA]($,f,W){if(this[X6]=!1,$)this[KJ]($);else if(this[dA](f,W))this[LJ]()}[w2](){if(this[UJ]&&typeof this[m0]==="number"){let $=this[m0];this[m0]=null,m$.close($,(f)=>f?this.emit("error",f):this.emit("close"))}}[KJ]($){this[X6]=!0,this[w2](),this.emit("error",$)}[dA]($,f){let W=!1;if(this[yL]-=$,$>0)W=super.write($<f.length?f.slice(0,$):f);if($===0||this[yL]<=0)W=!1,this[w2](),super.end();return W}emit($,f){switch($){case"prefinish":case"finish":break;case"drain":if(typeof this[m0]==="number")this[LJ]();break;case"error":if(this[HJ])return;return this[HJ]=!0,super.emit($,f);default:return super.emit($,f)}}}class jb extends rA{[w6](){let $=!0;try{this[RJ](null,m$.openSync(this[J4],"r")),$=!1}finally{if($)this[w2]()}}[LJ](){let $=!0;try{if(!this[X6]){this[X6]=!0;do{let f=this[iA](),W=f.length===0?0:m$.readSync(this[m0],f,0,f.length,null);if(!this[dA](W,f))break}while(!0);this[X6]=!1}$=!1}finally{if($)this[w2]()}}[w2](){if(this[UJ]&&typeof this[m0]==="number"){let $=this[m0];this[m0]=null,m$.closeSync($),this.emit("close")}}}class lA extends C60{constructor($,f){f=f||{};super(f);this.readable=!1,this.writable=!0,this[HJ]=!1,this[GJ]=!1,this[TX]=!1,this[kL]=!1,this[o2]=[],this[J4]=$,this[m0]=typeof f.fd==="number"?f.fd:null,this[bL]=f.mode===void 0?438:f.mode,this[d5]=typeof f.start==="number"?f.start:null,this[UJ]=typeof f.autoClose==="boolean"?f.autoClose:!0;let W=this[d5]!==null?"r+":"w";if(this[gL]=f.flags===void 0,this[z6]=this[gL]?W:f.flags,this[m0]===null)this[w6]()}emit($,f){if($==="error"){if(this[HJ])return;this[HJ]=!0}return super.emit($,f)}get fd(){return this[m0]}get path(){return this[J4]}[KJ]($){this[w2](),this[GJ]=!0,this.emit("error",$)}[w6](){m$.open(this[J4],this[z6],this[bL],($,f)=>this[RJ]($,f))}[RJ]($,f){if(this[gL]&&this[z6]==="r+"&&$&&$.code==="ENOENT")this[z6]="w",this[w6]();else if($)this[KJ]($);else this[m0]=f,this.emit("open",f),this[bA]()}end($,f){if($)this.write($,f);if(this[TX]=!0,!this[GJ]&&!this[o2].length&&typeof this[m0]==="number")this[YJ](null,0);return this}write($,f){if(typeof $==="string")$=Buffer.from($,f);if(this[TX])return this.emit("error",new Error("write() after end()")),!1;if(this[m0]===null||this[GJ]||this[o2].length)return this[o2].push($),this[kL]=!0,!1;return this[GJ]=!0,this[jL]($),!0}[jL]($){m$.write(this[m0],$,0,$.length,this[d5],(f,W)=>this[YJ](f,W))}[YJ]($,f){if($)this[KJ]($);else{if(this[d5]!==null)this[d5]+=f;if(this[o2].length)this[bA]();else if(this[GJ]=!1,this[TX]&&!this[mb])this[mb]=!0,this[w2](),this.emit("finish");else if(this[kL])this[kL]=!1,this.emit("drain")}}[bA](){if(this[o2].length===0){if(this[TX])this[YJ](null,0)}else if(this[o2].length===1)this[jL](this[o2].pop());else{let $=this[o2];this[o2]=[],cA(this[m0],$,this[d5],(f,W)=>this[YJ](f,W))}}[w2](){if(this[UJ]&&typeof this[m0]==="number"){let $=this[m0];this[m0]=null,m$.close($,(f)=>f?this.emit("error",f):this.emit("close"))}}}class gb extends lA{[w6](){let $;if(this[gL]&&this[z6]==="r+")try{$=m$.openSync(this[J4],this[z6],this[bL])}catch(f){if(f.code==="ENOENT")return this[z6]="w",this[w6]();else throw f}else $=m$.openSync(this[J4],this[z6],this[bL]);this[RJ](null,$)}[w2](){if(this[UJ]&&typeof this[m0]==="number"){let $=this[m0];this[m0]=null,m$.closeSync($),this.emit("close")}}[jL]($){let f=!0;try{this[YJ](null,m$.writeSync(this[m0],$,0,$.length,this[d5])),f=!1}finally{if(f)try{this[w2]()}catch(W){}}}}E60.ReadStream=rA;E60.ReadStreamSync=jb;E60.WriteStream=lA;E60.WriteStreamSync=gb});var pL=d((Ee0,sb)=>{var k60=QL(),bb=ZJ(),y60=u("events"),j60=NA(),g60=ML(),ub=VL(),cb=ZA(),{nextTick:b60}=u("process"),pA=Buffer.from([31,139]),_f=Symbol("state"),i5=Symbol("writeEntry"),Z4=Symbol("readEntry"),nA=Symbol("nextEntry"),db=Symbol("processEntry"),Nf=Symbol("extendedHeader"),PX=Symbol("globalExtendedHeader"),G6=Symbol("meta"),ib=Symbol("emitMeta"),c0=Symbol("buffer"),X4=Symbol("queue"),Y6=Symbol("ended"),rb=Symbol("emittedEnd"),r5=Symbol("emit"),k1=Symbol("unzip"),uL=Symbol("consumeChunk"),cL=Symbol("consumeChunkSub"),sA=Symbol("consumeBody"),lb=Symbol("consumeMeta"),pb=Symbol("consumeHeader"),dL=Symbol("consuming"),tA=Symbol("bufferConcat"),aA=Symbol("maybeEnd"),CX=Symbol("writing"),L6=Symbol("aborted"),iL=Symbol("onDone"),l5=Symbol("sawValidEntry"),rL=Symbol("sawNullBlock"),lL=Symbol("sawEOF"),nb=Symbol("closeStream"),u60=($)=>!0;sb.exports=k60(class $ extends y60{constructor(f){f=f||{};super(f);if(this.file=f.file||"",this[l5]=null,this.on(iL,(J)=>{if(this[_f]==="begin"||this[l5]===!1)this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),f.ondone)this.on(iL,f.ondone);else this.on(iL,(J)=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")});this.strict=!!f.strict,this.maxMetaEntrySize=f.maxMetaEntrySize||1048576,this.filter=typeof f.filter==="function"?f.filter:u60;let W=f.file&&(f.file.endsWith(".tar.br")||f.file.endsWith(".tbr"));if(this.brotli=!f.gzip&&f.brotli!==void 0?f.brotli:W?void 0:!1,this.writable=!0,this.readable=!1,this[X4]=new j60,this[c0]=null,this[Z4]=null,this[i5]=null,this[_f]="begin",this[G6]="",this[Nf]=null,this[PX]=null,this[Y6]=!1,this[k1]=null,this[L6]=!1,this[rL]=!1,this[lL]=!1,this.on("end",()=>this[nb]()),typeof f.onwarn==="function")this.on("warn",f.onwarn);if(typeof f.onentry==="function")this.on("entry",f.onentry)}[pb](f,W){if(this[l5]===null)this[l5]=!1;let J;try{J=new bb(f,W,this[Nf],this[PX])}catch(Z){return this.warn("TAR_ENTRY_INVALID",Z)}if(J.nullBlock)if(this[rL]){if(this[lL]=!0,this[_f]==="begin")this[_f]="header";this[r5]("eof")}else this[rL]=!0,this[r5]("nullBlock");else if(this[rL]=!1,!J.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:J});else if(!J.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:J});else{let Z=J.type;if(/^(Symbolic)?Link$/.test(Z)&&!J.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:J});else if(!/^(Symbolic)?Link$/.test(Z)&&J.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:J});else{let X=this[i5]=new g60(J,this[Nf],this[PX]);if(!this[l5])if(X.remain){let z=()=>{if(!X.invalid)this[l5]=!0};X.on("end",z)}else this[l5]=!0;if(X.meta){if(X.size>this.maxMetaEntrySize)X.ignore=!0,this[r5]("ignoredEntry",X),this[_f]="ignore",X.resume();else if(X.size>0)this[G6]="",X.on("data",(z)=>this[G6]+=z),this[_f]="meta"}else if(this[Nf]=null,X.ignore=X.ignore||!this.filter(X.path,X),X.ignore)this[r5]("ignoredEntry",X),this[_f]=X.remain?"ignore":"header",X.resume();else{if(X.remain)this[_f]="body";else this[_f]="header",X.end();if(!this[Z4])this[X4].push(X),this[nA]();else this[X4].push(X)}}}}[nb](){b60(()=>this.emit("close"))}[db](f){let W=!0;if(!f)this[Z4]=null,W=!1;else if(Array.isArray(f))this.emit.apply(this,f);else if(this[Z4]=f,this.emit("entry",f),!f.emittedEnd)f.on("end",(J)=>this[nA]()),W=!1;return W}[nA](){do;while(this[db](this[X4].shift()));if(!this[X4].length){let f=this[Z4];if(!f||f.flowing||f.size===f.remain){if(!this[CX])this.emit("drain")}else f.once("drain",(J)=>this.emit("drain"))}}[sA](f,W){let J=this[i5],Z=J.blockRemain,X=Z>=f.length&&W===0?f:f.slice(W,W+Z);if(J.write(X),!J.blockRemain)this[_f]="header",this[i5]=null,J.end();return X.length}[lb](f,W){let J=this[i5],Z=this[sA](f,W);if(!this[i5])this[ib](J);return Z}[r5](f,W,J){if(!this[X4].length&&!this[Z4])this.emit(f,W,J);else this[X4].push([f,W,J])}[ib](f){switch(this[r5]("meta",this[G6]),f.type){case"ExtendedHeader":case"OldExtendedHeader":this[Nf]=ub.parse(this[G6],this[Nf],!1);break;case"GlobalExtendedHeader":this[PX]=ub.parse(this[G6],this[PX],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":this[Nf]=this[Nf]||Object.create(null),this[Nf].path=this[G6].replace(/\0.*/,"");break;case"NextFileHasLongLinkpath":this[Nf]=this[Nf]||Object.create(null),this[Nf].linkpath=this[G6].replace(/\0.*/,"");break;default:throw new Error("unknown meta: "+f.type)}}abort(f){this[L6]=!0,this.emit("abort",f),this.warn("TAR_ABORT",f,{recoverable:!1})}write(f){if(this[L6])return;if((this[k1]===null||this.brotli===void 0&&this[k1]===!1)&&f){if(this[c0])f=Buffer.concat([this[c0],f]),this[c0]=null;if(f.length<pA.length)return this[c0]=f,!0;for(let X=0;this[k1]===null&&X<pA.length;X++)if(f[X]!==pA[X])this[k1]=!1;let Z=this.brotli===void 0;if(this[k1]===!1&&Z)if(f.length<512)if(this[Y6])this.brotli=!0;else return this[c0]=f,!0;else try{new bb(f.slice(0,512)),this.brotli=!1}catch(X){this.brotli=!0}if(this[k1]===null||this[k1]===!1&&this.brotli){let X=this[Y6];this[Y6]=!1,this[k1]=this[k1]===null?new cb.Unzip:new cb.BrotliDecompress,this[k1].on("data",(w)=>this[uL](w)),this[k1].on("error",(w)=>this.abort(w)),this[k1].on("end",(w)=>{this[Y6]=!0,this[uL]()}),this[CX]=!0;let z=this[k1][X?"end":"write"](f);return this[CX]=!1,z}}if(this[CX]=!0,this[k1])this[k1].write(f);else this[uL](f);this[CX]=!1;let J=this[X4].length?!1:this[Z4]?this[Z4].flowing:!0;if(!J&&!this[X4].length)this[Z4].once("drain",(Z)=>this.emit("drain"));return J}[tA](f){if(f&&!this[L6])this[c0]=this[c0]?Buffer.concat([this[c0],f]):f}[aA](){if(this[Y6]&&!this[rb]&&!this[L6]&&!this[dL]){this[rb]=!0;let f=this[i5];if(f&&f.blockRemain){let W=this[c0]?this[c0].length:0;if(this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${f.blockRemain} more bytes, only ${W} available)`,{entry:f}),this[c0])f.write(this[c0]);f.end()}this[r5](iL)}}[uL](f){if(this[dL])this[tA](f);else if(!f&&!this[c0])this[aA]();else{if(this[dL]=!0,this[c0]){this[tA](f);let W=this[c0];this[c0]=null,this[cL](W)}else this[cL](f);while(this[c0]&&this[c0].length>=512&&!this[L6]&&!this[lL]){let W=this[c0];this[c0]=null,this[cL](W)}this[dL]=!1}if(!this[c0]||this[Y6])this[aA]()}[cL](f){let W=0,J=f.length;while(W+512<=J&&!this[L6]&&!this[lL])switch(this[_f]){case"begin":case"header":this[pb](f,W),W+=512;break;case"ignore":case"body":W+=this[sA](f,W);break;case"meta":W+=this[lb](f,W);break;default:throw new Error("invalid state: "+this[_f])}if(W<J)if(this[c0])this[c0]=Buffer.concat([f.slice(W),this[c0]]);else this[c0]=f.slice(W)}end(f){if(!this[L6])if(this[k1])this[k1].end(f);else{if(this[Y6]=!0,this.brotli===void 0)f=f||Buffer.alloc(0);this.write(f)}}})});var nL=d((he0,eb)=>{var c60=oW(),ab=pL(),qJ=u("fs"),d60=MJ(),tb=u("path"),oA=XJ();eb.exports=($,f,W)=>{if(typeof $==="function")W=$,f=null,$={};else if(Array.isArray($))f=$,$={};if(typeof f==="function")W=f,f=null;if(!f)f=[];else f=Array.from(f);let J=c60($);if(J.sync&&typeof W==="function")throw new TypeError("callback not supported for sync tar functions");if(!J.file&&typeof W==="function")throw new TypeError("callback only supported with file option");if(f.length)r60(J,f);if(!J.noResume)i60(J);return J.file&&J.sync?l60(J):J.file?p60(J,W):ob(J)};var i60=($)=>{let f=$.onentry;$.onentry=f?(W)=>{f(W),W.resume()}:(W)=>W.resume()},r60=($,f)=>{let W=new Map(f.map((X)=>[oA(X),!0])),J=$.filter,Z=(X,z)=>{let w=z||tb.parse(X).root||".",G=X===w?!1:W.has(X)?W.get(X):Z(tb.dirname(X),w);return W.set(X,G),G};$.filter=J?(X,z)=>J(X,z)&&Z(oA(X)):(X)=>Z(oA(X))},l60=($)=>{let f=ob($),W=$.file,J=!0,Z;try{let X=qJ.statSync(W),z=$.maxReadSize||16777216;if(X.size<z)f.end(qJ.readFileSync(W));else{let w=0,G=Buffer.allocUnsafe(z);Z=qJ.openSync(W,"r");while(w<X.size){let Y=qJ.readSync(Z,G,0,z,w);w+=Y,f.write(G.slice(0,Y))}f.end()}J=!1}finally{if(J&&Z)try{qJ.closeSync(Z)}catch(X){}}},p60=($,f)=>{let W=new ab($),J=$.maxReadSize||16777216,Z=$.file,X=new Promise((z,w)=>{W.on("error",w),W.on("end",z),qJ.stat(Z,(G,Y)=>{if(G)w(G);else{let L=new d60.ReadStream(Z,{readSize:J,size:Y.size});L.on("error",w),L.pipe(W)}})});return f?X.then(f,f):X},ob=($)=>new ab($)});var Xu=d((De0,Zu)=>{var n60=oW(),sL=EL(),$u=MJ(),fu=nL(),Wu=u("path");Zu.exports=($,f,W)=>{if(typeof f==="function")W=f;if(Array.isArray($))f=$,$={};if(!f||!Array.isArray(f)||!f.length)throw new TypeError("no files or directories specified");f=Array.from(f);let J=n60($);if(J.sync&&typeof W==="function")throw new TypeError("callback not supported for sync tar functions");if(!J.file&&typeof W==="function")throw new TypeError("callback only supported with file option");return J.file&&J.sync?s60(J,f):J.file?t60(J,f,W):J.sync?a60(J,f):o60(J,f)};var s60=($,f)=>{let W=new sL.Sync($),J=new $u.WriteStreamSync($.file,{mode:$.mode||438});W.pipe(J),Ju(W,f)},t60=($,f,W)=>{let J=new sL($),Z=new $u.WriteStream($.file,{mode:$.mode||438});J.pipe(Z);let X=new Promise((z,w)=>{Z.on("error",w),Z.on("close",z),J.on("error",w)});return eA(J,f),W?X.then(W,W):X},Ju=($,f)=>{f.forEach((W)=>{if(W.charAt(0)==="@")fu({file:Wu.resolve($.cwd,W.slice(1)),sync:!0,noResume:!0,onentry:(J)=>$.add(J)});else $.add(W)}),$.end()},eA=($,f)=>{while(f.length){let W=f.shift();if(W.charAt(0)==="@")return fu({file:Wu.resolve($.cwd,W.slice(1)),noResume:!0,onentry:(J)=>$.add(J)}).then((J)=>eA($,f));else $.add(W)}$.end()},a60=($,f)=>{let W=new sL.Sync($);return Ju(W,f),W},o60=($,f)=>{let W=new sL($);return eA(W,f),W}});var $x=d((ve0,Hu)=>{var e60=oW(),zu=EL(),Jf=u("fs"),wu=MJ(),Gu=nL(),Yu=u("path"),Lu=ZJ();Hu.exports=($,f,W)=>{let J=e60($);if(!J.file)throw new TypeError("file is required");if(J.gzip||J.brotli||J.file.endsWith(".br")||J.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!f||!Array.isArray(f)||!f.length)throw new TypeError("no files or directories specified");return f=Array.from(f),J.sync?$50(J,f):W50(J,f,W)};var $50=($,f)=>{let W=new zu.Sync($),J=!0,Z,X;try{try{Z=Jf.openSync($.file,"r+")}catch(G){if(G.code==="ENOENT")Z=Jf.openSync($.file,"w+");else throw G}let z=Jf.fstatSync(Z),w=Buffer.alloc(512);$:for(X=0;X<z.size;X+=512){for(let L=0,U=0;L<512;L+=U){if(U=Jf.readSync(Z,w,L,w.length-L,X+L),X===0&&w[0]===31&&w[1]===139)throw new Error("cannot append to compressed archives");if(!U)break $}let G=new Lu(w);if(!G.cksumValid)break;let Y=512*Math.ceil(G.size/512);if(X+Y+512>z.size)break;if(X+=Y,$.mtimeCache)$.mtimeCache.set(G.path,G.mtime)}J=!1,f50($,W,X,Z,f)}finally{if(J)try{Jf.closeSync(Z)}catch(z){}}},f50=($,f,W,J,Z)=>{let X=new wu.WriteStreamSync($.file,{fd:J,start:W});f.pipe(X),J50(f,Z)},W50=($,f,W)=>{f=Array.from(f);let J=new zu($),Z=(z,w,G)=>{let Y=(V,Q)=>{if(V)Jf.close(z,(O)=>G(V));else G(null,Q)},L=0;if(w===0)return Y(null,0);let U=0,M=Buffer.alloc(512),q=(V,Q)=>{if(V)return Y(V);if(U+=Q,U<512&&Q)return Jf.read(z,M,U,M.length-U,L+U,q);if(L===0&&M[0]===31&&M[1]===139)return Y(new Error("cannot append to compressed archives"));if(U<512)return Y(null,L);let O=new Lu(M);if(!O.cksumValid)return Y(null,L);let x=512*Math.ceil(O.size/512);if(L+x+512>w)return Y(null,L);if(L+=x+512,L>=w)return Y(null,L);if($.mtimeCache)$.mtimeCache.set(O.path,O.mtime);U=0,Jf.read(z,M,0,512,L,q)};Jf.read(z,M,0,512,L,q)},X=new Promise((z,w)=>{J.on("error",w);let G="r+",Y=(L,U)=>{if(L&&L.code==="ENOENT"&&G==="r+")return G="w+",Jf.open($.file,G,Y);if(L)return w(L);Jf.fstat(U,(M,q)=>{if(M)return Jf.close(U,()=>w(M));Z(U,q.size,(V,Q)=>{if(V)return w(V);let O=new wu.WriteStream($.file,{fd:U,start:Q});J.pipe(O),O.on("error",w),O.on("close",z),Ku(J,f)})})};Jf.open($.file,G,Y)});return W?X.then(W,W):X},J50=($,f)=>{f.forEach((W)=>{if(W.charAt(0)==="@")Gu({file:Yu.resolve($.cwd,W.slice(1)),sync:!0,noResume:!0,onentry:(J)=>$.add(J)});else $.add(W)}),$.end()},Ku=($,f)=>{while(f.length){let W=f.shift();if(W.charAt(0)==="@")return Gu({file:Yu.resolve($.cwd,W.slice(1)),noResume:!0,onentry:(J)=>$.add(J)}).then((J)=>Ku($,f));else $.add(W)}$.end()}});var Ru=d((me0,Uu)=>{var Z50=oW(),X50=$x();Uu.exports=($,f,W)=>{let J=Z50($);if(!J.file)throw new TypeError("file is required");if(J.gzip||J.brotli||J.file.endsWith(".br")||J.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!f||!Array.isArray(f)||!f.length)throw new TypeError("no files or directories specified");return f=Array.from(f),z50(J),X50(J,f,W)};var z50=($)=>{let f=$.filter;if(!$.mtimeCache)$.mtimeCache=new Map;$.filter=f?(W,J)=>f(W,J)&&!($.mtimeCache.get(W)>J.mtime):(W,J)=>!($.mtimeCache.get(W)>J.mtime)}});var Vu=d((ke0,qu)=>{var{promisify:Mu}=u("util"),K6=u("fs"),w50=($)=>{if(!$)$={mode:511,fs:K6};else if(typeof $==="object")$={mode:511,fs:K6,...$};else if(typeof $==="number")$={mode:$,fs:K6};else if(typeof $==="string")$={mode:parseInt($,8),fs:K6};else throw new TypeError("invalid options argument");return $.mkdir=$.mkdir||$.fs.mkdir||K6.mkdir,$.mkdirAsync=Mu($.mkdir),$.stat=$.stat||$.fs.stat||K6.stat,$.statAsync=Mu($.stat),$.statSync=$.statSync||$.fs.statSync||K6.statSync,$.mkdirSync=$.mkdirSync||$.fs.mkdirSync||K6.mkdirSync,$};qu.exports=w50});var Iu=d((ye0,Qu)=>{var G50=process.env.__TESTING_MKDIRP_PLATFORM__||process.platform,{resolve:Y50,parse:L50}=u("path"),K50=($)=>{if(/\0/.test($))throw Object.assign(new TypeError("path must be a string without null bytes"),{path:$,code:"ERR_INVALID_ARG_VALUE"});if($=Y50($),G50==="win32"){let f=/[*|"<>?:]/,{root:W}=L50($);if(f.test($.substr(W.length)))throw Object.assign(new Error("Illegal characters in path."),{path:$,code:"EINVAL"})}return $};Qu.exports=K50});var Nu=d((je0,_u)=>{var{dirname:Ou}=u("path"),Au=($,f,W=void 0)=>{if(W===f)return Promise.resolve();return $.statAsync(f).then((J)=>J.isDirectory()?W:void 0,(J)=>J.code==="ENOENT"?Au($,Ou(f),f):void 0)},xu=($,f,W=void 0)=>{if(W===f)return;try{return $.statSync(f).isDirectory()?W:void 0}catch(J){return J.code==="ENOENT"?xu($,Ou(f),f):void 0}};_u.exports={findMade:Au,findMadeSync:xu}});var Jx=d((ge0,Fu)=>{var{dirname:Su}=u("path"),fx=($,f,W)=>{f.recursive=!1;let J=Su($);if(J===$)return f.mkdirAsync($,f).catch((Z)=>{if(Z.code!=="EISDIR")throw Z});return f.mkdirAsync($,f).then(()=>W||$,(Z)=>{if(Z.code==="ENOENT")return fx(J,f).then((X)=>fx($,f,X));if(Z.code!=="EEXIST"&&Z.code!=="EROFS")throw Z;return f.statAsync($).then((X)=>{if(X.isDirectory())return W;else throw Z},()=>{throw Z})})},Wx=($,f,W)=>{let J=Su($);if(f.recursive=!1,J===$)try{return f.mkdirSync($,f)}catch(Z){if(Z.code!=="EISDIR")throw Z;else return}try{return f.mkdirSync($,f),W||$}catch(Z){if(Z.code==="ENOENT")return Wx($,f,Wx(J,f,W));if(Z.code!=="EEXIST"&&Z.code!=="EROFS")throw Z;try{if(!f.statSync($).isDirectory())throw Z}catch(X){throw Z}}};Fu.exports={mkdirpManual:fx,mkdirpManualSync:Wx}});var Pu=d((be0,Tu)=>{var{dirname:Bu}=u("path"),{findMade:H50,findMadeSync:U50}=Nu(),{mkdirpManual:R50,mkdirpManualSync:M50}=Jx(),q50=($,f)=>{if(f.recursive=!0,Bu($)===$)return f.mkdirAsync($,f);return H50(f,$).then((J)=>f.mkdirAsync($,f).then(()=>J).catch((Z)=>{if(Z.code==="ENOENT")return R50($,f);else throw Z}))},V50=($,f)=>{if(f.recursive=!0,Bu($)===$)return f.mkdirSync($,f);let J=U50(f,$);try{return f.mkdirSync($,f),J}catch(Z){if(Z.code==="ENOENT")return M50($,f);else throw Z}};Tu.exports={mkdirpNative:q50,mkdirpNativeSync:V50}});var Du=d((ue0,hu)=>{var Cu=u("fs"),Q50=process.env.__TESTING_MKDIRP_NODE_VERSION__||process.version,Zx=Q50.replace(/^v/,"").split("."),Eu=+Zx[0]>10||+Zx[0]===10&&+Zx[1]>=12,I50=!Eu?()=>!1:($)=>$.mkdir===Cu.mkdir,O50=!Eu?()=>!1:($)=>$.mkdirSync===Cu.mkdirSync;hu.exports={useNative:I50,useNativeSync:O50}});var gu=d((ce0,ju)=>{var VJ=Vu(),QJ=Iu(),{mkdirpNative:vu,mkdirpNativeSync:mu}=Pu(),{mkdirpManual:ku,mkdirpManualSync:yu}=Jx(),{useNative:A50,useNativeSync:x50}=Du(),IJ=($,f)=>{return $=QJ($),f=VJ(f),A50(f)?vu($,f):ku($,f)},_50=($,f)=>{return $=QJ($),f=VJ(f),x50(f)?mu($,f):yu($,f)};IJ.sync=_50;IJ.native=($,f)=>vu(QJ($),VJ(f));IJ.manual=($,f)=>ku(QJ($),VJ(f));IJ.nativeSync=($,f)=>mu(QJ($),VJ(f));IJ.manualSync=($,f)=>yu(QJ($),VJ(f));ju.exports=IJ});var lu=d((de0,ru)=>{var Sf=u("fs"),p5=u("path"),N50=Sf.lchown?"lchown":"chown",S50=Sf.lchownSync?"lchownSync":"chownSync",uu=Sf.lchown&&!process.version.match(/v1[1-9]+\./)&&!process.version.match(/v10\.[6-9]/),bu=($,f,W)=>{try{return Sf[S50]($,f,W)}catch(J){if(J.code!=="ENOENT")throw J}},F50=($,f,W)=>{try{return Sf.chownSync($,f,W)}catch(J){if(J.code!=="ENOENT")throw J}},B50=uu?($,f,W,J)=>(Z)=>{if(!Z||Z.code!=="EISDIR")J(Z);else Sf.chown($,f,W,J)}:($,f,W,J)=>J,Xx=uu?($,f,W)=>{try{return bu($,f,W)}catch(J){if(J.code!=="EISDIR")throw J;F50($,f,W)}}:($,f,W)=>bu($,f,W),T50=process.version,cu=($,f,W)=>Sf.readdir($,f,W),P50=($,f)=>Sf.readdirSync($,f);if(/^v4\./.test(T50))cu=($,f,W)=>Sf.readdir($,W);var tL=($,f,W,J)=>{Sf[N50]($,f,W,B50($,f,W,(Z)=>{J(Z&&Z.code!=="ENOENT"?Z:null)}))},du=($,f,W,J,Z)=>{if(typeof f==="string")return Sf.lstat(p5.resolve($,f),(X,z)=>{if(X)return Z(X.code!=="ENOENT"?X:null);z.name=f,du($,z,W,J,Z)});if(f.isDirectory())zx(p5.resolve($,f.name),W,J,(X)=>{if(X)return Z(X);let z=p5.resolve($,f.name);tL(z,W,J,Z)});else{let X=p5.resolve($,f.name);tL(X,W,J,Z)}},zx=($,f,W,J)=>{cu($,{withFileTypes:!0},(Z,X)=>{if(Z){if(Z.code==="ENOENT")return J();else if(Z.code!=="ENOTDIR"&&Z.code!=="ENOTSUP")return J(Z)}if(Z||!X.length)return tL($,f,W,J);let z=X.length,w=null,G=(Y)=>{if(w)return;if(Y)return J(w=Y);if(--z===0)return tL($,f,W,J)};X.forEach((Y)=>du($,Y,f,W,G))})},C50=($,f,W,J)=>{if(typeof f==="string")try{let Z=Sf.lstatSync(p5.resolve($,f));Z.name=f,f=Z}catch(Z){if(Z.code==="ENOENT")return;else throw Z}if(f.isDirectory())iu(p5.resolve($,f.name),W,J);Xx(p5.resolve($,f.name),W,J)},iu=($,f,W)=>{let J;try{J=P50($,{withFileTypes:!0})}catch(Z){if(Z.code==="ENOENT")return;else if(Z.code==="ENOTDIR"||Z.code==="ENOTSUP")return Xx($,f,W);else throw Z}if(J&&J.length)J.forEach((Z)=>C50($,Z,f,W));return Xx($,f,W)};ru.exports=zx;zx.sync=iu});var tu=d((ie0,Yx)=>{var pu=gu(),Ff=u("fs"),aL=u("path"),nu=lu(),G2=WJ();class wx extends Error{constructor($,f){super("Cannot extract through symbolic link");this.path=f,this.symlink=$}get name(){return"SylinkError"}}class Gx extends Error{constructor($,f){super(f+": Cannot cd into '"+$+"'");this.path=$,this.code=f}get name(){return"CwdError"}}var oL=($,f)=>$.get(G2(f)),EX=($,f,W)=>$.set(G2(f),W),E50=($,f)=>{Ff.stat($,(W,J)=>{if(W||!J.isDirectory())W=new Gx($,W&&W.code||"ENOTDIR");f(W)})};Yx.exports=($,f,W)=>{$=G2($);let J=f.umask,Z=f.mode|448,X=(Z&J)!==0,z=f.uid,w=f.gid,G=typeof z==="number"&&typeof w==="number"&&(z!==f.processUid||w!==f.processGid),Y=f.preserve,L=f.unlink,U=f.cache,M=G2(f.cwd),q=(O,x)=>{if(O)W(O);else if(EX(U,$,!0),x&&G)nu(x,z,w,(y)=>q(y));else if(X)Ff.chmod($,Z,W);else W()};if(U&&oL(U,$)===!0)return q();if($===M)return E50($,q);if(Y)return pu($,{mode:Z}).then((O)=>q(null,O),q);let Q=G2(aL.relative(M,$)).split("/");eL(M,Q,Z,U,L,M,null,q)};var eL=($,f,W,J,Z,X,z,w)=>{if(!f.length)return w(null,z);let G=f.shift(),Y=G2(aL.resolve($+"/"+G));if(oL(J,Y))return eL(Y,f,W,J,Z,X,z,w);Ff.mkdir(Y,W,su(Y,f,W,J,Z,X,z,w))},su=($,f,W,J,Z,X,z,w)=>(G)=>{if(G)Ff.lstat($,(Y,L)=>{if(Y)Y.path=Y.path&&G2(Y.path),w(Y);else if(L.isDirectory())eL($,f,W,J,Z,X,z,w);else if(Z)Ff.unlink($,(U)=>{if(U)return w(U);Ff.mkdir($,W,su($,f,W,J,Z,X,z,w))});else if(L.isSymbolicLink())return w(new wx($,$+"/"+f.join("/")));else w(G)});else z=z||$,eL($,f,W,J,Z,X,z,w)},h50=($)=>{let f=!1,W="ENOTDIR";try{f=Ff.statSync($).isDirectory()}catch(J){W=J.code}finally{if(!f)throw new Gx($,W)}};Yx.exports.sync=($,f)=>{$=G2($);let W=f.umask,J=f.mode|448,Z=(J&W)!==0,X=f.uid,z=f.gid,w=typeof X==="number"&&typeof z==="number"&&(X!==f.processUid||z!==f.processGid),G=f.preserve,Y=f.unlink,L=f.cache,U=G2(f.cwd),M=(O)=>{if(EX(L,$,!0),O&&w)nu.sync(O,X,z);if(Z)Ff.chmodSync($,J)};if(L&&oL(L,$)===!0)return M();if($===U)return h50(U),M();if(G)return M(pu.sync($,J));let V=G2(aL.relative(U,$)).split("/"),Q=null;for(let O=V.shift(),x=U;O&&(x+="/"+O);O=V.shift()){if(x=G2(aL.resolve(x)),oL(L,x))continue;try{Ff.mkdirSync(x,J),Q=Q||x,EX(L,x,!0)}catch(y){let F=Ff.lstatSync(x);if(F.isDirectory()){EX(L,x,!0);continue}else if(Y){Ff.unlinkSync(x),Ff.mkdirSync(x,J),Q=Q||x,EX(L,x,!0);continue}else if(F.isSymbolicLink())return new wx(x,x+"/"+V.join("/"))}}return M(Q)}});var Kx=d((re0,au)=>{var Lx=Object.create(null),{hasOwnProperty:D50}=Object.prototype;au.exports=($)=>{if(!D50.call(Lx,$))Lx[$]=$.normalize("NFD");return Lx[$]}});var fc=d((le0,$c)=>{var ou=u("assert"),v50=Kx(),m50=XJ(),{join:eu}=u("path"),k50=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,y50=k50==="win32";$c.exports=()=>{let $=new Map,f=new Map,W=(Y)=>{return Y.split("/").slice(0,-1).reduce((U,M)=>{if(U.length)M=eu(U[U.length-1],M);return U.push(M||"/"),U},[])},J=new Set,Z=(Y)=>{let L=f.get(Y);if(!L)throw new Error("function does not have any path reservations");return{paths:L.paths.map((U)=>$.get(U)),dirs:[...L.dirs].map((U)=>$.get(U))}},X=(Y)=>{let{paths:L,dirs:U}=Z(Y);return L.every((M)=>M[0]===Y)&&U.every((M)=>M[0]instanceof Set&&M[0].has(Y))},z=(Y)=>{if(J.has(Y)||!X(Y))return!1;return J.add(Y),Y(()=>w(Y)),!0},w=(Y)=>{if(!J.has(Y))return!1;let{paths:L,dirs:U}=f.get(Y),M=new Set;return L.forEach((q)=>{let V=$.get(q);if(ou.equal(V[0],Y),V.length===1)$.delete(q);else if(V.shift(),typeof V[0]==="function")M.add(V[0]);else V[0].forEach((Q)=>M.add(Q))}),U.forEach((q)=>{let V=$.get(q);if(ou(V[0]instanceof Set),V[0].size===1&&V.length===1)$.delete(q);else if(V[0].size===1)V.shift(),M.add(V[0]);else V[0].delete(Y)}),J.delete(Y),M.forEach((q)=>z(q)),!0};return{check:X,reserve:(Y,L)=>{Y=y50?["win32 parallelization disabled"]:Y.map((M)=>{return m50(eu(v50(M))).toLowerCase()});let U=new Set(Y.map((M)=>W(M)).reduce((M,q)=>M.concat(q)));return f.set(L,{dirs:U,paths:Y}),Y.forEach((M)=>{let q=$.get(M);if(!q)$.set(M,[L]);else q.push(L)}),U.forEach((M)=>{let q=$.get(M);if(!q)$.set(M,[new Set([L])]);else if(q[q.length-1]instanceof Set)q[q.length-1].add(L);else q.push(new Set([L]))}),z(L)}}}});var Zc=d((pe0,Jc)=>{var j50=process.env.__FAKE_PLATFORM__||process.platform,g50=j50==="win32",b50=global.__FAKE_TESTING_FS__||u("fs"),{O_CREAT:u50,O_TRUNC:c50,O_WRONLY:d50,UV_FS_O_FILEMAP:Wc=0}=b50.constants,i50=g50&&!!Wc,r50=Wc|c50|u50|d50;Jc.exports=!i50?()=>"w":($)=>$<524288?r50:"w"});var Ix=d((ne0,Ic)=>{var l50=u("assert"),p50=pL(),O0=u("fs"),n50=MJ(),z4=u("path"),Mc=tu(),Xc=UA(),s50=fc(),t50=RA(),Bf=WJ(),a50=XJ(),o50=Kx(),zc=Symbol("onEntry"),Rx=Symbol("checkFs"),wc=Symbol("checkFs2"),WK=Symbol("pruneCache"),Mx=Symbol("isReusable"),Tf=Symbol("makeFs"),qx=Symbol("file"),Vx=Symbol("directory"),JK=Symbol("link"),Gc=Symbol("symlink"),Yc=Symbol("hardlink"),Lc=Symbol("unsupported"),Kc=Symbol("checkPath"),H6=Symbol("mkdir"),w$=Symbol("onError"),$K=Symbol("pending"),Hc=Symbol("pend"),OJ=Symbol("unpend"),Hx=Symbol("ended"),Ux=Symbol("maybeClose"),Qx=Symbol("skip"),hX=Symbol("doChown"),DX=Symbol("uid"),vX=Symbol("gid"),mX=Symbol("checkedCwd"),qc=u("crypto"),Vc=Zc(),e50=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,kX=e50==="win32",$80=($,f)=>{if(!kX)return O0.unlink($,f);let W=$+".DELETE."+qc.randomBytes(16).toString("hex");O0.rename($,W,(J)=>{if(J)return f(J);O0.unlink(W,f)})},f80=($)=>{if(!kX)return O0.unlinkSync($);let f=$+".DELETE."+qc.randomBytes(16).toString("hex");O0.renameSync($,f),O0.unlinkSync(f)},Uc=($,f,W)=>$===$>>>0?$:f===f>>>0?f:W,Rc=($)=>a50(Bf(o50($))).toLowerCase(),W80=($,f)=>{f=Rc(f);for(let W of $.keys()){let J=Rc(W);if(J===f||J.indexOf(f+"/")===0)$.delete(W)}},J80=($)=>{for(let f of $.keys())$.delete(f)};class ZK extends p50{constructor($){if(!$)$={};$.ondone=(f)=>{this[Hx]=!0,this[Ux]()};super($);if(this[mX]=!1,this.reservations=s50(),this.transform=typeof $.transform==="function"?$.transform:null,this.writable=!0,this.readable=!1,this[$K]=0,this[Hx]=!1,this.dirCache=$.dirCache||new Map,typeof $.uid==="number"||typeof $.gid==="number"){if(typeof $.uid!=="number"||typeof $.gid!=="number")throw new TypeError("cannot set owner without number uid and gid");if($.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=$.uid,this.gid=$.gid,this.setOwner=!0}else this.uid=null,this.gid=null,this.setOwner=!1;if($.preserveOwner===void 0&&typeof $.uid!=="number")this.preserveOwner=process.getuid&&process.getuid()===0;else this.preserveOwner=!!$.preserveOwner;this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():null,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():null,this.maxDepth=typeof $.maxDepth==="number"?$.maxDepth:1024,this.forceChown=$.forceChown===!0,this.win32=!!$.win32||kX,this.newer=!!$.newer,this.keep=!!$.keep,this.noMtime=!!$.noMtime,this.preservePaths=!!$.preservePaths,this.unlink=!!$.unlink,this.cwd=Bf(z4.resolve($.cwd||process.cwd())),this.strip=+$.strip||0,this.processUmask=$.noChmod?0:process.umask(),this.umask=typeof $.umask==="number"?$.umask:this.processUmask,this.dmode=$.dmode||511&~this.umask,this.fmode=$.fmode||438&~this.umask,this.on("entry",(f)=>this[zc](f))}warn($,f,W={}){if($==="TAR_BAD_ARCHIVE"||$==="TAR_ABORT")W.recoverable=!1;return super.warn($,f,W)}[Ux](){if(this[Hx]&&this[$K]===0)this.emit("prefinish"),this.emit("finish"),this.emit("end")}[Kc]($){let f=Bf($.path),W=f.split("/");if(this.strip){if(W.length<this.strip)return!1;if($.type==="Link"){let J=Bf($.linkpath).split("/");if(J.length>=this.strip)$.linkpath=J.slice(this.strip).join("/");else return!1}W.splice(0,this.strip),$.path=W.join("/")}if(isFinite(this.maxDepth)&&W.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:$,path:f,depth:W.length,maxDepth:this.maxDepth}),!1;if(!this.preservePaths){if(W.includes("..")||kX&&/^[a-z]:\.\.$/i.test(W[0]))return this.warn("TAR_ENTRY_ERROR","path contains '..'",{entry:$,path:f}),!1;let[J,Z]=t50(f);if(J)$.path=Z,this.warn("TAR_ENTRY_INFO",`stripping ${J} from absolute path`,{entry:$,path:f})}if(z4.isAbsolute($.path))$.absolute=Bf(z4.resolve($.path));else $.absolute=Bf(z4.resolve(this.cwd,$.path));if(!this.preservePaths&&$.absolute.indexOf(this.cwd+"/")!==0&&$.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:$,path:Bf($.path),resolvedPath:$.absolute,cwd:this.cwd}),!1;if($.absolute===this.cwd&&$.type!=="Directory"&&$.type!=="GNUDumpDir")return!1;if(this.win32){let{root:J}=z4.win32.parse($.absolute);$.absolute=J+Xc.encode($.absolute.slice(J.length));let{root:Z}=z4.win32.parse($.path);$.path=Z+Xc.encode($.path.slice(Z.length))}return!0}[zc]($){if(!this[Kc]($))return $.resume();switch(l50.equal(typeof $.absolute,"string"),$.type){case"Directory":case"GNUDumpDir":if($.mode)$.mode=$.mode|448;case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Rx]($);case"CharacterDevice":case"BlockDevice":case"FIFO":default:return this[Lc]($)}}[w$]($,f){if($.name==="CwdError")this.emit("error",$);else this.warn("TAR_ENTRY_ERROR",$,{entry:f}),this[OJ](),f.resume()}[H6]($,f,W){Mc(Bf($),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:f,noChmod:this.noChmod},W)}[hX]($){return this.forceChown||this.preserveOwner&&(typeof $.uid==="number"&&$.uid!==this.processUid||typeof $.gid==="number"&&$.gid!==this.processGid)||(typeof this.uid==="number"&&this.uid!==this.processUid||typeof this.gid==="number"&&this.gid!==this.processGid)}[DX]($){return Uc(this.uid,$.uid,this.processUid)}[vX]($){return Uc(this.gid,$.gid,this.processGid)}[qx]($,f){let W=$.mode&4095||this.fmode,J=new n50.WriteStream($.absolute,{flags:Vc($.size),mode:W,autoClose:!1});J.on("error",(w)=>{if(J.fd)O0.close(J.fd,()=>{});J.write=()=>!0,this[w$](w,$),f()});let Z=1,X=(w)=>{if(w){if(J.fd)O0.close(J.fd,()=>{});this[w$](w,$),f();return}if(--Z===0)O0.close(J.fd,(G)=>{if(G)this[w$](G,$);else this[OJ]();f()})};J.on("finish",(w)=>{let G=$.absolute,Y=J.fd;if($.mtime&&!this.noMtime){Z++;let L=$.atime||new Date,U=$.mtime;O0.futimes(Y,L,U,(M)=>M?O0.utimes(G,L,U,(q)=>X(q&&M)):X())}if(this[hX]($)){Z++;let L=this[DX]($),U=this[vX]($);O0.fchown(Y,L,U,(M)=>M?O0.chown(G,L,U,(q)=>X(q&&M)):X())}X()});let z=this.transform?this.transform($)||$:$;if(z!==$)z.on("error",(w)=>{this[w$](w,$),f()}),$.pipe(z);z.pipe(J)}[Vx]($,f){let W=$.mode&4095||this.dmode;this[H6]($.absolute,W,(J)=>{if(J){this[w$](J,$),f();return}let Z=1,X=(z)=>{if(--Z===0)f(),this[OJ](),$.resume()};if($.mtime&&!this.noMtime)Z++,O0.utimes($.absolute,$.atime||new Date,$.mtime,X);if(this[hX]($))Z++,O0.chown($.absolute,this[DX]($),this[vX]($),X);X()})}[Lc]($){$.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${$.type}`,{entry:$}),$.resume()}[Gc]($,f){this[JK]($,$.linkpath,"symlink",f)}[Yc]($,f){let W=Bf(z4.resolve(this.cwd,$.linkpath));this[JK]($,W,"link",f)}[Hc](){this[$K]++}[OJ](){this[$K]--,this[Ux]()}[Qx]($){this[OJ](),$.resume()}[Mx]($,f){return $.type==="File"&&!this.unlink&&f.isFile()&&f.nlink<=1&&!kX}[Rx]($){this[Hc]();let f=[$.path];if($.linkpath)f.push($.linkpath);this.reservations.reserve(f,(W)=>this[wc]($,W))}[WK]($){if($.type==="SymbolicLink")J80(this.dirCache);else if($.type!=="Directory")W80(this.dirCache,$.absolute)}[wc]($,f){this[WK]($);let W=(z)=>{this[WK]($),f(z)},J=()=>{this[H6](this.cwd,this.dmode,(z)=>{if(z){this[w$](z,$),W();return}this[mX]=!0,Z()})},Z=()=>{if($.absolute!==this.cwd){let z=Bf(z4.dirname($.absolute));if(z!==this.cwd)return this[H6](z,this.dmode,(w)=>{if(w){this[w$](w,$),W();return}X()})}X()},X=()=>{O0.lstat($.absolute,(z,w)=>{if(w&&(this.keep||this.newer&&w.mtime>$.mtime)){this[Qx]($),W();return}if(z||this[Mx]($,w))return this[Tf](null,$,W);if(w.isDirectory()){if($.type==="Directory"){let G=!this.noChmod&&$.mode&&(w.mode&4095)!==$.mode,Y=(L)=>this[Tf](L,$,W);if(!G)return Y();return O0.chmod($.absolute,$.mode,Y)}if($.absolute!==this.cwd)return O0.rmdir($.absolute,(G)=>this[Tf](G,$,W))}if($.absolute===this.cwd)return this[Tf](null,$,W);$80($.absolute,(G)=>this[Tf](G,$,W))})};if(this[mX])Z();else J()}[Tf]($,f,W){if($){this[w$]($,f),W();return}switch(f.type){case"File":case"OldFile":case"ContiguousFile":return this[qx](f,W);case"Link":return this[Yc](f,W);case"SymbolicLink":return this[Gc](f,W);case"Directory":case"GNUDumpDir":return this[Vx](f,W)}}[JK]($,f,W,J){O0[W](f,$.absolute,(Z)=>{if(Z)this[w$](Z,$);else this[OJ](),$.resume();J()})}}var fK=($)=>{try{return[null,$()]}catch(f){return[f,null]}};class Qc extends ZK{[Tf]($,f){return super[Tf]($,f,()=>{})}[Rx]($){if(this[WK]($),!this[mX]){let Z=this[H6](this.cwd,this.dmode);if(Z)return this[w$](Z,$);this[mX]=!0}if($.absolute!==this.cwd){let Z=Bf(z4.dirname($.absolute));if(Z!==this.cwd){let X=this[H6](Z,this.dmode);if(X)return this[w$](X,$)}}let[f,W]=fK(()=>O0.lstatSync($.absolute));if(W&&(this.keep||this.newer&&W.mtime>$.mtime))return this[Qx]($);if(f||this[Mx]($,W))return this[Tf](null,$);if(W.isDirectory()){if($.type==="Directory"){let X=!this.noChmod&&$.mode&&(W.mode&4095)!==$.mode,[z]=X?fK(()=>{O0.chmodSync($.absolute,$.mode)}):[];return this[Tf](z,$)}let[Z]=fK(()=>O0.rmdirSync($.absolute));this[Tf](Z,$)}let[J]=$.absolute===this.cwd?[]:fK(()=>f80($.absolute));this[Tf](J,$)}[qx]($,f){let W=$.mode&4095||this.fmode,J=(z)=>{let w;try{O0.closeSync(Z)}catch(G){w=G}if(z||w)this[w$](z||w,$);f()},Z;try{Z=O0.openSync($.absolute,Vc($.size),W)}catch(z){return J(z)}let X=this.transform?this.transform($)||$:$;if(X!==$)X.on("error",(z)=>this[w$](z,$)),$.pipe(X);X.on("data",(z)=>{try{O0.writeSync(Z,z,0,z.length)}catch(w){J(w)}}),X.on("end",(z)=>{let w=null;if($.mtime&&!this.noMtime){let G=$.atime||new Date,Y=$.mtime;try{O0.futimesSync(Z,G,Y)}catch(L){try{O0.utimesSync($.absolute,G,Y)}catch(U){w=L}}}if(this[hX]($)){let G=this[DX]($),Y=this[vX]($);try{O0.fchownSync(Z,G,Y)}catch(L){try{O0.chownSync($.absolute,G,Y)}catch(U){w=w||L}}}J(w)})}[Vx]($,f){let W=$.mode&4095||this.dmode,J=this[H6]($.absolute,W);if(J){this[w$](J,$),f();return}if($.mtime&&!this.noMtime)try{O0.utimesSync($.absolute,$.atime||new Date,$.mtime)}catch(Z){}if(this[hX]($))try{O0.chownSync($.absolute,this[DX]($),this[vX]($))}catch(Z){}f(),$.resume()}[H6]($,f){try{return Mc.sync(Bf($),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:f})}catch(W){return W}}[JK]($,f,W,J){try{O0[W+"Sync"](f,$.absolute),J(),$.resume()}catch(Z){return this[w$](Z,$)}}}ZK.Sync=Qc;Ic.exports=ZK});var Nc=d((se0,_c)=>{var Z80=oW(),XK=Ix(),Ac=u("fs"),xc=MJ(),Oc=u("path"),Ox=XJ();_c.exports=($,f,W)=>{if(typeof $==="function")W=$,f=null,$={};else if(Array.isArray($))f=$,$={};if(typeof f==="function")W=f,f=null;if(!f)f=[];else f=Array.from(f);let J=Z80($);if(J.sync&&typeof W==="function")throw new TypeError("callback not supported for sync tar functions");if(!J.file&&typeof W==="function")throw new TypeError("callback only supported with file option");if(f.length)X80(J,f);return J.file&&J.sync?z80(J):J.file?w80(J,W):J.sync?G80(J):Y80(J)};var X80=($,f)=>{let W=new Map(f.map((X)=>[Ox(X),!0])),J=$.filter,Z=(X,z)=>{let w=z||Oc.parse(X).root||".",G=X===w?!1:W.has(X)?W.get(X):Z(Oc.dirname(X),w);return W.set(X,G),G};$.filter=J?(X,z)=>J(X,z)&&Z(Ox(X)):(X)=>Z(Ox(X))},z80=($)=>{let f=new XK.Sync($),W=$.file,J=Ac.statSync(W),Z=$.maxReadSize||16777216;new xc.ReadStreamSync(W,{readSize:Z,size:J.size}).pipe(f)},w80=($,f)=>{let W=new XK($),J=$.maxReadSize||16777216,Z=$.file,X=new Promise((z,w)=>{W.on("error",w),W.on("close",z),Ac.stat(Z,(G,Y)=>{if(G)w(G);else{let L=new xc.ReadStream(Z,{readSize:J,size:Y.size});L.on("error",w),L.pipe(W)}})});return f?X.then(f,f):X},G80=($)=>new XK.Sync($),Y80=($)=>new XK($)});var Sc=d((L80)=>{L80.c=L80.create=Xu();L80.r=L80.replace=$x();L80.t=L80.list=nL();L80.u=L80.update=Ru();L80.x=L80.extract=Nc();L80.Pack=EL();L80.Unpack=Ix();L80.Parse=pL();L80.ReadEntry=ML();L80.WriteEntry=_A();L80.Header=ZJ();L80.Pax=VL();L80.types=wA()});var Wd=d((fd)=>{Object.defineProperty(fd,"__esModule",{value:!0});var g;(function($){$.AnonymousId="anonymous_id",$.DistinctId="distinct_id",$.Props="props",$.FeatureFlags="feature_flags",$.FeatureFlagPayloads="feature_flag_payloads",$.BootstrapFeatureFlags="bootstrap_feature_flags",$.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",$.OverrideFeatureFlags="override_feature_flags",$.Queue="queue",$.OptedOut="opted_out",$.SessionId="session_id",$.SessionLastTimestamp="session_timestamp",$.PersonProperties="person_properties",$.GroupProperties="group_properties",$.InstalledAppBuild="installed_app_build",$.InstalledAppVersion="installed_app_version",$.SessionReplay="session_replay",$.DecideEndpointWasHit="decide_endpoint_was_hit"})(g||(g={}));function d80($,f){if(!$)throw new Error(f)}function i80($){return $?.replace(/\/+$/,"")}async function r80($,f){let W=null;for(let J=0;J<f.retryCount+1;J++){if(J>0)await new Promise((Z)=>setTimeout(Z,f.retryDelay));try{return await $()}catch(Z){if(W=Z,!f.retryCheck(Z))throw Z}}throw W}function pc(){return new Date().getTime()}function gc(){return new Date().toISOString()}function bc($,f){let W=setTimeout($,f);return W?.unref&&W?.unref(),W}var uc=($)=>{return $ instanceof Error};function l80(){return typeof fetch!=="undefined"?fetch:typeof global.fetch!=="undefined"?global.fetch:void 0}var uX=String.fromCharCode,cc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",YK={};function p80($,f){if(!YK[$]){YK[$]={};for(let W=0;W<$.length;W++)YK[$][$.charAt(W)]=W}return YK[$][f]}var iX={compressToBase64:function($){if($==null)return"";let f=iX._compress($,6,function(W){return cc.charAt(W)});switch(f.length%4){default:case 0:return f;case 1:return f+"===";case 2:return f+"==";case 3:return f+"="}},decompressFromBase64:function($){if($==null)return"";if($=="")return null;return iX._decompress($.length,32,function(f){return p80(cc,$.charAt(f))})},compress:function($){return iX._compress($,16,function(f){return uX(f)})},_compress:function($,f,W){if($==null)return"";let J={},Z={},X=[],z,w,G="",Y="",L="",U=2,M=3,q=2,V=0,Q=0,O;for(O=0;O<$.length;O+=1){if(G=$.charAt(O),!Object.prototype.hasOwnProperty.call(J,G))J[G]=M++,Z[G]=!0;if(Y=L+G,Object.prototype.hasOwnProperty.call(J,Y))L=Y;else{if(Object.prototype.hasOwnProperty.call(Z,L)){if(L.charCodeAt(0)<256){for(z=0;z<q;z++)if(V=V<<1,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=L.charCodeAt(0);for(z=0;z<8;z++){if(V=V<<1|w&1,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=w>>1}}else{w=1;for(z=0;z<q;z++){if(V=V<<1|w,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=0}w=L.charCodeAt(0);for(z=0;z<16;z++){if(V=V<<1|w&1,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=w>>1}}if(U--,U==0)U=Math.pow(2,q),q++;delete Z[L]}else{w=J[L];for(z=0;z<q;z++){if(V=V<<1|w&1,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=w>>1}}if(U--,U==0)U=Math.pow(2,q),q++;J[Y]=M++,L=String(G)}}if(L!==""){if(Object.prototype.hasOwnProperty.call(Z,L)){if(L.charCodeAt(0)<256){for(z=0;z<q;z++)if(V=V<<1,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=L.charCodeAt(0);for(z=0;z<8;z++){if(V=V<<1|w&1,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=w>>1}}else{w=1;for(z=0;z<q;z++){if(V=V<<1|w,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=0}w=L.charCodeAt(0);for(z=0;z<16;z++){if(V=V<<1|w&1,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=w>>1}}if(U--,U==0)U=Math.pow(2,q),q++;delete Z[L]}else{w=J[L];for(z=0;z<q;z++){if(V=V<<1|w&1,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=w>>1}}if(U--,U==0)U=Math.pow(2,q),q++}w=2;for(z=0;z<q;z++){if(V=V<<1|w&1,Q==f-1)Q=0,X.push(W(V)),V=0;else Q++;w=w>>1}while(!0)if(V=V<<1,Q==f-1){X.push(W(V));break}else Q++;return X.join("")},decompress:function($){if($==null)return"";if($=="")return null;return iX._decompress($.length,32768,function(f){return $.charCodeAt(f)})},_decompress:function($,f,W){let J=[],Z=[],X={val:W(0),position:f,index:1},z=4,w=4,G=3,Y="",L,U,M,q,V,Q,O;for(L=0;L<3;L+=1)J[L]=L;M=0,V=Math.pow(2,2),Q=1;while(Q!=V){if(q=X.val&X.position,X.position>>=1,X.position==0)X.position=f,X.val=W(X.index++);M|=(q>0?1:0)*Q,Q<<=1}switch(M){case 0:M=0,V=Math.pow(2,8),Q=1;while(Q!=V){if(q=X.val&X.position,X.position>>=1,X.position==0)X.position=f,X.val=W(X.index++);M|=(q>0?1:0)*Q,Q<<=1}O=uX(M);break;case 1:M=0,V=Math.pow(2,16),Q=1;while(Q!=V){if(q=X.val&X.position,X.position>>=1,X.position==0)X.position=f,X.val=W(X.index++);M|=(q>0?1:0)*Q,Q<<=1}O=uX(M);break;case 2:return""}J[3]=O,U=O,Z.push(O);while(!0){if(X.index>$)return"";M=0,V=Math.pow(2,G),Q=1;while(Q!=V){if(q=X.val&X.position,X.position>>=1,X.position==0)X.position=f,X.val=W(X.index++);M|=(q>0?1:0)*Q,Q<<=1}switch(O=M){case 0:M=0,V=Math.pow(2,8),Q=1;while(Q!=V){if(q=X.val&X.position,X.position>>=1,X.position==0)X.position=f,X.val=W(X.index++);M|=(q>0?1:0)*Q,Q<<=1}J[w++]=uX(M),O=w-1,z--;break;case 1:M=0,V=Math.pow(2,16),Q=1;while(Q!=V){if(q=X.val&X.position,X.position>>=1,X.position==0)X.position=f,X.val=W(X.index++);M|=(q>0?1:0)*Q,Q<<=1}J[w++]=uX(M),O=w-1,z--;break;case 2:return Z.join("")}if(z==0)z=Math.pow(2,G),G++;if(J[O])Y=J[O];else if(O===w)Y=U+U.charAt(0);else return null;if(Z.push(Y),J[w++]=U+Y.charAt(0),z--,U=Y,z==0)z=Math.pow(2,G),G++}}};class nc{constructor(){this.events={},this.events={}}on($,f){if(!this.events[$])this.events[$]=[];return this.events[$].push(f),()=>{this.events[$]=this.events[$].filter((W)=>W!==f)}}emit($,f){for(let W of this.events[$]||[])W(f);for(let W of this.events["*"]||[])W($,f)}}var LK="0123456789abcdef";class n5{constructor($){this.bytes=$}static ofInner($){if($.length!==16)throw new TypeError("not 128-bit length");else return new n5($)}static fromFieldsV7($,f,W,J){if(!Number.isInteger($)||!Number.isInteger(f)||!Number.isInteger(W)||!Number.isInteger(J)||$<0||f<0||W<0||J<0||$>281474976710655||f>4095||W>1073741823||J>4294967295)throw new RangeError("invalid field value");let Z=new Uint8Array(16);return Z[0]=$/1099511627776,Z[1]=$/4294967296,Z[2]=$/16777216,Z[3]=$/65536,Z[4]=$/256,Z[5]=$,Z[6]=112|f>>>8,Z[7]=f,Z[8]=128|W>>>24,Z[9]=W>>>16,Z[10]=W>>>8,Z[11]=W,Z[12]=J>>>24,Z[13]=J>>>16,Z[14]=J>>>8,Z[15]=J,new n5(Z)}static parse($){let f=void 0;switch($.length){case 32:f=/^[0-9a-f]{32}$/i.exec($)?.[0];break;case 36:f=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec($)?.slice(1,6).join("");break;case 38:f=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec($)?.slice(1,6).join("");break;case 45:f=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec($)?.slice(1,6).join("");break}if(f){let W=new Uint8Array(16);for(let J=0;J<16;J+=4){let Z=parseInt(f.substring(2*J,2*J+8),16);W[J+0]=Z>>>24,W[J+1]=Z>>>16,W[J+2]=Z>>>8,W[J+3]=Z}return new n5(W)}else throw new SyntaxError("could not parse UUID string")}toString(){let $="";for(let f=0;f<this.bytes.length;f++)if($+=LK.charAt(this.bytes[f]>>>4),$+=LK.charAt(this.bytes[f]&15),f===3||f===5||f===7||f===9)$+="-";return $}toHex(){let $="";for(let f=0;f<this.bytes.length;f++)$+=LK.charAt(this.bytes[f]>>>4),$+=LK.charAt(this.bytes[f]&15);return $}toJSON(){return this.toString()}getVariant(){let $=this.bytes[8]>>>4;if($<0)throw new Error("unreachable");else if($<=7)return this.bytes.every((f)=>f===0)?"NIL":"VAR_0";else if($<=11)return"VAR_10";else if($<=13)return"VAR_110";else if($<=15)return this.bytes.every((f)=>f===255)?"MAX":"VAR_RESERVED";else throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new n5(this.bytes.slice(0))}equals($){return this.compareTo($)===0}compareTo($){for(let f=0;f<16;f++){let W=this.bytes[f]-$.bytes[f];if(W!==0)return Math.sign(W)}return 0}}class sc{constructor($){this.timestamp=0,this.counter=0,this.random=$??n80()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore($,f){let W=this.generateOrAbortCore($,f);if(W===void 0)this.timestamp=0,W=this.generateOrAbortCore($,f);return W}generateOrAbortCore($,f){if(!Number.isInteger($)||$<1||$>281474976710655)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");else if(f<0||f>281474976710655)throw new RangeError("`rollbackAllowance` out of reasonable range");if($>this.timestamp)this.timestamp=$,this.resetCounter();else if($+f>=this.timestamp){if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}else return;return n5.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let $=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return $[6]=64|$[6]>>>4,$[8]=128|$[8]>>>2,n5.ofInner($)}}var n80=()=>{return{nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}},dc,HK=()=>s80().toString(),s80=()=>(dc||(dc=new sc)).generate();class Cx extends Error{constructor($){super("HTTP error while fetching PostHog: "+$.status);this.response=$,this.name="PostHogFetchHttpError"}}class UK extends Error{constructor($){super("Network error while fetching PostHog",$ instanceof Error?{cause:$}:{});this.error=$,this.name="PostHogFetchNetworkError"}}function ic($){return typeof $==="object"&&($ instanceof Cx||$ instanceof UK)}var RK;(function($){$.FeatureFlags="feature_flags",$.Recordings="recordings"})(RK||(RK={}));class tc{constructor($,f){this.flushPromise=null,this.disableGeoip=!0,this.historicalMigration=!1,this.disabled=!1,this.defaultOptIn=!0,this.pendingPromises={},this._events=new nc,this._isInitialized=!1,d80($,"You must pass your PostHog project's api key."),this.apiKey=$,this.host=i80(f?.host||"https://us.i.posthog.com"),this.flushAt=f?.flushAt?Math.max(f?.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,f?.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,f?.maxQueueSize??1000),this.flushInterval=f?.flushInterval??1e4,this.captureMode=f?.captureMode||"json",this.defaultOptIn=f?.defaultOptIn??!0,this._retryOptions={retryCount:f?.fetchRetryCount??3,retryDelay:f?.fetchRetryDelay??3000,retryCheck:ic},this.requestTimeout=f?.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=f?.featureFlagsRequestTimeoutMs??3000,this.disableGeoip=f?.disableGeoip??!0,this.disabled=f?.disabled??!1,this.historicalMigration=f?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0}logMsgIfDebug($){if(this.isDebug)$()}wrap($){if(this.disabled){this.logMsgIfDebug(()=>console.warn("[PostHog] The client is disabled"));return}if(this._isInitialized)return $();this._initPromise.then(()=>$())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(g.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(g.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(g.OptedOut,!0)})}on($,f){return this._events.on($,f)}debug($=!0){if(this.removeDebugCallback?.(),$){let f=this.on("*",(W,J)=>console.log("PostHog Debug",W,J));this.removeDebugCallback=()=>{f(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload($){return{distinct_id:$.distinct_id,event:$.event,properties:{...$.properties||{},...this.getCommonEventProperties()}}}addPendingPromise($){let f=HK();return this.pendingPromises[f]=$,$.catch(()=>{}).finally(()=>{delete this.pendingPromises[f]}),$}identifyStateless($,f,W){this.wrap(()=>{let J={...this.buildPayload({distinct_id:$,event:"$identify",properties:f})};this.enqueue("identify",J,W)})}captureStateless($,f,W,J){this.wrap(()=>{let Z=this.buildPayload({distinct_id:$,event:f,properties:W});this.enqueue("capture",Z,J)})}aliasStateless($,f,W,J){this.wrap(()=>{let Z=this.buildPayload({event:"$create_alias",distinct_id:f,properties:{...W||{},distinct_id:f,alias:$}});this.enqueue("alias",Z,J)})}groupIdentifyStateless($,f,W,J,Z,X){this.wrap(()=>{let z=this.buildPayload({distinct_id:Z||`$${$}_${f}`,event:"$groupidentify",properties:{$group_type:$,$group_key:f,$group_set:W||{},...X||{}}});this.enqueue("capture",z,J)})}async getDecide($,f={},W={},J={},Z={}){await this._initPromise;let X=`${this.host}/decide/?v=3`,z={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify({token:this.apiKey,distinct_id:$,groups:f,person_properties:W,group_properties:J,...Z})};return this.fetchWithRetry(X,z,{retryCount:0},this.featureFlagsRequestTimeoutMs).then((w)=>w.json()).catch((w)=>{this._events.emit("error",w);return})}async getFeatureFlagStateless($,f,W={},J={},Z={},X){await this._initPromise;let z=await this.getFeatureFlagsStateless(f,W,J,Z,X);if(!z)return;let w=z[$];if(w===void 0)w=!1;return w}async getFeatureFlagPayloadStateless($,f,W={},J={},Z={},X){await this._initPromise;let z=await this.getFeatureFlagPayloadsStateless(f,W,J,Z,X);if(!z)return;let w=z[$];if(w===void 0)return null;return w}async getFeatureFlagPayloadsStateless($,f={},W={},J={},Z){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless($,f,W,J,Z)).payloads}_parsePayload($){try{return JSON.parse($)}catch{return $}}async getFeatureFlagsStateless($,f={},W={},J={},Z){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless($,f,W,J,Z)).flags}async getFeatureFlagsAndPayloadsStateless($,f={},W={},J={},Z){await this._initPromise;let X={};if(Z??this.disableGeoip)X.geoip_disable=!0;let z=await this.getDecide($,f,W,J,X);if(z?.quotaLimited?.includes(RK.FeatureFlags))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:void 0,payloads:void 0};let w=z?.featureFlags,G=z?.featureFlagPayloads,Y=G;if(G)Y=Object.fromEntries(Object.entries(G).map(([L,U])=>[L,this._parsePayload(U)]));return{flags:w,payloads:Y}}enqueue($,f,W){this.wrap(()=>{if(this.optedOut){this._events.emit($,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");return}let J={...f,type:$,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:W?.timestamp?W?.timestamp:gc(),uuid:W?.uuid?W.uuid:HK()};if(W?.disableGeoip??this.disableGeoip){if(!J.properties)J.properties={};J.properties.$geoip_disable=!0}if(J.distinctId)J.distinct_id=J.distinctId,delete J.distinctId;let X=this.getPersistedProperty(g.Queue)||[];if(X.length>=this.maxQueueSize)X.shift(),this.logMsgIfDebug(()=>console.info("Queue is full, the oldest event is dropped."));if(X.push({message:J}),this.setPersistedProperty(g.Queue,X),this._events.emit($,J),X.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=bc(()=>this.flushBackground(),this.flushInterval)})}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){this.flush().catch(()=>{})}async flush(){if(!this.flushPromise)this.flushPromise=this._flush().finally(()=>{this.flushPromise=null}),this.addPendingPromise(this.flushPromise);return this.flushPromise}getCustomHeaders(){let $=this.getCustomUserAgent(),f={};if($&&$!=="")f["User-Agent"]=$;return f}async _flush(){this.clearFlushTimer(),await this._initPromise;let $=this.getPersistedProperty(g.Queue)||[];if(!$.length)return[];let f=$.slice(0,this.maxBatchSize),W=f.map((G)=>G.message),J=()=>{let G=this.getPersistedProperty(g.Queue)||[];this.setPersistedProperty(g.Queue,G.slice(f.length))},Z={api_key:this.apiKey,batch:W,sent_at:gc()};if(this.historicalMigration)Z.historical_migration=!0;let X=JSON.stringify(Z),z=this.captureMode==="form"?`${this.host}/e/?ip=1&_=${pc()}&v=${this.getLibraryVersion()}`:`${this.host}/batch/`,w=this.captureMode==="form"?{method:"POST",mode:"no-cors",credentials:"omit",headers:{...this.getCustomHeaders(),"Content-Type":"application/x-www-form-urlencoded"},body:`data=${encodeURIComponent(iX.compressToBase64(X))}&compression=lz64`}:{method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:X};try{await this.fetchWithRetry(z,w)}catch(G){if(!(G instanceof UK))J();throw this._events.emit("error",G),G}return J(),this._events.emit("flush",W),W}async fetchWithRetry($,f,W,J){var Z;return(Z=AbortSignal).timeout??(Z.timeout=function X(z){let w=new AbortController;return setTimeout(()=>w.abort(),z),w.signal}),await r80(async()=>{let X=null;try{X=await this.fetch($,{signal:AbortSignal.timeout(J??this.requestTimeout),...f})}catch(w){throw new UK(w)}if(f.mode!=="no-cors"&&(X.status<200||X.status>=400))throw new Cx(X);return X},{...this._retryOptions,...W})}async shutdown($=30000){await this._initPromise;let f=!1;this.clearFlushTimer();let W=async()=>{try{await Promise.all(Object.values(this.pendingPromises));while(!0){if((this.getPersistedProperty(g.Queue)||[]).length===0)break;if(await this.flush(),f)break}}catch(J){if(!ic(J))throw J;this.logMsgIfDebug(()=>console.error("Error while shutting down PostHog",J))}};return Promise.race([new Promise((J,Z)=>{bc(()=>{this.logMsgIfDebug(()=>console.error("Timed out while shutting down PostHog")),f=!0,Z("Timeout while shutting down PostHog. Some events may not have been sent.")},$)}),W()])}}class ac extends tc{constructor($,f){let W=f?.disableGeoip??!1,J=f?.featureFlagsRequestTimeoutMs??1e4;super($,{...f,disableGeoip:W,featureFlagsRequestTimeoutMs:J});this.flagCallReported={},this.sessionProps={},this.sendFeatureFlagEvent=f?.sendFeatureFlagEvent??!0,this._sessionExpirationTimeSeconds=f?.sessionExpirationTimeSeconds??1800}setupBootstrap($){let f=$?.bootstrap;if(!f)return;if(f.distinctId){if(f.isIdentifiedId){if(!this.getPersistedProperty(g.DistinctId))this.setPersistedProperty(g.DistinctId,f.distinctId)}else if(!this.getPersistedProperty(g.AnonymousId))this.setPersistedProperty(g.AnonymousId,f.distinctId)}let W=f.featureFlags;if(W&&Object.keys(W).length){let J=Object.keys(W).filter((X)=>!!W[X]).reduce((X,z)=>(X[z]=W[z]||!1,X),{});if(Object.keys(J).length){this.setPersistedProperty(g.BootstrapFeatureFlags,J);let X=this.getPersistedProperty(g.FeatureFlags)||{},z={...J,...X};this.setKnownFeatureFlags(z)}let Z=f.featureFlagPayloads;if(Z&&Object.keys(Z).length){this.setPersistedProperty(g.BootstrapFeatureFlagPayloads,Z);let X=this.getPersistedProperty(g.FeatureFlagPayloads)||{},z={...Z,...X};this.setKnownFeatureFlagPayloads(z)}}}get props(){if(!this._props)this._props=this.getPersistedProperty(g.Props);return this._props||{}}set props($){this._props=$}clearProps(){this.props=void 0,this.sessionProps={},this.flagCallReported={}}on($,f){return this._events.on($,f)}reset($){this.wrap(()=>{let f=[g.Queue,...$||[]];this.clearProps();for(let W of Object.keys(g))if(!f.includes(g[W]))this.setPersistedProperty(g[W],null);this.reloadFeatureFlags()})}getCommonEventProperties(){let $=this.getFeatureFlags(),f={};if($)for(let[W,J]of Object.entries($))f[`$feature/${W}`]=J;return{$active_feature_flags:$?Object.keys($):void 0,...f,...super.getCommonEventProperties()}}enrichProperties($){return{...this.props,...this.sessionProps,...$||{},...this.getCommonEventProperties(),$session_id:this.getSessionId()}}getSessionId(){if(!this._isInitialized)return"";let $=this.getPersistedProperty(g.SessionId),f=this.getPersistedProperty(g.SessionLastTimestamp)||0;if(!$||Date.now()-f>this._sessionExpirationTimeSeconds*1000)$=HK(),this.setPersistedProperty(g.SessionId,$);return this.setPersistedProperty(g.SessionLastTimestamp,Date.now()),$}resetSessionId(){this.wrap(()=>{this.setPersistedProperty(g.SessionId,null),this.setPersistedProperty(g.SessionLastTimestamp,null)})}getAnonymousId(){if(!this._isInitialized)return"";let $=this.getPersistedProperty(g.AnonymousId);if(!$)$=HK(),this.setPersistedProperty(g.AnonymousId,$);return $}getDistinctId(){if(!this._isInitialized)return"";return this.getPersistedProperty(g.DistinctId)||this.getAnonymousId()}async unregister($){this.wrap(()=>{delete this.props[$],this.setPersistedProperty(g.Props,this.props)})}async register($){this.wrap(()=>{this.props={...this.props,...$},this.setPersistedProperty(g.Props,this.props)})}registerForSession($){this.sessionProps={...this.sessionProps,...$}}unregisterForSession($){delete this.sessionProps[$]}identify($,f,W){this.wrap(()=>{let J=this.getDistinctId();if($=$||J,f?.$groups)this.groups(f.$groups);let Z=f?.$set_once;delete f?.$set_once;let X=f?.$set||f,z=this.enrichProperties({$anon_distinct_id:this.getAnonymousId(),$set:X,$set_once:Z});if($!==J)this.setPersistedProperty(g.AnonymousId,J),this.setPersistedProperty(g.DistinctId,$),this.reloadFeatureFlags();super.identifyStateless($,z,W)})}capture($,f,W){this.wrap(()=>{let J=this.getDistinctId();if(f?.$groups)this.groups(f.$groups);let Z=this.enrichProperties(f);super.captureStateless(J,$,Z,W)})}alias($){this.wrap(()=>{let f=this.getDistinctId(),W=this.enrichProperties({});super.aliasStateless($,f,W)})}autocapture($,f,W={},J){this.wrap(()=>{let X={distinct_id:this.getDistinctId(),event:"$autocapture",properties:{...this.enrichProperties(W),$event_type:$,$elements:f}};this.enqueue("autocapture",X,J)})}groups($){this.wrap(()=>{let f=this.props.$groups||{};if(this.register({$groups:{...f,...$}}),Object.keys($).find((W)=>f[W]!==$[W]))this.reloadFeatureFlags()})}group($,f,W,J){this.wrap(()=>{if(this.groups({[$]:f}),W)this.groupIdentify($,f,W,J)})}groupIdentify($,f,W,J){this.wrap(()=>{let Z=this.getDistinctId(),X=this.enrichProperties({});super.groupIdentifyStateless($,f,W,J,Z,X)})}setPersonPropertiesForFlags($){this.wrap(()=>{let f=this.getPersistedProperty(g.PersonProperties)||{};this.setPersistedProperty(g.PersonProperties,{...f,...$})})}resetPersonPropertiesForFlags(){this.wrap(()=>{this.setPersistedProperty(g.PersonProperties,{})})}personProperties($){return this.setPersonPropertiesForFlags($)}setGroupPropertiesForFlags($){this.wrap(()=>{let f=this.getPersistedProperty(g.GroupProperties)||{};if(Object.keys(f).length!==0)Object.keys(f).forEach((W)=>{f[W]={...f[W],...$[W]},delete $[W]});this.setPersistedProperty(g.GroupProperties,{...f,...$})})}resetGroupPropertiesForFlags(){this.wrap(()=>{this.setPersistedProperty(g.GroupProperties,{})})}groupProperties($){this.wrap(()=>{this.setGroupPropertiesForFlags($)})}async decideAsync($=!0){if(await this._initPromise,this._decideResponsePromise)return this._decideResponsePromise;return this._decideAsync($)}async _decideAsync($=!0){return this._decideResponsePromise=this._initPromise.then(async()=>{let f=this.getDistinctId(),W=this.props.$groups||{},J=this.getPersistedProperty(g.PersonProperties)||{},Z=this.getPersistedProperty(g.GroupProperties)||{},X={$anon_distinct_id:$?this.getAnonymousId():void 0},z=await super.getDecide(f,W,J,Z,X);if(z?.quotaLimited?.includes(RK.FeatureFlags))return this.setKnownFeatureFlags(null),this.setKnownFeatureFlagPayloads(null),console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),z;if(z?.featureFlags){if(this.sendFeatureFlagEvent)this.flagCallReported={};let{featureFlags:w,featureFlagPayloads:G}=z;if(z.errorsWhileComputingFlags){let L=this.getPersistedProperty(g.FeatureFlags);this.logMsgIfDebug(()=>console.log("PostHog Debug","Cached feature flags: ",JSON.stringify(L)));let U=this.getPersistedProperty(g.FeatureFlagPayloads);w={...L,...z.featureFlags},G={...U,...z.featureFlagPayloads}}this.setKnownFeatureFlags(w),this.setKnownFeatureFlagPayloads(Object.fromEntries(Object.entries(G||{}).map(([L,U])=>[L,this._parsePayload(U)]))),this.setPersistedProperty(g.DecideEndpointWasHit,!0);let Y=z?.sessionRecording;if(Y)this.setPersistedProperty(g.SessionReplay,Y),this.logMsgIfDebug(()=>console.log("PostHog Debug","Session replay config: ",JSON.stringify(Y)));else this.logMsgIfDebug(()=>console.info("PostHog Debug","Session replay config disabled.")),this.setPersistedProperty(g.SessionReplay,null)}return z}).finally(()=>{this._decideResponsePromise=void 0}),this._decideResponsePromise}setKnownFeatureFlags($){this.wrap(()=>{this.setPersistedProperty(g.FeatureFlags,$),this._events.emit("featureflags",$)})}setKnownFeatureFlagPayloads($){this.wrap(()=>{this.setPersistedProperty(g.FeatureFlagPayloads,$)})}getFeatureFlag($){let f=this.getFeatureFlags();if(!f)return;let W=f[$];if(W===void 0)W=!1;if(this.sendFeatureFlagEvent&&!this.flagCallReported[$])this.flagCallReported[$]=!0,this.capture("$feature_flag_called",{$feature_flag:$,$feature_flag_response:W,$feature_flag_bootstrapped_response:this.getPersistedProperty(g.BootstrapFeatureFlags)?.[$],$feature_flag_bootstrapped_payload:this.getPersistedProperty(g.BootstrapFeatureFlagPayloads)?.[$],$used_bootstrap_value:!this.getPersistedProperty(g.DecideEndpointWasHit)});return W}getFeatureFlagPayload($){let f=this.getFeatureFlagPayloads();if(!f)return;let W=f[$];if(W===void 0)return null;return W}getFeatureFlagPayloads(){return this.getPersistedProperty(g.FeatureFlagPayloads)}getFeatureFlags(){let $=this.getPersistedProperty(g.FeatureFlags),f=this.getPersistedProperty(g.OverrideFeatureFlags);if(!f)return $;$=$||{};for(let W in f)if(!f[W])delete $[W];else $[W]=f[W];return $}getFeatureFlagsAndPayloads(){let $=this.getFeatureFlags(),f=this.getFeatureFlagPayloads();return{flags:$,payloads:f}}isFeatureEnabled($){let f=this.getFeatureFlag($);if(f===void 0)return;return!!f}reloadFeatureFlags($){this.decideAsync().then((f)=>{$?.(void 0,f?.featureFlags)}).catch((f)=>{if($?.(f,void 0),!$)this.logMsgIfDebug(()=>console.log("[PostHog] Error reloading feature flags",f))})}async reloadFeatureFlagsAsync($=!0){return(await this.decideAsync($))?.featureFlags}onFeatureFlags($){return this.on("featureflags",async()=>{let f=this.getFeatureFlags();if(f)$(f)})}onFeatureFlag($,f){return this.on("featureflags",async()=>{let W=this.getFeatureFlag($);if(W!==void 0)f(W)})}async overrideFeatureFlag($){this.wrap(()=>{if($===null)return this.setPersistedProperty(g.OverrideFeatureFlags,null);return this.setPersistedProperty(g.OverrideFeatureFlags,$)})}captureException($,f){let W={$exception_level:"error",$exception_list:[{type:uc($)?$.name:"Error",value:uc($)?$.message:$,mechanism:{handled:!0,synthetic:!1}}],...f};W.$exception_personURL=new URL(`/project/${this.apiKey}/person/${this.getDistinctId()}`,this.host).toString(),this.capture("$exception",W)}captureTraceFeedback($,f){this.capture("$ai_feedback",{$ai_feedback_text:f,$ai_trace_id:String($)})}captureTraceMetric($,f,W){this.capture("$ai_metric",{$ai_metric_name:f,$ai_metric_value:String(W),$ai_trace_id:String($)})}}var oc="3.4.2";function t80($){let f={};if($?.navigator){let W=$.navigator.userAgent,J=o80($);f={...f,...J!==void 0&&{$os:J},$browser:ec(W,$.navigator.vendor,!!$.opera),$referrer:$.document.referrer,$referring_domain:$W0($.document.referrer),$device:e80(W),$current_url:$.location.href,$host:$.location.host,$pathname:$.location.pathname,$browser_version:a80(W,$.navigator.vendor,!!$.opera),$screen_height:$.screen.height,$screen_width:$.screen.width,$screen_dpr:$.devicePixelRatio}}return f={...f,$lib:"js",$lib_version:oc,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:pc()/1000},f}function H1($,f){return $.indexOf(f)>=0}function ec($,f,W){if(f=f||"",W||H1($," OPR/")){if(H1($,"Mini"))return"Opera Mini";return"Opera"}else if(/(BlackBerry|PlayBook|BB10)/i.test($))return"BlackBerry";else if(H1($,"IEMobile")||H1($,"WPDesktop"))return"Internet Explorer Mobile";else if(H1($,"SamsungBrowser/"))return"Samsung Internet";else if(H1($,"Edge")||H1($,"Edg/"))return"Microsoft Edge";else if(H1($,"FBIOS"))return"Facebook Mobile";else if(H1($,"Chrome"))return"Chrome";else if(H1($,"CriOS"))return"Chrome iOS";else if(H1($,"UCWEB")||H1($,"UCBrowser"))return"UC Browser";else if(H1($,"FxiOS"))return"Firefox iOS";else if(H1(f,"Apple")){if(H1($,"Mobile"))return"Mobile Safari";return"Safari"}else if(H1($,"Android"))return"Android Mobile";else if(H1($,"Konqueror"))return"Konqueror";else if(H1($,"Firefox"))return"Firefox";else if(H1($,"MSIE")||H1($,"Trident/"))return"Internet Explorer";else if(H1($,"Gecko"))return"Mozilla";else return""}function a80($,f,W){let J={"Internet Explorer Mobile":/rv:(\d+(\.\d+)?)/,"Microsoft Edge":/Edge?\/(\d+(\.\d+)?)/,Chrome:/Chrome\/(\d+(\.\d+)?)/,"Chrome iOS":/CriOS\/(\d+(\.\d+)?)/,"UC Browser":/(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,Safari:/Version\/(\d+(\.\d+)?)/,"Mobile Safari":/Version\/(\d+(\.\d+)?)/,Opera:/(Opera|OPR)\/(\d+(\.\d+)?)/,Firefox:/Firefox\/(\d+(\.\d+)?)/,"Firefox iOS":/FxiOS\/(\d+(\.\d+)?)/,Konqueror:/Konqueror:(\d+(\.\d+)?)/,BlackBerry:/BlackBerry (\d+(\.\d+)?)/,"Android Mobile":/android\s(\d+(\.\d+)?)/,"Samsung Internet":/SamsungBrowser\/(\d+(\.\d+)?)/,"Internet Explorer":/(rv:|MSIE )(\d+(\.\d+)?)/,Mozilla:/rv:(\d+(\.\d+)?)/},Z=ec($,f,W),X=J[Z]||void 0;if(X===void 0)return null;let z=$.match(X);if(!z)return null;return parseFloat(z[z.length-2])}function o80($){if(!$?.navigator)return;let f=$.navigator.userAgent;if(/Windows/i.test(f)){if(/Phone/.test(f)||/WPDesktop/.test(f))return"Windows Phone";return"Windows"}else if(/(iPhone|iPad|iPod)/.test(f))return"iOS";else if(/Android/.test(f))return"Android";else if(/(BlackBerry|PlayBook|BB10)/i.test(f))return"BlackBerry";else if(/Mac/i.test(f))return"Mac OS X";else if(/Linux/.test(f))return"Linux";else if(/CrOS/.test(f))return"Chrome OS";else return}function e80($){if(/Windows Phone/i.test($)||/WPDesktop/.test($))return"Windows Phone";else if(/iPad/.test($))return"iPad";else if(/iPod/.test($))return"iPod Touch";else if(/iPhone/.test($))return"iPhone";else if(/(BlackBerry|PlayBook|BB10)/i.test($))return"BlackBerry";else if(/Android/.test($))return"Android";else return""}function $W0($){let f=$.split("/");if(f.length>=3)return f[2];return""}var $d={getItem($){try{let f=$+"=",W=document.cookie.split(";");for(let J=0;J<W.length;J++){let Z=W[J];while(Z.charAt(0)==" ")Z=Z.substring(1,Z.length);if(Z.indexOf(f)===0)return decodeURIComponent(Z.substring(f.length,Z.length))}}catch(f){}return null},setItem($,f){try{let X=$+"="+encodeURIComponent(f)+"; path=/";document.cookie=X}catch(W){return}},removeItem($){try{$d.setItem($,"")}catch(f){return}},clear(){document.cookie=""},getAllKeys(){let $=document.cookie.split(";"),f=[];for(let W=0;W<$.length;W++){let J=$[W];while(J.charAt(0)==" ")J=J.substring(1,J.length);f.push(J.split("=")[0])}return f}},rc=($)=>{return{getItem(f){return $.getItem(f)},setItem(f,W){$.setItem(f,W)},removeItem(f){$.removeItem(f)},clear(){$.clear()},getAllKeys(){let f=[];for(let W in localStorage)f.push(W);return f}}},lc=($,f="__mplssupport__")=>{try{if($.setItem(f,"xyz"),$.getItem(f)!=="xyz")return!1;return $.removeItem(f),!0}catch(W){return!1}},KK=void 0,cX=void 0,dX=()=>{let $={};return{getItem(W){return $[W]},setItem(W,J){$[W]=J!==null?J:void 0},removeItem(W){delete $[W]},clear(){for(let W in $)delete $[W]},getAllKeys(){let W=[];for(let J in $)W.push(J);return W}}},fW0=($,f)=>{if(f){if(!KK){let W=rc(f.localStorage);KK=lc(W)?W:void 0}if(!cX){let W=rc(f.sessionStorage);cX=lc(W)?W:void 0}}switch($){case"cookie":return $d||KK||cX||dX();case"localStorage":return KK||cX||dX();case"sessionStorage":return cX||dX();case"memory":return dX();default:return dX()}};class Ex extends ac{constructor($,f){super($,f);if(this._storageKey=f?.persistence_name?`ph_${f.persistence_name}`:`ph_${$}_posthog`,this._storage=fW0(f?.persistence||"localStorage",this.getWindow()),this.setupBootstrap(f),f?.preloadFeatureFlags!==!1)this.reloadFeatureFlags()}getWindow(){return typeof window!=="undefined"?window:void 0}getPersistedProperty($){if(!this._storageCache)this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{};return this._storageCache[$]}setPersistedProperty($,f){if(!this._storageCache)this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{};if(f===null)delete this._storageCache[$];else this._storageCache[$]=f;this._storage.setItem(this._storageKey,JSON.stringify(this._storageCache))}fetch($,f){let W=l80();if(!W)return Promise.reject(new Error("Fetch API is not available in this environment."));return W($,f)}getLibraryId(){return"posthog-js-lite"}getLibraryVersion(){return oc}getCustomUserAgent(){return}getCommonEventProperties(){return{...super.getCommonEventProperties(),...t80(this.getWindow())}}}fd.PostHog=Ex;fd.default=Ex});var $_=q1(ex(),1),{program:IW0,createCommand:OW0,createArgument:AW0,createOption:xW0,CommanderError:_W0,InvalidArgumentError:NW0,InvalidOptionArgumentError:SW0,Command:f_,Argument:oX,Option:Q1,Help:FW0}=$_.default;var OK=q1(Ef(),1);var Dx={};V1(Dx,{user:()=>aj,types:()=>Kd,schema:()=>Sm,run:()=>Ij,debug:()=>_j,create:()=>Gd,copyAssets:()=>Yd,config:()=>Nm});g7();var Nm=($)=>{$.command("config").description("get default config").option("--pretty","pretty print").action((f)=>{let W=yQ();console.log(f.pretty?JSON.stringify(W,null,2):JSON.stringify(W))})};g7();var Sm=($)=>{$.command("schema").description("get schema").option("--pretty","pretty print").action((f)=>{let W=kQ();console.log(f.pretty?JSON.stringify(W,null,2):JSON.stringify(W))})};P5();_();import{readFile as Sf0,readdir as Ff0,stat as yI,unlink as Bf0,writeFile as Tf0}from"node:fs/promises";var sk=R.object({path:R.string({default:"./"})},{title:"Local",description:"Local file system storage",additionalProperties:!1});class bY extends r4{config;constructor($={}){super();this.config=F0(sk,$)}getSchema(){return sk}getName(){return"local"}async listObjects($){let f=await Ff0(this.config.path);return await Promise.all(f.filter((J)=>!$||J.startsWith($)).map(async(J)=>{let Z=await yI(`${this.config.path}/${J}`);return{key:J,last_modified:Z.mtime,size:Z.size}}))}async computeEtag($){let f=j$($)?$:new Response($),W=await crypto.subtle.digest("SHA-256",await f.arrayBuffer());return`"${Array.from(new Uint8Array(W)).map((X)=>X.toString(16).padStart(2,"0")).join("")}"`}async putObject($,f){if(f===null)throw new Error("Body is empty");let W=`${this.config.path}/${$}`;return await Tf0(W,j$(f)?f.stream():f),await this.computeEtag(f)}async deleteObject($){try{await Bf0(`${this.config.path}/${$}`)}catch(f){}}async objectExists($){try{return(await yI(`${this.config.path}/${$}`)).isFile()}catch(f){return!1}}async getObject($,f){try{let W=await Sf0(`${this.config.path}/${$}`),J=M6($);return new Response(W,{status:200,headers:{"Content-Type":J||"application/octet-stream","Content-Length":W.length.toString()}})}catch(W){return new Response("",{status:404})}}getObjectUrl($){throw new Error("Method not implemented.")}async getObjectMeta($){let f=await yI(`${this.config.path}/${$}`);return{type:M6($)||"application/octet-stream",size:f.size}}toJSON($){return{type:this.getName(),config:this.config}}}P5();var Qj=q1($y(),1);PQ();var D5=q1(Ef(),1);import A90 from"node:path";_();import MO from"node:path";import JX from"node:process";import{Buffer as I20}from"node:buffer";import Yy from"node:path";import{fileURLToPath as O20}from"node:url";import A20 from"node:child_process";import tI,{constants as Ly}from"node:fs/promises";import Jy from"node:process";import f20 from"node:os";import W20 from"node:fs";import ef0 from"node:fs";import fy from"node:fs";var uI;function af0(){try{return fy.statSync("/.dockerenv"),!0}catch{return!1}}function of0(){try{return fy.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function cI(){if(uI===void 0)uI=af0()||of0();return uI}var dI,$20=()=>{try{return ef0.statSync("/run/.containerenv"),!0}catch{return!1}};function rW(){if(dI===void 0)dI=$20()||cI();return dI}var Wy=()=>{if(Jy.platform!=="linux")return!1;if(f20.release().toLowerCase().includes("microsoft")){if(rW())return!1;return!0}try{return W20.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!rW():!1}catch{return!1}},WX=Jy.env.__IS_WSL_TEST__?Wy:Wy();function C5($,f,W){let J=(Z)=>Object.defineProperty($,f,{value:Z,enumerable:!0,writable:!0});return Object.defineProperty($,f,{configurable:!0,enumerable:!0,get(){let Z=W();return J(Z),Z},set(Z){J(Z)}}),$}import{promisify as M20}from"node:util";import nI from"node:process";import{execFile as q20}from"node:child_process";import{promisify as J20}from"node:util";import Z20 from"node:process";import{execFile as X20}from"node:child_process";var z20=J20(X20);async function iI(){if(Z20.platform!=="darwin")throw new Error("macOS only");let{stdout:$}=await z20("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec($)?.groups.id??"com.apple.Safari"}import w20 from"node:process";import{promisify as G20}from"node:util";import{execFile as Y20,execFileSync as Nt0}from"node:child_process";var L20=G20(Y20);async function Zy($,{humanReadableOutput:f=!0}={}){if(w20.platform!=="darwin")throw new Error("macOS only");let W=f?[]:["-ss"],{stdout:J}=await L20("osascript",["-e",$,W]);return J.trim()}async function rI($){return Zy(`tell application "Finder" to set app_path to application file id "${$}" as string
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as K20}from"node:util";import{execFile as H20}from"node:child_process";var U20=K20(H20),R20={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},MSEdgeDHTML:{name:"Edge",id:"com.microsoft.edge"},MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"}};class lI extends Error{}async function pI($=U20){let{stdout:f}=await $("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),W=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(f);if(!W)throw new lI(`Cannot find Windows browser in stdout: ${JSON.stringify(f)}`);let{id:J}=W.groups,Z=R20[J];if(!Z)throw new lI(`Unknown browser ID: ${J}`);return Z}var V20=M20(q20),Q20=($)=>$.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,(f)=>f.toUpperCase());async function sI(){if(nI.platform==="darwin"){let $=await iI();return{name:await rI($),id:$}}if(nI.platform==="linux"){let{stdout:$}=await V20("xdg-mime",["query","default","x-scheme-handler/http"]),f=$.trim();return{name:Q20(f.replace(/.desktop$/,"").replace("-"," ")),id:f}}if(nI.platform==="win32")return pI();throw new Error("Only macOS, Linux, and Windows are supported")}var aI=Yy.dirname(O20(import.meta.url)),Xy=Yy.join(aI,"xdg-open"),{platform:lW,arch:zy}=JX,x20=(()=>{let f;return async function(){if(f)return f;let W="/etc/wsl.conf",J=!1;try{await tI.access(W,Ly.F_OK),J=!0}catch{}if(!J)return"/mnt/";let Z=await tI.readFile(W,{encoding:"utf8"}),X=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(Z);if(!X)return"/mnt/";return f=X.groups.mountPoint.trim(),f=f.endsWith("/")?f:`${f}/`,f}})(),wy=async($,f)=>{let W;for(let J of $)try{return await f(J)}catch(Z){W=Z}throw W},cY=async($)=>{if($={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...$},Array.isArray($.app))return wy($.app,(w)=>cY({...$,app:w}));let{name:f,arguments:W=[]}=$.app??{};if(W=[...W],Array.isArray(f))return wy(f,(w)=>cY({...$,app:{name:w,arguments:W}}));if(f==="browser"||f==="browserPrivate"){let w={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","microsoft-edge.desktop":"edge"},G={chrome:"--incognito",firefox:"--private-window",edge:"--inPrivate"},Y=await sI();if(Y.id in w){let L=w[Y.id];if(f==="browserPrivate")W.push(G[L]);return cY({...$,app:{name:pW[L],arguments:W}})}throw new Error(`${Y.name} is not supported as a default browser`)}let J,Z=[],X={};if(lW==="darwin"){if(J="open",$.wait)Z.push("--wait-apps");if($.background)Z.push("--background");if($.newInstance)Z.push("--new");if(f)Z.push("-a",f)}else if(lW==="win32"||WX&&!rW()&&!f){let w=await x20();if(J=WX?`${w}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`:`${JX.env.SYSTEMROOT||JX.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell`,Z.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),!WX)X.windowsVerbatimArguments=!0;let G=["Start"];if($.wait)G.push("-Wait");if(f){if(G.push(`"\`"${f}\`""`),$.target)W.push($.target)}else if($.target)G.push(`"${$.target}"`);if(W.length>0)W=W.map((Y)=>`"\`"${Y}\`""`),G.push("-ArgumentList",W.join(","));$.target=I20.from(G.join(" "),"utf16le").toString("base64")}else{if(f)J=f;else{let w=!aI||aI==="/",G=!1;try{await tI.access(Xy,Ly.X_OK),G=!0}catch{}J=JX.versions.electron??(lW==="android"||w||!G)?"xdg-open":Xy}if(W.length>0)Z.push(...W);if(!$.wait)X.stdio="ignore",X.detached=!0}if(lW==="darwin"&&W.length>0)Z.push("--args",...W);if($.target)Z.push($.target);let z=A20.spawn(J,Z,X);if($.wait)return new Promise((w,G)=>{z.once("error",G),z.once("close",(Y)=>{if(!$.allowNonzeroExitCode&&Y>0){G(new Error(`Exited with code ${Y}`));return}w(z)})});return z.unref(),z},_20=($,f)=>{if(typeof $!=="string")throw new TypeError("Expected a `target`");return cY({...f,target:$})};function Gy($){if(typeof $==="string"||Array.isArray($))return $;let{[zy]:f}=$;if(!f)throw new Error(`${zy} is not supported`);return f}function oI({[lW]:$},{wsl:f}){if(f&&WX)return Gy(f);if(!$)throw new Error(`${lW} is not supported`);return Gy($)}var pW={};C5(pW,"chrome",()=>oI({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));C5(pW,"firefox",()=>oI({darwin:"firefox",win32:"C:\\Program Files\\Mozilla Firefox\\firefox.exe",linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));C5(pW,"edge",()=>oI({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));C5(pW,"browser",()=>"browser");C5(pW,"browserPrivate",()=>"browserPrivate");var Ky=_20;_();import{execSync as N20,exec as S20}from"node:child_process";import{readFile as Hy,writeFile as F20}from"node:fs/promises";import p4 from"node:path";import B20 from"node:url";function ZX(){let $=p4.dirname(B20.fileURLToPath(import.meta.url));return p4.resolve($,process.env.LOCAL?"../../../":"../../")}function eI(){return p4.resolve(ZX(),"dist")}function E5(){return p4.relative(process.cwd(),eI())}async function n4($=""){try{let f=p4.resolve(ZX(),p4.join($,"package.json")),W=await Hy(f,"utf-8");if(W)return JSON.parse(W).version??"preview"}catch(f){console.error("Failed to resolve version")}return"unknown"}async function $O($){try{return await Hy(p4.resolve(process.cwd(),$)),!0}catch{return!1}}async function Uy($,f){try{return await F20(p4.resolve(process.cwd(),$),f),!0}catch(W){return A.error("Failed to write file",W),!1}}function fO($,f){let W=f?.silent?"pipe":"inherit",J=N20($,{stdio:["inherit",W,W],env:{...process.env,...f?.env}});if(!f?.silent)return;return J.toString()}function Ry($,f){return new Promise((W,J)=>{S20($,{env:{...process.env,...f?.env}},(Z,X,z)=>{if(Z)return J(Z);W(X)})})}var wj=["node","bun"];async function Gj($){switch($){case"node":return(await Promise.resolve().then(() => (Oy(),Iy))).serveStatic({root:E5()+"/static"});case"bun":return(await Promise.resolve().then(() => (ay(),ty))).serveStatic({root:MO.resolve(E5(),"static")})}}async function Yj($,f,W){let J=W.port;switch(A.log(`Using ${$} serve`),$){case"node":{(await Promise.resolve().then(() => (zj(),Xj)).then((z)=>z.serve))({fetch:(z)=>f.fetch(z),port:J});break}case"bun":{Bun.serve({fetch:(X)=>f.fetch(X),port:J});break}}let Z=`http://localhost:${J}`;if(A.info("Server listening on",Z),W.open)await Ky(Z)}async function Lj($){if($){let J=MO.resolve(process.cwd(),$);if(await $O(J))return J}let W=["",".js",".ts",".mjs",".cjs",".json"].map((J)=>`bknd.config${J}`);for(let J of W){let Z=MO.resolve(process.cwd(),J);if(await $O(Z))return Z}return}function sY(){let $=process.env.DB_URL,f=process.env.DB_TOKEN;return $?{url:$,authToken:f}:void 0}P5();_();function qO($,f){let W={},{app:J,...Z}=$;if(J)if(typeof J==="function"){if(!f)throw new Error("args is required when config.app is a function");W=J(f)}else W=J;return{...Z,...W}}var Rj=new Map;async function O90($={},f,W){let J=W?.id??"app",Z=Rj.get(J);if(!Z||W?.force){let X=qO($,f);if(!X.connection||!F$.isConnection(X.connection)){let z;if(F$.isConnection($.connection))z=$.connection;else{let w=(await Promise.resolve().then(() => (Uj(),Hj))).sqlite,G=X.connection??{url:":memory:"};z=w(G),A.info(`Using ${z.name} connection`,G.url)}X.connection=z}Z=iW.create(X),Rj.set(J,Z)}return Z}async function Mj({serveStatic:$,adminOptions:f,...W}={},J,Z){let X=await O90(W,J,Z);if(!X.isBuilt())X.emgr.onEvent(iW.Events.AppBuiltEvent,async()=>{if($){let[z,w]=Array.isArray($)?$:[pf.server.assets_path+"*",$];X.modules.server.get(z,w)}if(await W.onBuilt?.(X),f!==!1)X.registerAdminController(f)},"sync"),await W.beforeBuild?.(X),await X.build(W.buildConfig);return X}_();var x90=[".env",".dev.vars"];Qj.default.config({path:x90.map(($)=>A90.resolve(process.cwd(),$))});var _90=Hz(),Ij=($)=>{$.command("run").description("run an instance").addOption(new Q1("-p, --port <port>","port to run on").env("PORT").default(pf.server.default_port).argParser((f)=>Number.parseInt(f))).addOption(new Q1("-m, --memory","use in-memory database").conflicts(["config","db-url","db-token"])).addOption(new Q1("-c, --config <config>","config file")).addOption(new Q1("--db-url <db>","database url, can be any valid sqlite url").conflicts("config")).addOption(new Q1("--server <server>","server type").choices(wj).default(_90?"bun":"node")).addOption(new Q1("--no-open","don't open browser window on start")).action(N90)},qj=bY.prototype.getName();if(!y7.media.has(qj))y7.media.register(qj,bY);async function tY($){return await Mj({serveStatic:await Gj($.server?.platform??"node"),...$})}async function Vj($,f){let W=qO($,process.env);return tY({...W,server:{platform:f}})}async function KX($={}){let f=await Lj($.config),W=void 0;if($.dbUrl){console.info("Using connection from",D5.default.cyan("--db-url"),D5.default.cyan($.dbUrl));let J=$.dbUrl?{url:$.dbUrl}:void 0;W=await tY({connection:J,server:{platform:$.server}})}else if(f){console.info("Using config from",D5.default.cyan(f));try{let J=await import(f).then((Z)=>Z.default);W=await Vj(J,$.server)}catch(J){console.error("Failed to load config:",J),process.exit(1)}}else if($.memory)console.info("Using",D5.default.cyan("in-memory"),"connection"),W=await tY({server:{platform:$.server}});else{let J=sY();if(J)console.info("Using connection from env",D5.default.cyan(J.url)),W=await Vj({app:{connection:J}},$.server)}if(!W){let J={url:"file:data.db"};console.info("Using fallback connection",D5.default.cyan(J.url)),W=await tY({connection:J,server:{platform:$.server}})}return W}async function N90($){U_(console);let f=await KX($);await Yj($.server,f,{port:$.port,open:$.open})}NI();import xj from"node:path";import B90 from"node:url";function Oj(){let{process:$,Deno:f}=globalThis;return!(typeof f?.noColor==="boolean"?f.noColor:$!==void 0?"NO_COLOR"in $?.env:!1)}wO();var S90=($)=>{return $.name||(zX($)?"[middleware]":"[handler]")},F90=($)=>{return $.routes.map(({path:f,method:W,handler:J})=>{let Z=wX(J);return{path:f,method:W,name:S90(Z),isMiddleware:zX(Z)}})},Aj=($,f)=>{let W=f?.colorize??Oj(),J={},Z=0,X=0;F90($).filter(({isMiddleware:z})=>f?.verbose||!z).map((z)=>{let w=`${z.method}-${z.path}`;if((J[w]||=[]).push(z),J[w].length>1)return;return Z=Math.max(Z,z.method.length),X=Math.max(X,z.path.length),{method:z.method,path:z.path,routes:J[w]}}).forEach((z)=>{if(!z)return;let{method:w,path:G,routes:Y}=z,L=W?`\x1B[32m${w}\x1B[0m`:w;if(console.log(`${L} ${" ".repeat(Z-w.length)} ${G}`),!f?.verbose)return;Y.forEach(({name:U})=>{console.log(`${" ".repeat(Z+3)} ${U}`)})})};var _j=($)=>{$.command("debug").description("debug bknd").addArgument(new oX("<subject>","subject to debug").choices(Object.keys(VO))).action(T90)},VO={paths:async()=>{console.log("[PATHS]",{rootpath:ZX(),distPath:eI(),relativeDistPath:E5(),cwd:process.cwd(),dir:xj.dirname(B90.fileURLToPath(import.meta.url)),resolvedPkg:xj.resolve(ZX(),"package.json")})},routes:async()=>{console.log("[APP ROUTES]");let $=sY(),f=jY({connection:$});await f.build(),Aj(f.server)}};async function T90($){if($ in VO)await VO[$]();else console.error("Invalid subject: ",$)}import{stripVTControlCharacters as CO}from"node:util";var W$=q1(IO(),1),HX=q1(Ef(),1);import{stdin as vj,stdout as mj}from"node:process";import*as t4 from"node:readline";import Sj from"node:readline";import{WriteStream as E90}from"node:tty";function h90({onlyFirst:$=!1}={}){let f=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(f,$?void 0:"g")}var D90=h90();function kj($){if(typeof $!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof $}\``);return $.replace(D90,"")}function yj($){return $&&$.__esModule&&Object.prototype.hasOwnProperty.call($,"default")?$.default:$}var jj={exports:{}};(function($){var f={};$.exports=f,f.eastAsianWidth=function(J){var Z=J.charCodeAt(0),X=J.length==2?J.charCodeAt(1):0,z=Z;return 55296<=Z&&Z<=56319&&56320<=X&&X<=57343&&(Z&=1023,X&=1023,z=Z<<10|X,z+=65536),z==12288||65281<=z&&z<=65376||65504<=z&&z<=65510?"F":z==8361||65377<=z&&z<=65470||65474<=z&&z<=65479||65482<=z&&z<=65487||65490<=z&&z<=65495||65498<=z&&z<=65500||65512<=z&&z<=65518?"H":4352<=z&&z<=4447||4515<=z&&z<=4519||4602<=z&&z<=4607||9001<=z&&z<=9002||11904<=z&&z<=11929||11931<=z&&z<=12019||12032<=z&&z<=12245||12272<=z&&z<=12283||12289<=z&&z<=12350||12353<=z&&z<=12438||12441<=z&&z<=12543||12549<=z&&z<=12589||12593<=z&&z<=12686||12688<=z&&z<=12730||12736<=z&&z<=12771||12784<=z&&z<=12830||12832<=z&&z<=12871||12880<=z&&z<=13054||13056<=z&&z<=19903||19968<=z&&z<=42124||42128<=z&&z<=42182||43360<=z&&z<=43388||44032<=z&&z<=55203||55216<=z&&z<=55238||55243<=z&&z<=55291||63744<=z&&z<=64255||65040<=z&&z<=65049||65072<=z&&z<=65106||65108<=z&&z<=65126||65128<=z&&z<=65131||110592<=z&&z<=110593||127488<=z&&z<=127490||127504<=z&&z<=127546||127552<=z&&z<=127560||127568<=z&&z<=127569||131072<=z&&z<=194367||177984<=z&&z<=196605||196608<=z&&z<=262141?"W":32<=z&&z<=126||162<=z&&z<=163||165<=z&&z<=166||z==172||z==175||10214<=z&&z<=10221||10629<=z&&z<=10630?"Na":z==161||z==164||167<=z&&z<=168||z==170||173<=z&&z<=174||176<=z&&z<=180||182<=z&&z<=186||188<=z&&z<=191||z==198||z==208||215<=z&&z<=216||222<=z&&z<=225||z==230||232<=z&&z<=234||236<=z&&z<=237||z==240||242<=z&&z<=243||247<=z&&z<=250||z==252||z==254||z==257||z==273||z==275||z==283||294<=z&&z<=295||z==299||305<=z&&z<=307||z==312||319<=z&&z<=322||z==324||328<=z&&z<=331||z==333||338<=z&&z<=339||358<=z&&z<=359||z==363||z==462||z==464||z==466||z==468||z==470||z==472||z==474||z==476||z==593||z==609||z==708||z==711||713<=z&&z<=715||z==717||z==720||728<=z&&z<=731||z==733||z==735||768<=z&&z<=879||913<=z&&z<=929||931<=z&&z<=937||945<=z&&z<=961||963<=z&&z<=969||z==1025||1040<=z&&z<=1103||z==1105||z==8208||8211<=z&&z<=8214||8216<=z&&z<=8217||8220<=z&&z<=8221||8224<=z&&z<=8226||8228<=z&&z<=8231||z==8240||8242<=z&&z<=8243||z==8245||z==8251||z==8254||z==8308||z==8319||8321<=z&&z<=8324||z==8364||z==8451||z==8453||z==8457||z==8467||z==8470||8481<=z&&z<=8482||z==8486||z==8491||8531<=z&&z<=8532||8539<=z&&z<=8542||8544<=z&&z<=8555||8560<=z&&z<=8569||z==8585||8592<=z&&z<=8601||8632<=z&&z<=8633||z==8658||z==8660||z==8679||z==8704||8706<=z&&z<=8707||8711<=z&&z<=8712||z==8715||z==8719||z==8721||z==8725||z==8730||8733<=z&&z<=8736||z==8739||z==8741||8743<=z&&z<=8748||z==8750||8756<=z&&z<=8759||8764<=z&&z<=8765||z==8776||z==8780||z==8786||8800<=z&&z<=8801||8804<=z&&z<=8807||8810<=z&&z<=8811||8814<=z&&z<=8815||8834<=z&&z<=8835||8838<=z&&z<=8839||z==8853||z==8857||z==8869||z==8895||z==8978||9312<=z&&z<=9449||9451<=z&&z<=9547||9552<=z&&z<=9587||9600<=z&&z<=9615||9618<=z&&z<=9621||9632<=z&&z<=9633||9635<=z&&z<=9641||9650<=z&&z<=9651||9654<=z&&z<=9655||9660<=z&&z<=9661||9664<=z&&z<=9665||9670<=z&&z<=9672||z==9675||9678<=z&&z<=9681||9698<=z&&z<=9701||z==9711||9733<=z&&z<=9734||z==9737||9742<=z&&z<=9743||9748<=z&&z<=9749||z==9756||z==9758||z==9792||z==9794||9824<=z&&z<=9825||9827<=z&&z<=9829||9831<=z&&z<=9834||9836<=z&&z<=9837||z==9839||9886<=z&&z<=9887||9918<=z&&z<=9919||9924<=z&&z<=9933||9935<=z&&z<=9953||z==9955||9960<=z&&z<=9983||z==10045||z==10071||10102<=z&&z<=10111||11093<=z&&z<=11097||12872<=z&&z<=12879||57344<=z&&z<=63743||65024<=z&&z<=65039||z==65533||127232<=z&&z<=127242||127248<=z&&z<=127277||127280<=z&&z<=127337||127344<=z&&z<=127386||917760<=z&&z<=917999||983040<=z&&z<=1048573||1048576<=z&&z<=1114109?"A":"N"},f.characterLength=function(J){var Z=this.eastAsianWidth(J);return Z=="F"||Z=="W"||Z=="A"?2:1};function W(J){return J.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}f.length=function(J){for(var Z=W(J),X=0,z=0;z<Z.length;z++)X=X+this.characterLength(Z[z]);return X},f.slice=function(J,Z,X){textLen=f.length(J),Z=Z||0,X=X||1,Z<0&&(Z=textLen+Z),X<0&&(X=textLen+X);for(var z="",w=0,G=W(J),Y=0;Y<G.length;Y++){var L=G[Y],U=f.length(L);if(w>=Z-(U==2?1:0))if(w+U<=X)z+=L;else break;w+=U}return z}})(jj);var v90=jj.exports,m90=yj(v90),k90=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},y90=yj(k90);function UX($,f={}){if(typeof $!="string"||$.length===0||(f={ambiguousIsNarrow:!0,...f},$=kj($),$.length===0))return 0;$=$.replace(y90()," ");let W=f.ambiguousIsNarrow?1:2,J=0;for(let Z of $){let X=Z.codePointAt(0);if(X<=31||X>=127&&X<=159||X>=768&&X<=879)continue;switch(m90.eastAsianWidth(Z)){case"F":case"W":J+=2;break;case"A":J+=W;break;default:J+=1}}return J}var OO=10,Fj=($=0)=>(f)=>`\x1B[${f+$}m`,Bj=($=0)=>(f)=>`\x1B[${38+$};5;${f}m`,Tj=($=0)=>(f,W,J)=>`\x1B[${38+$};2;${f};${W};${J}m`,$1={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys($1.modifier);var j90=Object.keys($1.color),g90=Object.keys($1.bgColor);[...j90];function b90(){let $=new Map;for(let[f,W]of Object.entries($1)){for(let[J,Z]of Object.entries(W))$1[J]={open:`\x1B[${Z[0]}m`,close:`\x1B[${Z[1]}m`},W[J]=$1[J],$.set(Z[0],Z[1]);Object.defineProperty($1,f,{value:W,enumerable:!1})}return Object.defineProperty($1,"codes",{value:$,enumerable:!1}),$1.color.close="\x1B[39m",$1.bgColor.close="\x1B[49m",$1.color.ansi=Fj(),$1.color.ansi256=Bj(),$1.color.ansi16m=Tj(),$1.bgColor.ansi=Fj(OO),$1.bgColor.ansi256=Bj(OO),$1.bgColor.ansi16m=Tj(OO),Object.defineProperties($1,{rgbToAnsi256:{value:(f,W,J)=>f===W&&W===J?f<8?16:f>248?231:Math.round((f-8)/247*24)+232:16+36*Math.round(f/255*5)+6*Math.round(W/255*5)+Math.round(J/255*5),enumerable:!1},hexToRgb:{value:(f)=>{let W=/[a-f\d]{6}|[a-f\d]{3}/i.exec(f.toString(16));if(!W)return[0,0,0];let[J]=W;J.length===3&&(J=[...J].map((X)=>X+X).join(""));let Z=Number.parseInt(J,16);return[Z>>16&255,Z>>8&255,Z&255]},enumerable:!1},hexToAnsi256:{value:(f)=>$1.rgbToAnsi256(...$1.hexToRgb(f)),enumerable:!1},ansi256ToAnsi:{value:(f)=>{if(f<8)return 30+f;if(f<16)return 90+(f-8);let W,J,Z;if(f>=232)W=((f-232)*10+8)/255,J=W,Z=W;else{f-=16;let w=f%36;W=Math.floor(f/36)/5,J=Math.floor(w/6)/5,Z=w%6/5}let X=Math.max(W,J,Z)*2;if(X===0)return 30;let z=30+(Math.round(Z)<<2|Math.round(J)<<1|Math.round(W));return X===2&&(z+=60),z},enumerable:!1},rgbToAnsi:{value:(f,W,J)=>$1.ansi256ToAnsi($1.rgbToAnsi256(f,W,J)),enumerable:!1},hexToAnsi:{value:(f)=>$1.ansi256ToAnsi($1.hexToAnsi256(f)),enumerable:!1}}),$1}var u90=b90(),eY=new Set(["\x1B",""]),c90=39,_O="\x07",gj="[",d90="]",bj="m",NO=`${d90}8;;`,Pj=($)=>`${eY.values().next().value}${gj}${$}${bj}`,Cj=($)=>`${eY.values().next().value}${NO}${$}${_O}`,i90=($)=>$.split(" ").map((f)=>UX(f)),AO=($,f,W)=>{let J=[...f],Z=!1,X=!1,z=UX(kj($[$.length-1]));for(let[w,G]of J.entries()){let Y=UX(G);if(z+Y<=W?$[$.length-1]+=G:($.push(G),z=0),eY.has(G)&&(Z=!0,X=J.slice(w+1).join("").startsWith(NO)),Z){X?G===_O&&(Z=!1,X=!1):G===bj&&(Z=!1);continue}z+=Y,z===W&&w<J.length-1&&($.push(""),z=0)}!z&&$[$.length-1].length>0&&$.length>1&&($[$.length-2]+=$.pop())},r90=($)=>{let f=$.split(" "),W=f.length;for(;W>0&&!(UX(f[W-1])>0);)W--;return W===f.length?$:f.slice(0,W).join(" ")+f.slice(W).join("")},l90=($,f,W={})=>{if(W.trim!==!1&&$.trim()==="")return"";let J="",Z,X,z=i90($),w=[""];for(let[Y,L]of $.split(" ").entries()){W.trim!==!1&&(w[w.length-1]=w[w.length-1].trimStart());let U=UX(w[w.length-1]);if(Y!==0&&(U>=f&&(W.wordWrap===!1||W.trim===!1)&&(w.push(""),U=0),(U>0||W.trim===!1)&&(w[w.length-1]+=" ",U++)),W.hard&&z[Y]>f){let M=f-U,q=1+Math.floor((z[Y]-M-1)/f);Math.floor((z[Y]-1)/f)<q&&w.push(""),AO(w,L,f);continue}if(U+z[Y]>f&&U>0&&z[Y]>0){if(W.wordWrap===!1&&U<f){AO(w,L,f);continue}w.push("")}if(U+z[Y]>f&&W.wordWrap===!1){AO(w,L,f);continue}w[w.length-1]+=L}W.trim!==!1&&(w=w.map((Y)=>r90(Y)));let G=[...w.join(`
`)];for(let[Y,L]of G.entries()){if(J+=L,eY.has(L)){let{groups:M}=new RegExp(`(?:\\${gj}(?<code>\\d+)m|\\${NO}(?<uri>.*)${_O})`).exec(G.slice(Y).join(""))||{groups:{}};if(M.code!==void 0){let q=Number.parseFloat(M.code);Z=q===c90?void 0:q}else M.uri!==void 0&&(X=M.uri.length===0?void 0:M.uri)}let U=u90.codes.get(Number(Z));G[Y+1]===`
`?(X&&(J+=Cj("")),Z&&U&&(J+=Pj(U))):L===`
`&&(Z&&U&&(J+=Pj(Z)),X&&(J+=Cj(X)))}return J};function Ej($,f,W){return String($).normalize().replace(/\r\n/g,`
`).split(`
`).map((J)=>l90(J,f,W)).join(`
`)}var p90=["up","down","left","right","space","enter","cancel"],oY={actions:new Set(p90),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]])};function SO($,f){if(typeof $=="string")return oY.aliases.get($)===f;for(let W of $)if(W!==void 0&&SO(W,f))return!0;return!1}function n90($,f){if($===f)return;let W=$.split(`
`),J=f.split(`
`),Z=[];for(let X=0;X<Math.max(W.length,J.length);X++)W[X]!==J[X]&&Z.push(X);return Z}var s90=globalThis.process.platform.startsWith("win"),xO=Symbol("clack:cancel");function F1($){return $===xO}function aY($,f){let W=$;W.isTTY&&W.setRawMode(f)}function uj({input:$=vj,output:f=mj,overwrite:W=!0,hideCursor:J=!0}={}){let Z=t4.createInterface({input:$,output:f,prompt:"",tabSize:1});t4.emitKeypressEvents($,Z),$.isTTY&&$.setRawMode(!0);let X=(z,{name:w,sequence:G})=>{let Y=String(z);if(SO([Y,w,G],"cancel")){J&&f.write(W$.cursor.show),process.exit(0);return}if(!W)return;t4.moveCursor(f,w==="return"?0:-1,w==="return"?-1:0,()=>{t4.clearLine(f,1,()=>{$.once("keypress",X)})})};return J&&f.write(W$.cursor.hide),$.once("keypress",X),()=>{$.off("keypress",X),J&&f.write(W$.cursor.show),$.isTTY&&!s90&&$.setRawMode(!1),Z.terminal=!1,Z.close()}}var t90=Object.defineProperty,a90=($,f,W)=>(f in $)?t90($,f,{enumerable:!0,configurable:!0,writable:!0,value:W}):$[f]=W,ff=($,f,W)=>(a90($,typeof f!="symbol"?f+"":f,W),W);class RX{constructor($,f=!0){ff(this,"input"),ff(this,"output"),ff(this,"_abortSignal"),ff(this,"rl"),ff(this,"opts"),ff(this,"_render"),ff(this,"_track",!1),ff(this,"_prevFrame",""),ff(this,"_subscribers",new Map),ff(this,"_cursor",0),ff(this,"state","initial"),ff(this,"error",""),ff(this,"value");let{input:W=vj,output:J=mj,render:Z,signal:X,...z}=$;this.opts=z,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=Z.bind(this),this._track=f,this._abortSignal=X,this.input=W,this.output=J}unsubscribe(){this._subscribers.clear()}setSubscriber($,f){let W=this._subscribers.get($)??[];W.push(f),this._subscribers.set($,W)}on($,f){this.setSubscriber($,{cb:f})}once($,f){this.setSubscriber($,{cb:f,once:!0})}emit($,...f){let W=this._subscribers.get($)??[],J=[];for(let Z of W)Z.cb(...f),Z.once&&J.push(()=>W.splice(W.indexOf(Z),1));for(let Z of J)Z()}prompt(){return new Promise(($,f)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(xO);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}let W=new E90(0);W._write=(J,Z,X)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,""),this._cursor=this.rl?.cursor??0,this.emit("value",this.value)),X()},this.input.pipe(W),this.rl=Sj.createInterface({input:this.input,output:W,tabSize:2,prompt:"",escapeCodeTimeout:50}),Sj.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),aY(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(W$.cursor.show),this.output.off("resize",this.render),aY(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(W$.cursor.show),this.output.off("resize",this.render),aY(this.input,!1),$(xO)})})}onKeypress($,f){if(this.state==="error"&&(this.state="active"),f?.name&&(!this._track&&oY.aliases.has(f.name)&&this.emit("cursor",oY.aliases.get(f.name)),oY.actions.has(f.name)&&this.emit("cursor",f.name)),$&&($.toLowerCase()==="y"||$.toLowerCase()==="n")&&this.emit("confirm",$.toLowerCase()==="y"),$==="\t"&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),$&&this.emit("key",$.toLowerCase()),f?.name==="return"){if(this.opts.validate){let W=this.opts.validate(this.value);W&&(this.error=W instanceof Error?W.message:W,this.state="error",this.rl?.write(this.value))}this.state!=="error"&&(this.state="submit")}SO([$,f?.name,f?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
`),aY(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=Ej(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
`).length-1;this.output.write(W$.cursor.move(-999,$*-1))}render(){let $=Ej(this._render(this)??"",process.stdout.columns,{hard:!0});if($!==this._prevFrame){if(this.state==="initial")this.output.write(W$.cursor.hide);else{let f=n90(this._prevFrame,$);if(this.restoreCursor(),f&&f?.length===1){let W=f[0];this.output.write(W$.cursor.move(0,W)),this.output.write(W$.erase.lines(1));let J=$.split(`
`);this.output.write(J[W]),this._prevFrame=$,this.output.write(W$.cursor.move(0,J.length-W-1));return}if(f&&f?.length>1){let W=f[0];this.output.write(W$.cursor.move(0,W)),this.output.write(W$.erase.down());let J=$.split(`
`).slice(W);this.output.write(J.join(`
`)),this._prevFrame=$;return}this.output.write(W$.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}class FO extends RX{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor($){super($,!1),this.value=!!$.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",(f)=>{this.output.write(W$.cursor.move(0,-1)),this.value=f,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var o90=Object.defineProperty,e90=($,f,W)=>(f in $)?o90($,f,{enumerable:!0,configurable:!0,writable:!0,value:W}):$[f]=W,hj=($,f,W)=>(e90($,typeof f!="symbol"?f+"":f,W),W);class BO extends RX{constructor({mask:$,...f}){super(f),hj(this,"valueWithCursor",""),hj(this,"_mask","•"),this._mask=$??"•",this.on("finalize",()=>{this.valueWithCursor=this.masked}),this.on("value",()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${HX.default.inverse(HX.default.hidden("_"))}`;else{let W=this.masked.slice(0,this.cursor),J=this.masked.slice(this.cursor);this.valueWithCursor=`${W}${HX.default.inverse(J[0])}${J.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}}var $40=Object.defineProperty,f40=($,f,W)=>(f in $)?$40($,f,{enumerable:!0,configurable:!0,writable:!0,value:W}):$[f]=W,Dj=($,f,W)=>(f40($,typeof f!="symbol"?f+"":f,W),W);class TO extends RX{constructor($){super($,!1),Dj(this,"options"),Dj(this,"cursor",0),this.options=$.options,this.cursor=this.options.findIndex(({value:f})=>f===$.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",(f)=>{switch(f){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}}class PO extends RX{get valueWithCursor(){if(this.state==="submit")return this.value;if(this.cursor>=this.value.length)return`${this.value}█`;let $=this.value.slice(0,this.cursor),[f,...W]=this.value.slice(this.cursor);return`${$}${HX.default.inverse(f)}${W.join("")}`}get cursor(){return this._cursor}constructor($){super($),this.on("finalize",()=>{this.value||(this.value=$.defaultValue)})}}var N=q1(Ef(),1),$L=q1(IO(),1);import z2 from"node:process";function W40(){return z2.platform!=="win32"?z2.env.TERM!=="linux":!!z2.env.CI||!!z2.env.WT_SESSION||!!z2.env.TERMINUS_SUBLIME||z2.env.ConEmuTask==="{cmd::Cmder}"||z2.env.TERM_PROGRAM==="Terminus-Sublime"||z2.env.TERM_PROGRAM==="vscode"||z2.env.TERM==="xterm-256color"||z2.env.TERM==="alacritty"||z2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var EO=W40(),Y1=($,f)=>EO?$:f,J40=Y1("◆","*"),dj=Y1("■","x"),ij=Y1("▲","x"),fL=Y1("◇","o"),Z40=Y1("┌","T"),A0=Y1("│","|"),v5=Y1("└","—"),hO=Y1("●",">"),DO=Y1("○"," "),ro0=Y1("◻","[•]"),lo0=Y1("◼","[+]"),po0=Y1("◻","[ ]"),X40=Y1("▪","•"),no0=Y1("─","-"),so0=Y1("╮","+"),to0=Y1("├","+"),ao0=Y1("╯","+"),rj=Y1("●","•"),lj=Y1("◆","*"),pj=Y1("▲","!"),nj=Y1("■","x"),WL=($)=>{switch($){case"initial":case"active":return N.default.cyan(J40);case"cancel":return N.default.red(dj);case"error":return N.default.yellow(ij);case"submit":return N.default.green(fL)}},z40=($)=>{let{cursor:f,options:W,style:J}=$,Z=$.maxItems??Number.POSITIVE_INFINITY,X=Math.max(process.stdout.rows-4,0),z=Math.min(X,Math.max(Z,5)),w=0;f>=w+z-3?w=Math.max(Math.min(f-z+3,W.length-z),0):f<w+2&&(w=Math.max(f-2,0));let G=z<W.length&&w>0,Y=z<W.length&&w+z<W.length;return W.slice(w,w+z).map((L,U,M)=>{let q=U===0&&G,V=U===M.length-1&&Y;return q||V?N.default.dim("..."):J(L,U+w===f)})},i9=($)=>new PO({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,render(){let f=`${N.default.gray(A0)}
${WL(this.state)} ${$.message}
`,W=$.placeholder?N.default.inverse($.placeholder[0])+N.default.dim($.placeholder.slice(1)):N.default.inverse(N.default.hidden("_")),J=this.value?this.valueWithCursor:W;switch(this.state){case"error":return`${f.trim()}
${N.default.yellow(A0)} ${J}
${N.default.yellow(v5)} ${N.default.yellow(this.error)}
`;case"submit":return`${f}${N.default.gray(A0)} ${N.default.dim(this.value||$.placeholder)}`;case"cancel":return`${f}${N.default.gray(A0)} ${N.default.strikethrough(N.default.dim(this.value??""))}${this.value?.trim()?`
${N.default.gray(A0)}`:""}`;default:return`${f}${N.default.cyan(A0)} ${J}
${N.default.cyan(v5)}
`}}}).prompt(),vO=($)=>new BO({validate:$.validate,mask:$.mask??X40,render(){let f=`${N.default.gray(A0)}
${WL(this.state)} ${$.message}
`,W=this.valueWithCursor,J=this.masked;switch(this.state){case"error":return`${f.trim()}
${N.default.yellow(A0)} ${J}
${N.default.yellow(v5)} ${N.default.yellow(this.error)}
`;case"submit":return`${f}${N.default.gray(A0)} ${N.default.dim(J)}`;case"cancel":return`${f}${N.default.gray(A0)} ${N.default.strikethrough(N.default.dim(J??""))}${J?`
${N.default.gray(A0)}`:""}`;default:return`${f}${N.default.cyan(A0)} ${W}
${N.default.cyan(v5)}
`}}}).prompt(),MX=($)=>{let f=$.active??"Yes",W=$.inactive??"No";return new FO({active:f,inactive:W,initialValue:$.initialValue??!0,render(){let J=`${N.default.gray(A0)}
${WL(this.state)} ${$.message}
`,Z=this.value?f:W;switch(this.state){case"submit":return`${J}${N.default.gray(A0)} ${N.default.dim(Z)}`;case"cancel":return`${J}${N.default.gray(A0)} ${N.default.strikethrough(N.default.dim(Z))}
${N.default.gray(A0)}`;default:return`${J}${N.default.cyan(A0)} ${this.value?`${N.default.green(hO)} ${f}`:`${N.default.dim(DO)} ${N.default.dim(f)}`} ${N.default.dim("/")} ${this.value?`${N.default.dim(DO)} ${N.default.dim(W)}`:`${N.default.green(hO)} ${W}`}
${N.default.cyan(v5)}
`}}}).prompt()},JL=($)=>{let f=(W,J)=>{let Z=W.label??String(W.value);switch(J){case"selected":return`${N.default.dim(Z)}`;case"active":return`${N.default.green(hO)} ${Z} ${W.hint?N.default.dim(`(${W.hint})`):""}`;case"cancelled":return`${N.default.strikethrough(N.default.dim(Z))}`;default:return`${N.default.dim(DO)} ${N.default.dim(Z)}`}};return new TO({options:$.options,initialValue:$.initialValue,render(){let W=`${N.default.gray(A0)}
${WL(this.state)} ${$.message}
`;switch(this.state){case"submit":return`${W}${N.default.gray(A0)} ${f(this.options[this.cursor],"selected")}`;case"cancel":return`${W}${N.default.gray(A0)} ${f(this.options[this.cursor],"cancelled")}
${N.default.gray(A0)}`;default:return`${W}${N.default.cyan(A0)} ${z40({cursor:this.cursor,options:this.options,maxItems:$.maxItems,style:(J,Z)=>f(J,Z?"active":"inactive")}).join(`
${N.default.cyan(A0)} `)}
${N.default.cyan(v5)}
`}}}).prompt()};var sj=($="")=>{process.stdout.write(`${N.default.gray(Z40)} ${$}
`)},mO=($="")=>{process.stdout.write(`${N.default.gray(A0)}
${N.default.gray(v5)} ${$}
`)},k0={message:($="",{symbol:f=N.default.gray(A0)}={})=>{let W=[`${N.default.gray(A0)}`];if($){let[J,...Z]=$.split(`
`);W.push(`${f} ${J}`,...Z.map((X)=>`${N.default.gray(A0)} ${X}`))}process.stdout.write(`${W.join(`
`)}
`)},info:($)=>{k0.message($,{symbol:N.default.blue(rj)})},success:($)=>{k0.message($,{symbol:N.default.green(lj)})},step:($)=>{k0.message($,{symbol:N.default.green(fL)})},warn:($)=>{k0.message($,{symbol:N.default.yellow(pj)})},warning:($)=>{k0.warn($)},error:($)=>{k0.message($,{symbol:N.default.red(nj)})}},cj=`${N.default.gray(A0)} `,M$={message:async($,{symbol:f=N.default.gray(A0)}={})=>{process.stdout.write(`${N.default.gray(A0)}
${f} `);let W=3;for await(let J of $){J=J.replace(/\n/g,`
${cj}`),J.includes(`
`)&&(W=3+CO(J.slice(J.lastIndexOf(`
`))).length);let Z=CO(J).length;W+Z<process.stdout.columns?(W+=Z,process.stdout.write(J)):(process.stdout.write(`
${cj}${J.trimStart()}`),W=3+CO(J.trimStart()).length)}process.stdout.write(`
`)},info:($)=>M$.message($,{symbol:N.default.blue(rj)}),success:($)=>M$.message($,{symbol:N.default.green(lj)}),step:($)=>M$.message($,{symbol:N.default.green(fL)}),warn:($)=>M$.message($,{symbol:N.default.yellow(pj)}),warning:($)=>M$.warn($),error:($)=>M$.message($,{symbol:N.default.red(nj)})},kO=({indicator:$="dots"}={})=>{let f=EO?["◒","◐","◓","◑"]:["•","o","O","0"],W=EO?80:120,J=process.env.CI==="true",Z,X,z=!1,w="",G,Y=performance.now(),L=(B)=>{let i=B>1?"Something went wrong":"Canceled";z&&F(i,B)},U=()=>L(2),M=()=>L(1),q=()=>{process.on("uncaughtExceptionMonitor",U),process.on("unhandledRejection",U),process.on("SIGINT",M),process.on("SIGTERM",M),process.on("exit",L)},V=()=>{process.removeListener("uncaughtExceptionMonitor",U),process.removeListener("unhandledRejection",U),process.removeListener("SIGINT",M),process.removeListener("SIGTERM",M),process.removeListener("exit",L)},Q=()=>{if(G===void 0)return;J&&process.stdout.write(`
`);let B=G.split(`
`);process.stdout.write($L.cursor.move(-999,B.length-1)),process.stdout.write($L.erase.down(B.length))},O=(B)=>B.replace(/\.+$/,""),x=(B)=>{let i=(performance.now()-B)/1000,w0=Math.floor(i/60),L0=Math.floor(i%60);return w0>0?`[${w0}m ${L0}s]`:`[${L0}s]`},y=(B="")=>{z=!0,Z=uj(),w=O(B),Y=performance.now(),process.stdout.write(`${N.default.gray(A0)}
`);let i=0,w0=0;q(),X=setInterval(()=>{if(J&&w===G)return;Q(),G=w;let L0=N.default.magenta(f[i]);if(J)process.stdout.write(`${L0} ${w}...`);else if($==="timer")process.stdout.write(`${L0} ${w} ${x(Y)}`);else{let K0=".".repeat(Math.floor(w0)).slice(0,3);process.stdout.write(`${L0} ${w}${K0}`)}i=i+1<f.length?i+1:0,w0=w0<f.length?w0+0.125:0},W)},F=(B="",i=0)=>{z=!1,clearInterval(X),Q();let w0=i===0?N.default.green(fL):i===1?N.default.red(dj):N.default.red(ij);w=O(B??w),$==="timer"?process.stdout.write(`${w0} ${w} ${x(Y)}
`):process.stdout.write(`${w0} ${w}
`),V(),Z()};return{start:y,stop:F,message:(B="")=>{w=O(B??w)}}};_();var m5=q1(Ef(),1);_();var aj=($)=>{$.command("user").description("create/update users, or generate a token (auth)").addArgument(new oX("<action>","action to perform").choices(["create","update","token"])).action(w40)};async function w40($,f){let W=await KX({server:"node"});switch($){case"create":await G40(W,f);break;case"update":await Y40(W,f);break;case"token":await L40(W,f);break}}async function G40($,f){let W=$.module.auth.authenticator.strategy("password");if(!W)k0.error("Password strategy not configured"),process.exit(1);let J=await i9({message:"Enter email",validate:(X)=>{if(!X.includes("@"))return"Invalid email";return}});if(F1(J))process.exit(1);let Z=await vO({message:"Enter password",validate:(X)=>{if(X.length<3)return"Invalid password";return}});if(F1(Z))process.exit(1);try{let X=await $.createUser({email:J,password:await W.hash(Z)});k0.success(`Created user: ${m5.default.cyan(X.email)}`)}catch(X){k0.error("Error creating user"),A.error(X)}}async function Y40($,f){let W=$.module.auth.toJSON(!0),J=$.module.auth.authenticator.strategy("password"),Z=W.entity_name,X=$.modules.ctx().em,z=await i9({message:"Which user? Enter email",validate:(Y)=>{if(!Y.includes("@"))return"Invalid email";return}});if(F1(z))process.exit(1);let{data:w}=await X.repository(Z).findOne({email:z});if(!w)k0.error("User not found"),process.exit(1);k0.info(`User found: ${m5.default.cyan(w.email)}`);let G=await vO({message:"New Password?",validate:(Y)=>{if(Y.length<3)return"Invalid password";return}});if(F1(G))process.exit(1);try{let Y=function(L){let U=X.entity(Z).field("strategy_value");U.config.hidden=!L,U.config.fillable=L};Y(!0),await $.modules.ctx().em.mutator(Z).updateOne(w.id,{strategy_value:await J.hash(G)}),Y(!1),k0.success(`Updated user: ${m5.default.cyan(w.email)}`)}catch(Y){k0.error("Error updating user"),A.error(Y)}}async function L40($,f){if(Hz())k0.error("Please use node to generate tokens"),process.exit(1);let J=$.module.auth.toJSON(!0).entity_name,Z=$.modules.ctx().em,X=await i9({message:"Which user? Enter email",validate:(w)=>{if(!w.includes("@"))return"Invalid email";return}});if(F1(X))process.exit(1);let{data:z}=await Z.repository(J).findOne({email:X});if(!z)k0.error("User not found"),process.exit(1);k0.info(`User found: ${m5.default.cyan(z.email)}`),console.log(`
${m5.default.dim("Token:")}
${m5.default.yellow(await $.module.auth.authenticator.jwt(z))}
`)}import zW0 from"node:fs";import D80 from"node:fs/promises";import bX from"node:fs";import wK from"node:path";var Cc=q1(Sc(),1);import gX from"node:fs/promises";import Pc from"node:fs";import T80 from"node:os";import Sx from"node:path";import{pipeline as P80}from"node:stream";import{promisify as C80}from"node:util";class Ax extends Error{}class zK extends Error{}class xx extends Error{}class _x extends Error{}import N80 from"node:path";var Fc=async($,f)=>{let W=new URL($),J=N80.basename(W.pathname);return{name:J,version:void 0,subdir:void 0,url:W.href,tar:W.href,defaultDir:J,headers:f.auth?{Authorization:`Bearer ${f.auth}`}:void 0}},Bc=async($,f)=>{let W=yX($),J=await Nx(W,f,async()=>{return(await(await AJ(`https://api.github.com/repos/${W.repo}`)).json())?.default_branch});return{name:W.repo.replace("/","-"),version:J,subdir:W.subdir,headers:{...f.auth?{Authorization:`Bearer ${f.auth}`}:{},Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},url:`https://github.com/${W.repo}/tree/${J}${W.subdir}`,tar:`https://api.github.com/repos/${W.repo}/tarball/${J}`}},S80=async($,f)=>{let W=yX($),J=await Nx(W,f,async()=>{return(await(await AJ(`https://gitlab.com/api/v4/projects/${encodeURIComponent(W.repo)}`)).json())?.default_branch});return{name:W.repo.replace("/","-"),version:J,subdir:W.subdir,headers:{...f.auth?{Authorization:`Bearer ${f.auth}`}:{},"sec-fetch-mode":"same-origin"},url:`https://gitlab.com/${W.repo}/tree/${J}${W.subdir}`,tar:`https://gitlab.com/${W.repo}/-/archive/${J}.tar.gz`}},F80=async($,f)=>{let W=yX($),J=await Nx(W,f,async()=>{return(await(await AJ(`https://api.bitbucket.org/2.0/repositories/${W.repo}`)).json())?.mainbranch?.name});return{name:W.repo.replace("/","-"),version:J,subdir:W.subdir,headers:f.auth?{Authorization:`Bearer ${f.auth}`}:{},url:`https://bitbucket.com/${W.repo}/src/${J}${W.subdir}`,tar:`https://bitbucket.org/${W.repo}/get/${J}.tar.gz`}},B80=($,f)=>{let W=yX($),J=W.ref||"main";return{name:W.repo.replace("/","-"),version:J,subdir:W.subdir,headers:f.auth?{Authorization:`Bearer ${f.auth}`}:{},url:`https://git.sr.ht/~${W.repo}/tree/${J}/item${W.subdir}`,tar:`https://git.sr.ht/~${W.repo}/archive/${J}.tar.gz`}},Tc={http:Fc,https:Fc,github:Bc,gh:Bc,gitlab:S80,bitbucket:F80,sourcehut:B80};async function Nx($,f,W){if($.ref)return $.ref;if(f.offline!==!0)try{let J=await W();if(J)return J}catch(J){jX(`Failed to fetch ref for ${$.repo}`,J)}return"main"}var E80=/^([\w-.]+):/;function Ec($,f,W){f||="github";let J=$,Z=$.match(E80);if(Z){if(f=Z[1],f!=="http"&&f!=="https")J=$.slice(Z[0].length)}let X=W?.[f]||Tc[f];return{source:J,providerName:f,provider:X}}async function hc($,f,W={}){let J=f+".json",Z=JSON.parse(await gX.readFile(J,"utf8").catch(()=>"{}")),z=(await AJ($,{...W,method:"HEAD"}).catch(()=>{return}))?.headers.get("etag");if(Z.etag===z&&Pc.existsSync(f))return;if(typeof z==="string")Z.etag=z;let w=await AJ($,{headers:W.headers});if(w.status>=400)throw new zK(`Failed to download ${$}: ${w.status} ${w.statusText}`);if(w.body==null)throw new zK(`Failed to download ${$}: empty response body`);await gX.mkdir(Sx.dirname(f),{recursive:!0});let G=Pc.createWriteStream(f);await C80(P80)(w.body,G),await gX.writeFile(J,JSON.stringify(Z),"utf8")}var h80=/^(?<repo>[\w\-.]+\/[\w\-.]+)(?<subdir>[^#]+)?(?<ref>#[\w\-./@]+)?/;function yX($){let f=$.match(h80)?.groups||{};return{repo:f.repo,subdir:f.subdir||"/",ref:f.ref?.slice(1)}}function jX(...$){if(process.env.DEBUG)console.debug("[giget]",...$)}async function AJ($,f={}){if(f.headers?.["sec-fetch-mode"])f.mode=f.headers["sec-fetch-mode"];let W=await fetch($,f).catch((J)=>{throw new Error(`Failed to fetch ${$}`,{cause:J})});if(f.validateStatus&&W.status>=400)throw new Error(`Failed to fetch ${$}: ${W.status} ${W.statusText}`);return W}function Dc(){return process.env.XDG_CACHE_HOME?Sx.resolve(process.env.XDG_CACHE_HOME,"bluwy-giget"):Sx.resolve(T80.homedir(),".cache/bluwy-giget")}async function vc($,f,W){if(W==="/")W=void 0;if(W){if(W.startsWith("/"))W=W.slice(1);if(!W.endsWith("/"))W+="/"}let J=!1;if(await gX.mkdir(f,{recursive:!0}),await Cc.extract({file:$,cwd:f,onentry(Z){if(Z.path=Z.path.split("/").splice(1).join("/"),W)if(Z.path.startsWith(W))Z.path=Z.path.slice(W.length-1),J=!0;else Z.path=""}}),W&&!J)throw await gX.rm(f,{recursive:!0,force:!0}),new xx(`Subdirectory not found in tar: ${W}`)}async function Fx($,f={}){let{source:W,providerName:J,provider:Z}=Ec($,f.provider,f.providers);if(!Z)throw new Ax(`Unsupported provider: ${J}`);let X={...f.providerOptions,offline:f.offline},z=await Promise.resolve().then(()=>Z(W,X)).catch((U)=>{throw new Error(`The ${J} provider failed with errors`,{cause:U})});z.name=(z.name||"template").replace(/[^\da-z-]/gi,"-"),z.defaultDir=(z.defaultDir||z.name).replace(/[^\da-z-]/gi,"-");let w=wK.resolve(Dc(),J,z.name),G=wK.resolve(w,(z.version||z.name)+".tar.gz");if(f.offline==="prefer"?!bX.existsSync(G):!f.offline)await hc(z.tar,G,{headers:z.headers}).catch((U)=>{if(!bX.existsSync(G))throw U;jX("Download error. Using cached version:",U)}),jX(`Downloaded ${z.tar} to ${G}`);if(!bX.existsSync(G))throw new Error(`Tarball not found: ${G} (offline: ${f.offline})`);let Y=wK.resolve(f.cwd||"."),L=wK.resolve(Y,f.dir||z.defaultDir);if(f.force==="clean")await D80.rm(L,{recursive:!0,force:!0});else if(!f.force&&bX.existsSync(L)&&bX.readdirSync(L).length>0)throw new _x(`Destination ${L} already exists.`);return await vc(G,L,z.subdir),{info:z,source:W,dir:L}}var mc=process.env.LOCAL,v80=mc?0:250;async function w4($=1,f){let W=f===!0?$:v80*$;return new Promise((J)=>setTimeout(J,W))}function kc({onlyFirst:$=!1}={}){let W=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(W,$?void 0:"g")}var m80=mc?0:20;async function*Y2($,f,W){let J=m80*(W??1),Z=kc(),X=[],z,w=0;while((z=Z.exec($))!==null){if(w<z.index)X.push(...$.slice(w,z.index).split(""));X.push(z[0]),w=Z.lastIndex}if(w<$.length)X.push(...$.slice(w).split(""));for(let G of X)if(yield f?f(G):G,!Z.test(G))await w4(J,!0)}P5();var l0=q1(Ef(),1);import{readFile as k80,writeFile as y80}from"node:fs/promises";import j80 from"node:path";async function xJ($,f,W){let J=j80.resolve(W?.dir??process.cwd(),$),Z=await k80(J,"utf-8"),X=await f(JSON.parse(Z));await y80(J,JSON.stringify(X,null,W?.indent||2))}async function Bx($,f){return await xJ("package.json",$,{dir:f?.dir})}var g80=["dependencies","devDependencies","optionalDependencies"];async function b80($,f){let W=f?.include??g80;await Bx(async(J)=>{for(let Z of W)if(Z in J)for(let[X,z]of Object.entries(J[Z])){let w=await $(X,z);if(w)J[Z][X]=w}return J},{dir:f?.dir})}async function yc($,f){let W={bknd:await n4(),...f??{}};await b80(async(J)=>{if(J in W)return W[J];return},{dir:$})}var Tx=q1(Ef(),1);var GK="wrangler.json",jc={key:"cloudflare",title:"Cloudflare Basic",integration:"cloudflare",description:"A basic bknd Cloudflare worker",path:"gh:bknd-io/bknd/examples/cloudflare-worker",ref:!0,setup:async($)=>{await xJ(GK,(f)=>({...f,name:$.name,assets:{directory:"node_modules/bknd/dist/static"}}),{dir:$.dir});try{await u80($)}catch(f){let W=f.message||"An error occurred";k0.warn("Couldn't add database. You can add it manually later. Error: "+Tx.default.red(W))}try{await c80($)}catch(f){let W=f.message||"An error occurred";k0.warn("Couldn't add R2 bucket. You can add it manually later. Error: "+Tx.default.red(W))}}};async function u80($){let W=$.skip?"data":await i9({message:"Enter database name",initialValue:"data",placeholder:"data",validate:(J)=>{if(!J)return"Invalid name";return}});if(F1(W))process.exit(1);if(await M$.info(async function*(){yield*Y2("Now running wrangler to create a D1 database...")}()),await xJ(GK,(J)=>({...J,d1_databases:[{binding:"DB",database_name:W,database_id:"00000000-0000-0000-0000-000000000000"}]}),{dir:$.dir}),!$.skip)fO(`npx wrangler d1 create ${W}`),await M$.info(async function*(){yield*Y2("Please update your wrangler configuration with the output above.")}())}async function c80($){let f=$.skip?!1:await MX({message:"Do you want to use a R2 bucket?",initialValue:!0});if(F1(f))process.exit(1);if(!f){await xJ(GK,(Z)=>({...Z,r2_buckets:void 0}),{dir:$.dir});return}let W="bucket",J=$.skip?W:await i9({message:"Enter bucket name",initialValue:W,placeholder:W,validate:(Z)=>{if(!Z)return"Invalid name";return}});if(F1(J))process.exit(1);if(await M$.info(async function*(){yield*Y2("Now running wrangler to create a R2 bucket...")}()),await xJ(GK,(Z)=>({...Z,r2_buckets:[{binding:"BUCKET",bucket_name:J}]}),{dir:$.dir}),!$.skip)fO(`npx wrangler r2 bucket create ${J}`)}var Px=[jc,{key:"node",title:"Node.js Basic",integration:"node",description:"A basic bknd Node.js server",path:"gh:bknd-io/bknd/examples/node",ref:!0},{key:"bun",title:"Bun Basic",integration:"bun",description:"A basic bknd Bun server",path:"gh:bknd-io/bknd/examples/bun",ref:!0},{key:"nextjs",title:"Next.js Basic",integration:"nextjs",description:"A basic bknd Next.js starter",path:"gh:bknd-io/bknd/examples/nextjs",ref:!0},{key:"astro",title:"Astro Basic",integration:"astro",description:"A basic bknd Astro starter",path:"gh:bknd-io/bknd/examples/astro",ref:!0},{key:"react-router",title:"React Router Basic",integration:"react-router",description:"A basic bknd React Router starter",path:"gh:bknd-io/bknd/examples/react-router",ref:!0},{key:"aws",title:"AWS Lambda Basic",integration:"aws",description:"A basic bknd AWS Lambda starter",path:"gh:bknd-io/bknd/examples/aws-lambda",ref:!0}];var Jd=q1(Wd(),1);P5();_();var _J=null,Zd=null,ZW0=Z1()||!!process.env.LOCAL,MK=W9("cli_telemetry",!ZW0);async function Xd(){try{if(!MK)return A.debug("telemetry disabled"),!1;if(A.debug("init telemetry"),!_J)_J=new Jd.PostHog("phc_uq8SqG4I65G35xWkJeBaLYQ2gKv3czneUhcS8PIQw7R",{host:"https://eu.i.posthog.com",disabled:!MK});return Zd=await n4(),!0}catch($){A.debug("failed to initialize telemetry",$)}return!1}function XW0(){if(!_J)throw new Error("PostHog client not initialized. Call init() first.");return _J}function qK($,f={}){try{if(!MK)return;let W=`cli_${$}`,J={...f,version:Zd};A.debug(`capture "${W}"`,J),XW0().capture(W,J)}catch(W){A.debug("failed to capture telemetry",W)}}function zd($,f={}){let W=f;return{capture:(Z,X={})=>{return qK(`${$}_${Z}`,{...W,...X})},properties:W}}async function rX(){try{if(!MK)return;if(A.debug("flush telemetry"),_J)await _J.flush()}catch($){A.debug("failed to flush telemetry",$)}}var VK={types:{runtime:"Runtime",framework:"Framework"},runtime:{node:"Node.js",bun:"Bun",cloudflare:"Cloudflare",aws:"AWS Lambda"},framework:{nextjs:"Next.js","react-router":"React Router",astro:"Astro"}},Gd=($)=>{$.command("create").addOption(new Q1("-i, --integration <integration>","integration to use")).addOption(new Q1("-t, --template <template>","template to use")).addOption(new Q1("-d --dir <directory>","directory to create in")).addOption(new Q1("-c, --clean","cleans destination directory")).addOption(new Q1("-y, --yes","use defaults, skip skippable prompts")).description("create a new project").action(wW0)};function wd(){mO(l0.default.red("Failed to create project.")),console.log(l0.default.yellow("Sorry that this happened. If you think this is a bug, please report it at: ")+l0.default.cyan("https://github.com/bknd-io/bknd/issues")),console.log(""),process.exit(1)}async function e2(){await rX()}async function wW0($){console.log("");let f=zd("create");f.capture("start",{options:$});let W={dir:$.dir||"./",clean:!1},J=await n4();if(sj(`\uD83D\uDC4B Welcome to the ${l0.default.bold(l0.default.cyan("bknd"))} create cli ${l0.default.bold(`v${J}`)}`),await M$.message(async function*(){yield*Y2("Thanks for choosing to create a new project with bknd!",l0.default.dim),await w4()}()),f.properties.at="dir",!$.dir){let w=await i9({message:"Where to create your project?",placeholder:W.dir,initialValue:W.dir});if(F1(w))await e2(),process.exit(1);W.dir=w||"./"}if(f.properties.at="dir",zW0.existsSync(W.dir)){let w=$.clean??await MX({message:`Directory ${l0.default.cyan(W.dir)} exists. Clean it?`,initialValue:!1});if(F1(w))await e2(),process.exit(1);W.clean=w,f.properties.clean=w}let Z=W.dir.includes("/")?W.dir.split("/").pop():W.dir.replace(/[./]/g,"");if(!Z||Z.length===0)Z="bknd";let X;if($.template){if(f.properties.at="template",X=Px.find((w)=>w.key===$.template),!X)await e2(),k0.error(`Template ${l0.default.cyan($.template)} not found`),process.exit(1)}else{f.properties.at="integration";let w=$.integration;if(!w){await M$.info(async function*(){yield*Y2("Ready? ",l0.default.bold,1.5),await w4(2),yield*Y2("Let's find the perfect template for you.",l0.default.dim),await w4(2)}());let Y=await JL({message:"Pick an integration type",options:Object.entries(VK.types).map(([U,M])=>({value:U,label:M,hint:Object.values(VK[U]).join(", ")}))});if(F1(Y))await e2(),process.exit(1);f.properties.type=Y;let L=await JL({message:`Which ${l0.default.cyan(VK.types[Y])} do you want to continue with?`,options:Object.entries(VK[Y]).map(([U,M])=>({value:U,label:M}))});if(F1(L))await e2(),process.exit(1);w=String(L),f.properties.integration=w}if(!w)await e2(),k0.error("No integration selected"),process.exit(1);let G=Px.filter((Y)=>Y.integration===w);if(G.length===0)await e2(),k0.error(`No templates found for "${l0.default.cyan(String(w))}"`),process.exit(1);else if(G.length>1){f.properties.at="template";let Y=await JL({message:"Pick a template",options:G.map((L)=>({value:L.key,label:L.title,hint:L.description}))});if(F1(Y))await e2(),process.exit(1);X=G.find((L)=>L.key===Y)}else X=G[0]}if(!X)await e2(),k0.error("No template selected"),process.exit(1);f.properties.template=X.key;let z={template:X,dir:W.dir,name:Z,skip:!!$.yes};{let w=W9("cli_create_ref",`#v${J}`,{onValid:(U)=>{k0.warn(l0.default.dim("[DEV] Using local ref: ")+l0.default.yellow(U))}});f.properties.ref=w,f.capture("used");let G=X.ref===!0?`#${w}`:typeof X.ref==="string"?`#${X.ref}`:"",Y=`${X.path}${G}`,L=kO();await L.start("Downloading template...");try{await Fx(Y,{dir:z.dir,force:W.clean?"clean":!0})}catch(U){if(U instanceof Error)L.stop("Failed to download template: "+l0.default.red(U.message),1);else console.error(U),L.stop("Failed to download template. Check logs above.",1);wd()}if(L.stop("Template downloaded."),await yc(z.dir),X.preinstall)await X.preinstall(z)}await Bx((w)=>({...w,name:z.name}),{dir:z.dir}),k0.success(`Updated package name to ${l0.default.cyan(z.name)}`);{let w=$.yes??await MX({message:"Install dependencies?"});if(F1(w))await e2(),process.exit(1);else if(w){f.properties.install=!0;let G=X.scripts?.install||"npm install",Y=kO();await Y.start("Installing dependencies...");try{await Ry(`cd ${z.dir} && ${G}`,{silent:!0})}catch(L){if(L instanceof Error)Y.stop("Failed to install: "+l0.default.red(L.message),1);else console.error(L),Y.stop("Failed to install. Check logs above.",1);wd()}if(Y.stop("Dependencies installed."),X.postinstall)await X.postinstall(z)}else f.properties.install=!1,await M$.warn(async function*(){yield*Y2(l0.default.dim("Remember to run ")+l0.default.cyan("npm install")+l0.default.dim(" after setup")),await w4()}())}if(X.setup)await X.setup(z);await M$.success(async function*(){yield*Y2("That's it! "),await w4(0.5),yield"\uD83C\uDF89",await w4(),yield`
`,yield*Y2(`Enter your project's directory using ${l0.default.cyan("cd "+z.dir)}
If you need help, check ${l0.default.cyan("https://docs.bknd.io")} or join our Discord!`),await w4(2)}()),f.capture("complete"),mO(l0.default.green("Setup complete."))}var hx=q1(Ef(),1);import QK from"node:fs/promises";import IK from"node:path";var Yd=($)=>{$.command("copy-assets").description("copy static assets").addOption(new Q1("-o --out <directory>","directory to copy to")).addOption(new Q1("-c --clean","clean the output directory")).action(GW0)};async function GW0($){let f=$.out??"static";if($.clean)await QK.rm(f,{recursive:!0,force:!0});let W=IK.resolve(E5(),"static");await QK.cp(W,f,{recursive:!0}),await QK.rename(IK.resolve(f,".vite/manifest.json"),IK.resolve(f,"manifest.json")),await QK.rm(IK.resolve(f,".vite"),{recursive:!0}),console.log(hx.default.green(`Assets copied to: ${hx.default.bold(f)}`))}pk();var Ld=q1(Ef(),1),Kd=($)=>{$.command("types").description("generate types").addOption(new Q1("-o, --outfile <outfile>","output file").default("bknd-types.d.ts")).addOption(new Q1("--no-write","do not write to file").default(!0)).action(YW0)};async function YW0({outfile:$,write:f}){let W=await KX({server:"node"});await W.build();let J=new kI(W.em);if(f)await Uy($,J.toString()),console.info(`
Types written to ${Ld.default.cyan($)}`);else console.info(J.toString())}var vx=new f_;async function LW0(){await Xd(),qK("start");let $=await n4();vx.name("bknd").description(OK.default.yellowBright("⚡")+" bknd cli "+OK.default.bold(OK.default.cyan(`v${$}`))).version($).hook("preAction",(f,W)=>{qK(`cmd_${W.name()}`)}).hook("postAction",async()=>{await rX()});for(let f of Object.values(Dx))f(vx);await vx.parseAsync()}LW0().then(null).catch(async($)=>{await rX(),console.error($)});export{LW0 as main};