@schemavaults/dbh 0.8.7 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/.claude/hooks/install-deps-in-fresh-environment.sh +5 -0
  2. package/.claude/settings.json +15 -0
  3. package/README.md +5 -5
  4. package/dist/adapters/abstract-schemavaults-dbh-adapter.d.ts +28 -0
  5. package/dist/adapters/abstract-schemavaults-dbh-adapter.js +50 -0
  6. package/dist/adapters/abstract-schemavaults-dbh-adapter.js.map +1 -0
  7. package/dist/adapters/schemavaults-postgres-adapter.d.ts +11 -0
  8. package/dist/adapters/schemavaults-postgres-adapter.js +31 -0
  9. package/dist/adapters/schemavaults-postgres-adapter.js.map +1 -0
  10. package/dist/adapters/schemavaults-postgres-neon-proxy-adapter.d.ts +18 -0
  11. package/dist/{schemavaults-postgres-neon-proxy-adapter.js → adapters/schemavaults-postgres-neon-proxy-adapter.js} +17 -63
  12. package/dist/adapters/schemavaults-postgres-neon-proxy-adapter.js.map +1 -0
  13. package/dist/create-dbh.d.ts +67 -0
  14. package/dist/create-dbh.js +17 -0
  15. package/dist/create-dbh.js.map +1 -0
  16. package/dist/index.d.ts +4 -2
  17. package/dist/index.js +7 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/migrate.d.ts +1 -1
  20. package/dist/migrate.js +1 -1
  21. package/dist/migrate.js.map +1 -1
  22. package/dist/types/IDatabaseHandler.d.ts +5 -0
  23. package/dist/types/IDatabaseHandler.js +2 -0
  24. package/dist/types/IDatabaseHandler.js.map +1 -0
  25. package/dist/types/PostgresDatabaseCredentials.js.map +1 -0
  26. package/dist/types/SchemaVaultsAppEnvironment.js.map +1 -0
  27. package/dist/utils/buildPostgresUrl.d.ts +1 -1
  28. package/dist/utils/getAppEnvironment.d.ts +1 -1
  29. package/dist/utils/getAppEnvironment.js +1 -1
  30. package/dist/utils/getAppEnvironment.js.map +1 -1
  31. package/dist/utils/getPostgresNeonWsProxyUrl.d.ts +1 -1
  32. package/dist/utils/getPostgresNeonWsProxyUrl.js +1 -1
  33. package/dist/utils/getPostgresNeonWsProxyUrl.js.map +1 -1
  34. package/dist/utils/isDbhInDebugMode.d.ts +2 -2
  35. package/dist/utils/parseDatabaseCredentials.d.ts +1 -1
  36. package/dist/utils/parseDatabaseCredentialsFromEnv.d.ts +1 -1
  37. package/dist/utils/parsePort.d.ts +1 -0
  38. package/dist/utils/parsePort.js +21 -0
  39. package/dist/utils/parsePort.js.map +1 -0
  40. package/dist-cli/build-db-migrations.js +8 -8
  41. package/dist-cli/cli.js +24 -24
  42. package/eslint.config.cjs +3 -1
  43. package/package.json +8 -6
  44. package/dist/PostgresDatabaseCredentials.js.map +0 -1
  45. package/dist/SchemaVaultsAppEnvironment.js.map +0 -1
  46. package/dist/schemavaults-postgres-neon-proxy-adapter.d.ts +0 -33
  47. package/dist/schemavaults-postgres-neon-proxy-adapter.js.map +0 -1
  48. /package/dist/{PostgresDatabaseCredentials.d.ts → types/PostgresDatabaseCredentials.d.ts} +0 -0
  49. /package/dist/{PostgresDatabaseCredentials.js → types/PostgresDatabaseCredentials.js} +0 -0
  50. /package/dist/{SchemaVaultsAppEnvironment.d.ts → types/SchemaVaultsAppEnvironment.d.ts} +0 -0
  51. /package/dist/{SchemaVaultsAppEnvironment.js → types/SchemaVaultsAppEnvironment.js} +0 -0
package/dist-cli/cli.js CHANGED
@@ -1,31 +1,31 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e7}from"node:module";var a7=Object.create;var{getPrototypeOf:d7,defineProperty:z9,getOwnPropertyNames:n7}=Object;var o7=Object.prototype.hasOwnProperty;var r7=(W,$,k)=>{k=W!=null?a7(d7(W)):{};let J=$||!W||!W.__esModule?z9(k,"default",{value:W,enumerable:!0}):k;for(let Z of n7(W))if(!o7.call(J,Z))z9(J,Z,{get:()=>W[Z],enumerable:!0});return J};var X0=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports);var $8=e7(import.meta.url);var k8=X0((W$)=>{class I4 extends Error{constructor(W,$,k){super(k);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=W,this.nestedError=void 0}}class G9 extends I4{constructor(W){super(1,"commander.invalidArgument",W);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}W$.CommanderError=I4;W$.InvalidArgumentError=G9});var y8=X0((X$)=>{var{InvalidArgumentError:J$}=k8();class M9{constructor(W,$){switch(this.description=$||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,W[0]){case"<":this.required=!0,this._name=W.slice(1,-1);break;case"[":this.required=!1,this._name=W.slice(1,-1);break;default:this.required=!0,this._name=W;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(W,$){if($===this.defaultValue||!Array.isArray($))return[W];return $.push(W),$}default(W,$){return this.defaultValue=W,this.defaultValueDescription=$,this}argParser(W){return this.parseArg=W,this}choices(W){return this.argChoices=W.slice(),this.parseArg=($,k)=>{if(!this.argChoices.includes($))throw new J$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue($,k);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Z$(W){let $=W.name()+(W.variadic===!0?"...":"");return W.required?"<"+$+">":"["+$+"]"}X$.Argument=M9;X$.humanReadableArgName=Z$});var y4=X0((G$)=>{var{humanReadableArgName:z$}=y8();class L9{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(W){this.helpWidth=this.helpWidth??W.helpWidth??80}visibleCommands(W){let $=W.commands.filter((J)=>!J._hidden),k=W._getHelpCommand();if(k&&!k._hidden)$.push(k);if(this.sortSubcommands)$.sort((J,Z)=>{return J.name().localeCompare(Z.name())});return $}compareOptions(W,$){let k=(J)=>{return J.short?J.short.replace(/^-/,""):J.long.replace(/^--/,"")};return k(W).localeCompare(k($))}visibleOptions(W){let $=W.options.filter((J)=>!J.hidden),k=W._getHelpOption();if(k&&!k.hidden){let J=k.short&&W._findOption(k.short),Z=k.long&&W._findOption(k.long);if(!J&&!Z)$.push(k);else if(k.long&&!Z)$.push(W.createOption(k.long,k.description));else if(k.short&&!J)$.push(W.createOption(k.short,k.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(W){if(!this.showGlobalOptions)return[];let $=[];for(let k=W.parent;k;k=k.parent){let J=k.options.filter((Z)=>!Z.hidden);$.push(...J)}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleArguments(W){if(W._argsDescription)W.registeredArguments.forEach(($)=>{$.description=$.description||W._argsDescription[$.name()]||""});if(W.registeredArguments.find(($)=>$.description))return W.registeredArguments;return[]}subcommandTerm(W){let $=W.registeredArguments.map((k)=>z$(k)).join(" ");return W._name+(W._aliases[0]?"|"+W._aliases[0]:"")+(W.options.length?" [options]":"")+($?" "+$:"")}optionTerm(W){return W.flags}argumentTerm(W){return W.name()}longestSubcommandTermLength(W,$){return $.visibleCommands(W).reduce((k,J)=>{return Math.max(k,this.displayWidth($.styleSubcommandTerm($.subcommandTerm(J))))},0)}longestOptionTermLength(W,$){return $.visibleOptions(W).reduce((k,J)=>{return Math.max(k,this.displayWidth($.styleOptionTerm($.optionTerm(J))))},0)}longestGlobalOptionTermLength(W,$){return $.visibleGlobalOptions(W).reduce((k,J)=>{return Math.max(k,this.displayWidth($.styleOptionTerm($.optionTerm(J))))},0)}longestArgumentTermLength(W,$){return $.visibleArguments(W).reduce((k,J)=>{return Math.max(k,this.displayWidth($.styleArgumentTerm($.argumentTerm(J))))},0)}commandUsage(W){let $=W._name;if(W._aliases[0])$=$+"|"+W._aliases[0];let k="";for(let J=W.parent;J;J=J.parent)k=J.name()+" "+k;return k+$+" "+W.usage()}commandDescription(W){return W.description()}subcommandDescription(W){return W.summary()||W.description()}optionDescription(W){let $=[];if(W.argChoices)$.push(`choices: ${W.argChoices.map((k)=>JSON.stringify(k)).join(", ")}`);if(W.defaultValue!==void 0){if(W.required||W.optional||W.isBoolean()&&typeof W.defaultValue==="boolean")$.push(`default: ${W.defaultValueDescription||JSON.stringify(W.defaultValue)}`)}if(W.presetArg!==void 0&&W.optional)$.push(`preset: ${JSON.stringify(W.presetArg)}`);if(W.envVar!==void 0)$.push(`env: ${W.envVar}`);if($.length>0){let k=`(${$.join(", ")})`;if(W.description)return`${W.description} ${k}`;return k}return W.description}argumentDescription(W){let $=[];if(W.argChoices)$.push(`choices: ${W.argChoices.map((k)=>JSON.stringify(k)).join(", ")}`);if(W.defaultValue!==void 0)$.push(`default: ${W.defaultValueDescription||JSON.stringify(W.defaultValue)}`);if($.length>0){let k=`(${$.join(", ")})`;if(W.description)return`${W.description} ${k}`;return k}return W.description}formatItemList(W,$,k){if($.length===0)return[];return[k.styleTitle(W),...$,""]}groupItems(W,$,k){let J=new Map;return W.forEach((Z)=>{let X=k(Z);if(!J.has(X))J.set(X,[])}),$.forEach((Z)=>{let X=k(Z);if(!J.has(X))J.set(X,[]);J.get(X).push(Z)}),J}formatHelp(W,$){let k=$.padWidth(W,$),J=$.helpWidth??80;function Z(R,h){return $.formatItem(R,k,h,$)}let X=[`${$.styleTitle("Usage:")} ${$.styleUsage($.commandUsage(W))}`,""],G=$.commandDescription(W);if(G.length>0)X=X.concat([$.boxWrap($.styleCommandDescription(G),J),""]);let z=$.visibleArguments(W).map((R)=>{return Z($.styleArgumentTerm($.argumentTerm(R)),$.styleArgumentDescription($.argumentDescription(R)))});if(X=X.concat(this.formatItemList("Arguments:",z,$)),this.groupItems(W.options,$.visibleOptions(W),(R)=>R.helpGroupHeading??"Options:").forEach((R,h)=>{let _=R.map((D)=>{return Z($.styleOptionTerm($.optionTerm(D)),$.styleOptionDescription($.optionDescription(D)))});X=X.concat(this.formatItemList(h,_,$))}),$.showGlobalOptions){let R=$.visibleGlobalOptions(W).map((h)=>{return Z($.styleOptionTerm($.optionTerm(h)),$.styleOptionDescription($.optionDescription(h)))});X=X.concat(this.formatItemList("Global Options:",R,$))}return this.groupItems(W.commands,$.visibleCommands(W),(R)=>R.helpGroup()||"Commands:").forEach((R,h)=>{let _=R.map((D)=>{return Z($.styleSubcommandTerm($.subcommandTerm(D)),$.styleSubcommandDescription($.subcommandDescription(D)))});X=X.concat(this.formatItemList(h,_,$))}),X.join(`
3
- `)}displayWidth(W){return K9(W).length}styleTitle(W){return W}styleUsage(W){return W.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($==="[command]")return this.styleSubcommandText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleCommandText($)}).join(" ")}styleCommandDescription(W){return this.styleDescriptionText(W)}styleOptionDescription(W){return this.styleDescriptionText(W)}styleSubcommandDescription(W){return this.styleDescriptionText(W)}styleArgumentDescription(W){return this.styleDescriptionText(W)}styleDescriptionText(W){return W}styleOptionTerm(W){return this.styleOptionText(W)}styleSubcommandTerm(W){return W.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleSubcommandText($)}).join(" ")}styleArgumentTerm(W){return this.styleArgumentText(W)}styleOptionText(W){return W}styleArgumentText(W){return W}styleSubcommandText(W){return W}styleCommandText(W){return W}padWidth(W,$){return Math.max($.longestOptionTermLength(W,$),$.longestGlobalOptionTermLength(W,$),$.longestSubcommandTermLength(W,$),$.longestArgumentTermLength(W,$))}preformatted(W){return/\n[^\S\r\n]/.test(W)}formatItem(W,$,k,J){let X=" ".repeat(2);if(!k)return X+W;let G=W.padEnd($+W.length-J.displayWidth(W)),z=2,w=(this.helpWidth??80)-$-z-2,R;if(w<this.minWidthToWrap||J.preformatted(k))R=k;else R=J.boxWrap(k,w).replace(/\n/g,`
4
- `+" ".repeat($+z));return X+G+" ".repeat(z)+R.replace(/\n/g,`
5
- ${X}`)}boxWrap(W,$){if($<this.minWidthToWrap)return W;let k=W.split(/\r\n|\n/),J=/[\s]*[^\s]+/g,Z=[];return k.forEach((X)=>{let G=X.match(J);if(G===null){Z.push("");return}let z=[G.shift()],V=this.displayWidth(z[0]);G.forEach((w)=>{let R=this.displayWidth(w);if(V+R<=$){z.push(w),V+=R;return}Z.push(z.join(""));let h=w.trimStart();z=[h],V=this.displayWidth(h)}),Z.push(z.join(""))}),Z.join(`
6
- `)}}function K9(W){let $=/\x1b\[\d*(;\d*)*m/g;return W.replace($,"")}G$.Help=L9;G$.stripColor=K9});var g4=X0((V$)=>{var{InvalidArgumentError:K$}=k8();class V9{constructor(W,$){this.flags=W,this.description=$||"",this.required=W.includes("<"),this.optional=W.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(W),this.mandatory=!1;let k=U$(W);if(this.short=k.shortFlag,this.long=k.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,this.helpGroupHeading=void 0}default(W,$){return this.defaultValue=W,this.defaultValueDescription=$,this}preset(W){return this.presetArg=W,this}conflicts(W){return this.conflictsWith=this.conflictsWith.concat(W),this}implies(W){let $=W;if(typeof W==="string")$={[W]:!0};return this.implied=Object.assign(this.implied||{},$),this}env(W){return this.envVar=W,this}argParser(W){return this.parseArg=W,this}makeOptionMandatory(W=!0){return this.mandatory=!!W,this}hideHelp(W=!0){return this.hidden=!!W,this}_collectValue(W,$){if($===this.defaultValue||!Array.isArray($))return[W];return $.push(W),$}choices(W){return this.argChoices=W.slice(),this.parseArg=($,k)=>{if(!this.argChoices.includes($))throw new K$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue($,k);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return U9(this.name().replace(/^no-/,""));return U9(this.name())}helpGroup(W){return this.helpGroupHeading=W,this}is(W){return this.short===W||this.long===W}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class R9{constructor(W){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,W.forEach(($)=>{if($.negate)this.negativeOptions.set($.attributeName(),$);else this.positiveOptions.set($.attributeName(),$)}),this.negativeOptions.forEach(($,k)=>{if(this.positiveOptions.has(k))this.dualOptions.add(k)})}valueFromOption(W,$){let k=$.attributeName();if(!this.dualOptions.has(k))return!0;let J=this.negativeOptions.get(k).presetArg,Z=J!==void 0?J:!1;return $.negate===(Z===W)}}function U9(W){return W.split("-").reduce(($,k)=>{return $+k[0].toUpperCase()+k.slice(1)})}function U$(W){let $,k,J=/^-[^-]$/,Z=/^--[^-]/,X=W.split(/[ |,]+/).concat("guard");if(J.test(X[0]))$=X.shift();if(Z.test(X[0]))k=X.shift();if(!$&&J.test(X[0]))$=X.shift();if(!$&&Z.test(X[0]))$=k,k=X.shift();if(X[0].startsWith("-")){let G=X[0],z=`option creation failed due to '${G}' in option flags '${W}'`;if(/^-[^-][^-]/.test(G))throw Error(`${z}
2
+ import{createRequire as B$}from"node:module";var f$=Object.create;var{getPrototypeOf:j$,defineProperty:f9,getOwnPropertyNames:A$}=Object;var N$=Object.prototype.hasOwnProperty;function C$(W){return this[W]}var q$,O$,x$=(W,$,Z)=>{var J=W!=null&&typeof W==="object";if(J){var X=$?q$??=new WeakMap:O$??=new WeakMap,Y=X.get(W);if(Y)return Y}Z=W!=null?f$(j$(W)):{};let M=$||!W||!W.__esModule?f9(Z,"default",{value:W,enumerable:!0}):Z;for(let G of A$(W))if(!N$.call(M,G))f9(M,G,{get:C$.bind(W,G),enumerable:!0});if(J)X.set(W,M);return M};var L8=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports);var LW=B$(import.meta.url);var KW=L8((b$)=>{class o4 extends Error{constructor(W,$,Z){super(Z);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=W,this.nestedError=void 0}}class j9 extends o4{constructor(W){super(1,"commander.invalidArgument",W);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}b$.CommanderError=o4;b$.InvalidArgumentError=j9});var oW=L8((c$)=>{var{InvalidArgumentError:g$}=KW();class A9{constructor(W,$){switch(this.description=$||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,W[0]){case"<":this.required=!0,this._name=W.slice(1,-1);break;case"[":this.required=!1,this._name=W.slice(1,-1);break;default:this.required=!0,this._name=W;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(W,$){if($===this.defaultValue||!Array.isArray($))return[W];return $.push(W),$}default(W,$){return this.defaultValue=W,this.defaultValueDescription=$,this}argParser(W){return this.parseArg=W,this}choices(W){return this.argChoices=W.slice(),this.parseArg=($,Z)=>{if(!this.argChoices.includes($))throw new g$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue($,Z);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function m$(W){let $=W.name()+(W.variadic===!0?"...":"");return W.required?"<"+$+">":"["+$+"]"}c$.Argument=A9;c$.humanReadableArgName=m$});var e4=L8((i$)=>{var{humanReadableArgName:p$}=oW();class N9{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(W){this.helpWidth=this.helpWidth??W.helpWidth??80}visibleCommands(W){let $=W.commands.filter((J)=>!J._hidden),Z=W._getHelpCommand();if(Z&&!Z._hidden)$.push(Z);if(this.sortSubcommands)$.sort((J,X)=>{return J.name().localeCompare(X.name())});return $}compareOptions(W,$){let Z=(J)=>{return J.short?J.short.replace(/^-/,""):J.long.replace(/^--/,"")};return Z(W).localeCompare(Z($))}visibleOptions(W){let $=W.options.filter((J)=>!J.hidden),Z=W._getHelpOption();if(Z&&!Z.hidden){let J=Z.short&&W._findOption(Z.short),X=Z.long&&W._findOption(Z.long);if(!J&&!X)$.push(Z);else if(Z.long&&!X)$.push(W.createOption(Z.long,Z.description));else if(Z.short&&!J)$.push(W.createOption(Z.short,Z.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(W){if(!this.showGlobalOptions)return[];let $=[];for(let Z=W.parent;Z;Z=Z.parent){let J=Z.options.filter((X)=>!X.hidden);$.push(...J)}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleArguments(W){if(W._argsDescription)W.registeredArguments.forEach(($)=>{$.description=$.description||W._argsDescription[$.name()]||""});if(W.registeredArguments.find(($)=>$.description))return W.registeredArguments;return[]}subcommandTerm(W){let $=W.registeredArguments.map((Z)=>p$(Z)).join(" ");return W._name+(W._aliases[0]?"|"+W._aliases[0]:"")+(W.options.length?" [options]":"")+($?" "+$:"")}optionTerm(W){return W.flags}argumentTerm(W){return W.name()}longestSubcommandTermLength(W,$){return $.visibleCommands(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleSubcommandTerm($.subcommandTerm(J))))},0)}longestOptionTermLength(W,$){return $.visibleOptions(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleOptionTerm($.optionTerm(J))))},0)}longestGlobalOptionTermLength(W,$){return $.visibleGlobalOptions(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleOptionTerm($.optionTerm(J))))},0)}longestArgumentTermLength(W,$){return $.visibleArguments(W).reduce((Z,J)=>{return Math.max(Z,this.displayWidth($.styleArgumentTerm($.argumentTerm(J))))},0)}commandUsage(W){let $=W._name;if(W._aliases[0])$=$+"|"+W._aliases[0];let Z="";for(let J=W.parent;J;J=J.parent)Z=J.name()+" "+Z;return Z+$+" "+W.usage()}commandDescription(W){return W.description()}subcommandDescription(W){return W.summary()||W.description()}optionDescription(W){let $=[];if(W.argChoices)$.push(`choices: ${W.argChoices.map((Z)=>JSON.stringify(Z)).join(", ")}`);if(W.defaultValue!==void 0){if(W.required||W.optional||W.isBoolean()&&typeof W.defaultValue==="boolean")$.push(`default: ${W.defaultValueDescription||JSON.stringify(W.defaultValue)}`)}if(W.presetArg!==void 0&&W.optional)$.push(`preset: ${JSON.stringify(W.presetArg)}`);if(W.envVar!==void 0)$.push(`env: ${W.envVar}`);if($.length>0){let Z=`(${$.join(", ")})`;if(W.description)return`${W.description} ${Z}`;return Z}return W.description}argumentDescription(W){let $=[];if(W.argChoices)$.push(`choices: ${W.argChoices.map((Z)=>JSON.stringify(Z)).join(", ")}`);if(W.defaultValue!==void 0)$.push(`default: ${W.defaultValueDescription||JSON.stringify(W.defaultValue)}`);if($.length>0){let Z=`(${$.join(", ")})`;if(W.description)return`${W.description} ${Z}`;return Z}return W.description}formatItemList(W,$,Z){if($.length===0)return[];return[Z.styleTitle(W),...$,""]}groupItems(W,$,Z){let J=new Map;return W.forEach((X)=>{let Y=Z(X);if(!J.has(Y))J.set(Y,[])}),$.forEach((X)=>{let Y=Z(X);if(!J.has(Y))J.set(Y,[]);J.get(Y).push(X)}),J}formatHelp(W,$){let Z=$.padWidth(W,$),J=$.helpWidth??80;function X(P,w){return $.formatItem(P,Z,w,$)}let Y=[`${$.styleTitle("Usage:")} ${$.styleUsage($.commandUsage(W))}`,""],M=$.commandDescription(W);if(M.length>0)Y=Y.concat([$.boxWrap($.styleCommandDescription(M),J),""]);let G=$.visibleArguments(W).map((P)=>{return X($.styleArgumentTerm($.argumentTerm(P)),$.styleArgumentDescription($.argumentDescription(P)))});if(Y=Y.concat(this.formatItemList("Arguments:",G,$)),this.groupItems(W.options,$.visibleOptions(W),(P)=>P.helpGroupHeading??"Options:").forEach((P,w)=>{let D=P.map((S)=>{return X($.styleOptionTerm($.optionTerm(S)),$.styleOptionDescription($.optionDescription(S)))});Y=Y.concat(this.formatItemList(w,D,$))}),$.showGlobalOptions){let P=$.visibleGlobalOptions(W).map((w)=>{return X($.styleOptionTerm($.optionTerm(w)),$.styleOptionDescription($.optionDescription(w)))});Y=Y.concat(this.formatItemList("Global Options:",P,$))}return this.groupItems(W.commands,$.visibleCommands(W),(P)=>P.helpGroup()||"Commands:").forEach((P,w)=>{let D=P.map((S)=>{return X($.styleSubcommandTerm($.subcommandTerm(S)),$.styleSubcommandDescription($.subcommandDescription(S)))});Y=Y.concat(this.formatItemList(w,D,$))}),Y.join(`
3
+ `)}displayWidth(W){return C9(W).length}styleTitle(W){return W}styleUsage(W){return W.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($==="[command]")return this.styleSubcommandText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleCommandText($)}).join(" ")}styleCommandDescription(W){return this.styleDescriptionText(W)}styleOptionDescription(W){return this.styleDescriptionText(W)}styleSubcommandDescription(W){return this.styleDescriptionText(W)}styleArgumentDescription(W){return this.styleDescriptionText(W)}styleDescriptionText(W){return W}styleOptionTerm(W){return this.styleOptionText(W)}styleSubcommandTerm(W){return W.split(" ").map(($)=>{if($==="[options]")return this.styleOptionText($);if($[0]==="["||$[0]==="<")return this.styleArgumentText($);return this.styleSubcommandText($)}).join(" ")}styleArgumentTerm(W){return this.styleArgumentText(W)}styleOptionText(W){return W}styleArgumentText(W){return W}styleSubcommandText(W){return W}styleCommandText(W){return W}padWidth(W,$){return Math.max($.longestOptionTermLength(W,$),$.longestGlobalOptionTermLength(W,$),$.longestSubcommandTermLength(W,$),$.longestArgumentTermLength(W,$))}preformatted(W){return/\n[^\S\r\n]/.test(W)}formatItem(W,$,Z,J){let Y=" ".repeat(2);if(!Z)return Y+W;let M=W.padEnd($+W.length-J.displayWidth(W)),G=2,R=(this.helpWidth??80)-$-G-2,P;if(R<this.minWidthToWrap||J.preformatted(Z))P=Z;else P=J.boxWrap(Z,R).replace(/\n/g,`
4
+ `+" ".repeat($+G));return Y+M+" ".repeat(G)+P.replace(/\n/g,`
5
+ ${Y}`)}boxWrap(W,$){if($<this.minWidthToWrap)return W;let Z=W.split(/\r\n|\n/),J=/[\s]*[^\s]+/g,X=[];return Z.forEach((Y)=>{let M=Y.match(J);if(M===null){X.push("");return}let G=[M.shift()],V=this.displayWidth(G[0]);M.forEach((R)=>{let P=this.displayWidth(R);if(V+P<=$){G.push(R),V+=P;return}X.push(G.join(""));let w=R.trimStart();G=[w],V=this.displayWidth(w)}),X.push(G.join(""))}),X.join(`
6
+ `)}}function C9(W){let $=/\x1b\[\d*(;\d*)*m/g;return W.replace($,"")}i$.Help=N9;i$.stripColor=C9});var W6=L8((n$)=>{var{InvalidArgumentError:d$}=KW();class O9{constructor(W,$){this.flags=W,this.description=$||"",this.required=W.includes("<"),this.optional=W.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(W),this.mandatory=!1;let Z=s$(W);if(this.short=Z.shortFlag,this.long=Z.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,this.helpGroupHeading=void 0}default(W,$){return this.defaultValue=W,this.defaultValueDescription=$,this}preset(W){return this.presetArg=W,this}conflicts(W){return this.conflictsWith=this.conflictsWith.concat(W),this}implies(W){let $=W;if(typeof W==="string")$={[W]:!0};return this.implied=Object.assign(this.implied||{},$),this}env(W){return this.envVar=W,this}argParser(W){return this.parseArg=W,this}makeOptionMandatory(W=!0){return this.mandatory=!!W,this}hideHelp(W=!0){return this.hidden=!!W,this}_collectValue(W,$){if($===this.defaultValue||!Array.isArray($))return[W];return $.push(W),$}choices(W){return this.argChoices=W.slice(),this.parseArg=($,Z)=>{if(!this.argChoices.includes($))throw new d$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue($,Z);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return q9(this.name().replace(/^no-/,""));return q9(this.name())}helpGroup(W){return this.helpGroupHeading=W,this}is(W){return this.short===W||this.long===W}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class x9{constructor(W){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,W.forEach(($)=>{if($.negate)this.negativeOptions.set($.attributeName(),$);else this.positiveOptions.set($.attributeName(),$)}),this.negativeOptions.forEach(($,Z)=>{if(this.positiveOptions.has(Z))this.dualOptions.add(Z)})}valueFromOption(W,$){let Z=$.attributeName();if(!this.dualOptions.has(Z))return!0;let J=this.negativeOptions.get(Z).presetArg,X=J!==void 0?J:!1;return $.negate===(X===W)}}function q9(W){return W.split("-").reduce(($,Z)=>{return $+Z[0].toUpperCase()+Z.slice(1)})}function s$(W){let $,Z,J=/^-[^-]$/,X=/^--[^-]/,Y=W.split(/[ |,]+/).concat("guard");if(J.test(Y[0]))$=Y.shift();if(X.test(Y[0]))Z=Y.shift();if(!$&&J.test(Y[0]))$=Y.shift();if(!$&&X.test(Y[0]))$=Z,Z=Y.shift();if(Y[0].startsWith("-")){let M=Y[0],G=`option creation failed due to '${M}' in option flags '${W}'`;if(/^-[^-][^-]/.test(M))throw Error(`${G}
7
7
  - a short flag is a single dash and a single character
8
8
  - either use a single dash and a single character (for a short flag)
9
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(J.test(G))throw Error(`${z}
10
- - too many short flags`);if(Z.test(G))throw Error(`${z}
11
- - too many long flags`);throw Error(`${z}
12
- - unrecognised flag format`)}if($===void 0&&k===void 0)throw Error(`option creation failed due to no flags found in '${W}'.`);return{shortFlag:$,longFlag:k}}V$.Option=V9;V$.DualOptions=R9});var F9=X0((h$)=>{function w$(W,$){if(Math.abs(W.length-$.length)>3)return Math.max(W.length,$.length);let k=[];for(let J=0;J<=W.length;J++)k[J]=[J];for(let J=0;J<=$.length;J++)k[0][J]=J;for(let J=1;J<=$.length;J++)for(let Z=1;Z<=W.length;Z++){let X=1;if(W[Z-1]===$[J-1])X=0;else X=1;if(k[Z][J]=Math.min(k[Z-1][J]+1,k[Z][J-1]+1,k[Z-1][J-1]+X),Z>1&&J>1&&W[Z-1]===$[J-2]&&W[Z-2]===$[J-1])k[Z][J]=Math.min(k[Z][J],k[Z-2][J-2]+1)}return k[W.length][$.length]}function _$(W,$){if(!$||$.length===0)return"";$=Array.from(new Set($));let k=W.startsWith("--");if(k)W=W.slice(2),$=$.map((G)=>G.slice(2));let J=[],Z=3,X=0.4;if($.forEach((G)=>{if(G.length<=1)return;let z=w$(W,G),V=Math.max(W.length,G.length);if((V-z)/V>X){if(z<Z)Z=z,J=[G];else if(z===Z)J.push(G)}}),J.sort((G,z)=>G.localeCompare(z)),k)J=J.map((G)=>`--${G}`);if(J.length>1)return`
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(J.test(M))throw Error(`${G}
10
+ - too many short flags`);if(X.test(M))throw Error(`${G}
11
+ - too many long flags`);throw Error(`${G}
12
+ - unrecognised flag format`)}if($===void 0&&Z===void 0)throw Error(`option creation failed due to no flags found in '${W}'.`);return{shortFlag:$,longFlag:Z}}n$.Option=O9;n$.DualOptions=x9});var B9=L8(($2)=>{function e$(W,$){if(Math.abs(W.length-$.length)>3)return Math.max(W.length,$.length);let Z=[];for(let J=0;J<=W.length;J++)Z[J]=[J];for(let J=0;J<=$.length;J++)Z[0][J]=J;for(let J=1;J<=$.length;J++)for(let X=1;X<=W.length;X++){let Y=1;if(W[X-1]===$[J-1])Y=0;else Y=1;if(Z[X][J]=Math.min(Z[X-1][J]+1,Z[X][J-1]+1,Z[X-1][J-1]+Y),X>1&&J>1&&W[X-1]===$[J-2]&&W[X-2]===$[J-1])Z[X][J]=Math.min(Z[X][J],Z[X-2][J-2]+1)}return Z[W.length][$.length]}function W2(W,$){if(!$||$.length===0)return"";$=Array.from(new Set($));let Z=W.startsWith("--");if(Z)W=W.slice(2),$=$.map((M)=>M.slice(2));let J=[],X=3,Y=0.4;if($.forEach((M)=>{if(M.length<=1)return;let G=e$(W,M),V=Math.max(W.length,M.length);if((V-G)/V>Y){if(G<X)X=G,J=[M];else if(G===X)J.push(M)}}),J.sort((M,G)=>M.localeCompare(G)),Z)J=J.map((M)=>`--${M}`);if(J.length>1)return`
13
13
  (Did you mean one of ${J.join(", ")}?)`;if(J.length===1)return`
14
- (Did you mean ${J[0]}?)`;return""}h$.suggestSimilar=_$});var P9=X0((N$)=>{var D$=$8("node:events").EventEmitter,m4=$8("node:child_process"),A1=$8("node:path"),g8=$8("node:fs"),XW=$8("node:process"),{Argument:f$,humanReadableArgName:T$}=y8(),{CommanderError:c4}=k8(),{Help:E$,stripColor:v$}=y4(),{Option:w9,DualOptions:S$}=g4(),{suggestSimilar:_9}=F9();class l4 extends D${constructor(W){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=W||"",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._savedState=null,this._outputConfiguration={writeOut:($)=>XW.stdout.write($),writeErr:($)=>XW.stderr.write($),outputError:($,k)=>k($),getOutHelpWidth:()=>XW.stdout.isTTY?XW.stdout.columns:void 0,getErrHelpWidth:()=>XW.stderr.isTTY?XW.stderr.columns:void 0,getOutHasColors:()=>u4()??(XW.stdout.isTTY&&XW.stdout.hasColors?.()),getErrHasColors:()=>u4()??(XW.stderr.isTTY&&XW.stderr.hasColors?.()),stripColor:($)=>v$($)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(W){return this._outputConfiguration=W._outputConfiguration,this._helpOption=W._helpOption,this._helpCommand=W._helpCommand,this._helpConfiguration=W._helpConfiguration,this._exitCallback=W._exitCallback,this._storeOptionsAsProperties=W._storeOptionsAsProperties,this._combineFlagAndOptionalValue=W._combineFlagAndOptionalValue,this._allowExcessArguments=W._allowExcessArguments,this._enablePositionalOptions=W._enablePositionalOptions,this._showHelpAfterError=W._showHelpAfterError,this._showSuggestionAfterError=W._showSuggestionAfterError,this}_getCommandAndAncestors(){let W=[];for(let $=this;$;$=$.parent)W.push($);return W}command(W,$,k){let J=$,Z=k;if(typeof J==="object"&&J!==null)Z=J,J=null;Z=Z||{};let[,X,G]=W.match(/([^ ]+) *(.*)/),z=this.createCommand(X);if(J)z.description(J),z._executableHandler=!0;if(Z.isDefault)this._defaultCommandName=z._name;if(z._hidden=!!(Z.noHelp||Z.hidden),z._executableFile=Z.executableFile||null,G)z.arguments(G);if(this._registerCommand(z),z.parent=this,z.copyInheritedSettings(this),J)return this;return z}createCommand(W){return new l4(W)}createHelp(){return Object.assign(new E$,this.configureHelp())}configureHelp(W){if(W===void 0)return this._helpConfiguration;return this._helpConfiguration=W,this}configureOutput(W){if(W===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...W},this}showHelpAfterError(W=!0){if(typeof W!=="string")W=!!W;return this._showHelpAfterError=W,this}showSuggestionAfterError(W=!0){return this._showSuggestionAfterError=!!W,this}addCommand(W,$){if(!W._name)throw Error(`Command passed to .addCommand() must have a name
15
- - specify the name in Command constructor or using .name()`);if($=$||{},$.isDefault)this._defaultCommandName=W._name;if($.noHelp||$.hidden)W._hidden=!0;return this._registerCommand(W),W.parent=this,W._checkForBrokenPassThrough(),this}createArgument(W,$){return new f$(W,$)}argument(W,$,k,J){let Z=this.createArgument(W,$);if(typeof k==="function")Z.default(J).argParser(k);else Z.default(k);return this.addArgument(Z),this}arguments(W){return W.trim().split(/ +/).forEach(($)=>{this.argument($)}),this}addArgument(W){let $=this.registeredArguments.slice(-1)[0];if($?.variadic)throw Error(`only the last argument can be variadic '${$.name()}'`);if(W.required&&W.defaultValue!==void 0&&W.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${W.name()}'`);return this.registeredArguments.push(W),this}helpCommand(W,$){if(typeof W==="boolean"){if(this._addImplicitHelpCommand=W,W&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let k=W??"help [command]",[,J,Z]=k.match(/([^ ]+) *(.*)/),X=$??"display help for command",G=this.createCommand(J);if(G.helpOption(!1),Z)G.arguments(Z);if(X)G.description(X);if(this._addImplicitHelpCommand=!0,this._helpCommand=G,W||$)this._initCommandGroup(G);return this}addHelpCommand(W,$){if(typeof W!=="object")return this.helpCommand(W,$),this;return this._addImplicitHelpCommand=!0,this._helpCommand=W,this._initCommandGroup(W),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(W,$){let k=["preSubcommand","preAction","postAction"];if(!k.includes(W))throw Error(`Unexpected value for event passed to hook : '${W}'.
16
- Expecting one of '${k.join("', '")}'`);if(this._lifeCycleHooks[W])this._lifeCycleHooks[W].push($);else this._lifeCycleHooks[W]=[$];return this}exitOverride(W){if(W)this._exitCallback=W;else this._exitCallback=($)=>{if($.code!=="commander.executeSubCommandAsync")throw $};return this}_exit(W,$,k){if(this._exitCallback)this._exitCallback(new c4(W,$,k));XW.exit(W)}action(W){let $=(k)=>{let J=this.registeredArguments.length,Z=k.slice(0,J);if(this._storeOptionsAsProperties)Z[J]=this;else Z[J]=this.opts();return Z.push(this),W.apply(this,Z)};return this._actionHandler=$,this}createOption(W,$){return new w9(W,$)}_callParseArg(W,$,k,J){try{return W.parseArg($,k)}catch(Z){if(Z.code==="commander.invalidArgument"){let X=`${J} ${Z.message}`;this.error(X,{exitCode:Z.exitCode,code:Z.code})}throw Z}}_registerOption(W){let $=W.short&&this._findOption(W.short)||W.long&&this._findOption(W.long);if($){let k=W.long&&this._findOption(W.long)?W.long:W.short;throw Error(`Cannot add option '${W.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${k}'
17
- - already used by option '${$.flags}'`)}this._initOptionGroup(W),this.options.push(W)}_registerCommand(W){let $=(J)=>{return[J.name()].concat(J.aliases())},k=$(W).find((J)=>this._findCommand(J));if(k){let J=$(this._findCommand(k)).join("|"),Z=$(W).join("|");throw Error(`cannot add command '${Z}' as already have command '${J}'`)}this._initCommandGroup(W),this.commands.push(W)}addOption(W){this._registerOption(W);let $=W.name(),k=W.attributeName();if(W.negate){let Z=W.long.replace(/^--no-/,"--");if(!this._findOption(Z))this.setOptionValueWithSource(k,W.defaultValue===void 0?!0:W.defaultValue,"default")}else if(W.defaultValue!==void 0)this.setOptionValueWithSource(k,W.defaultValue,"default");let J=(Z,X,G)=>{if(Z==null&&W.presetArg!==void 0)Z=W.presetArg;let z=this.getOptionValue(k);if(Z!==null&&W.parseArg)Z=this._callParseArg(W,Z,z,X);else if(Z!==null&&W.variadic)Z=W._collectValue(Z,z);if(Z==null)if(W.negate)Z=!1;else if(W.isBoolean()||W.optional)Z=!0;else Z="";this.setOptionValueWithSource(k,Z,G)};if(this.on("option:"+$,(Z)=>{let X=`error: option '${W.flags}' argument '${Z}' is invalid.`;J(Z,X,"cli")}),W.envVar)this.on("optionEnv:"+$,(Z)=>{let X=`error: option '${W.flags}' value '${Z}' from env '${W.envVar}' is invalid.`;J(Z,X,"env")});return this}_optionEx(W,$,k,J,Z){if(typeof $==="object"&&$ instanceof w9)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let X=this.createOption($,k);if(X.makeOptionMandatory(!!W.mandatory),typeof J==="function")X.default(Z).argParser(J);else if(J instanceof RegExp){let G=J;J=(z,V)=>{let w=G.exec(z);return w?w[0]:V},X.default(Z).argParser(J)}else X.default(J);return this.addOption(X)}option(W,$,k,J){return this._optionEx({},W,$,k,J)}requiredOption(W,$,k,J){return this._optionEx({mandatory:!0},W,$,k,J)}combineFlagAndOptionalValue(W=!0){return this._combineFlagAndOptionalValue=!!W,this}allowUnknownOption(W=!0){return this._allowUnknownOption=!!W,this}allowExcessArguments(W=!0){return this._allowExcessArguments=!!W,this}enablePositionalOptions(W=!0){return this._enablePositionalOptions=!!W,this}passThroughOptions(W=!0){return this._passThroughOptions=!!W,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(W=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!W,this}getOptionValue(W){if(this._storeOptionsAsProperties)return this[W];return this._optionValues[W]}setOptionValue(W,$){return this.setOptionValueWithSource(W,$,void 0)}setOptionValueWithSource(W,$,k){if(this._storeOptionsAsProperties)this[W]=$;else this._optionValues[W]=$;return this._optionValueSources[W]=k,this}getOptionValueSource(W){return this._optionValueSources[W]}getOptionValueSourceWithGlobals(W){let $;return this._getCommandAndAncestors().forEach((k)=>{if(k.getOptionValueSource(W)!==void 0)$=k.getOptionValueSource(W)}),$}_prepareUserArgs(W,$){if(W!==void 0&&!Array.isArray(W))throw Error("first parameter to parse must be array or undefined");if($=$||{},W===void 0&&$.from===void 0){if(XW.versions?.electron)$.from="electron";let J=XW.execArgv??[];if(J.includes("-e")||J.includes("--eval")||J.includes("-p")||J.includes("--print"))$.from="eval"}if(W===void 0)W=XW.argv;this.rawArgs=W.slice();let k;switch($.from){case void 0:case"node":this._scriptPath=W[1],k=W.slice(2);break;case"electron":if(XW.defaultApp)this._scriptPath=W[1],k=W.slice(2);else k=W.slice(1);break;case"user":k=W.slice(0);break;case"eval":k=W.slice(1);break;default:throw Error(`unexpected parse option { from: '${$.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",k}parse(W,$){this._prepareForParse();let k=this._prepareUserArgs(W,$);return this._parseCommand([],k),this}async parseAsync(W,$){this._prepareForParse();let k=this._prepareUserArgs(W,$);return await this._parseCommand([],k),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
18
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(W,$,k){if(g8.existsSync(W))return;let J=$?`searched for local subcommand relative to directory '${$}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",Z=`'${W}' does not exist
19
- - if '${k}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
14
+ (Did you mean ${J[0]}?)`;return""}$2.suggestSimilar=W2});var g9=L8((M2)=>{var J2=LW("node:events").EventEmitter,$6=LW("node:child_process"),x0=LW("node:path"),eW=LW("node:fs"),H1=LW("node:process"),{Argument:X2,humanReadableArgName:Y2}=oW(),{CommanderError:Z6}=KW(),{Help:H2,stripColor:k2}=e4(),{Option:b9,DualOptions:G2}=W6(),{suggestSimilar:I9}=B9();class X6 extends J2{constructor(W){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=W||"",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._savedState=null,this._outputConfiguration={writeOut:($)=>H1.stdout.write($),writeErr:($)=>H1.stderr.write($),outputError:($,Z)=>Z($),getOutHelpWidth:()=>H1.stdout.isTTY?H1.stdout.columns:void 0,getErrHelpWidth:()=>H1.stderr.isTTY?H1.stderr.columns:void 0,getOutHasColors:()=>J6()??(H1.stdout.isTTY&&H1.stdout.hasColors?.()),getErrHasColors:()=>J6()??(H1.stderr.isTTY&&H1.stderr.hasColors?.()),stripColor:($)=>k2($)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(W){return this._outputConfiguration=W._outputConfiguration,this._helpOption=W._helpOption,this._helpCommand=W._helpCommand,this._helpConfiguration=W._helpConfiguration,this._exitCallback=W._exitCallback,this._storeOptionsAsProperties=W._storeOptionsAsProperties,this._combineFlagAndOptionalValue=W._combineFlagAndOptionalValue,this._allowExcessArguments=W._allowExcessArguments,this._enablePositionalOptions=W._enablePositionalOptions,this._showHelpAfterError=W._showHelpAfterError,this._showSuggestionAfterError=W._showSuggestionAfterError,this}_getCommandAndAncestors(){let W=[];for(let $=this;$;$=$.parent)W.push($);return W}command(W,$,Z){let J=$,X=Z;if(typeof J==="object"&&J!==null)X=J,J=null;X=X||{};let[,Y,M]=W.match(/([^ ]+) *(.*)/),G=this.createCommand(Y);if(J)G.description(J),G._executableHandler=!0;if(X.isDefault)this._defaultCommandName=G._name;if(G._hidden=!!(X.noHelp||X.hidden),G._executableFile=X.executableFile||null,M)G.arguments(M);if(this._registerCommand(G),G.parent=this,G.copyInheritedSettings(this),J)return this;return G}createCommand(W){return new X6(W)}createHelp(){return Object.assign(new H2,this.configureHelp())}configureHelp(W){if(W===void 0)return this._helpConfiguration;return this._helpConfiguration=W,this}configureOutput(W){if(W===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...W},this}showHelpAfterError(W=!0){if(typeof W!=="string")W=!!W;return this._showHelpAfterError=W,this}showSuggestionAfterError(W=!0){return this._showSuggestionAfterError=!!W,this}addCommand(W,$){if(!W._name)throw Error(`Command passed to .addCommand() must have a name
15
+ - specify the name in Command constructor or using .name()`);if($=$||{},$.isDefault)this._defaultCommandName=W._name;if($.noHelp||$.hidden)W._hidden=!0;return this._registerCommand(W),W.parent=this,W._checkForBrokenPassThrough(),this}createArgument(W,$){return new X2(W,$)}argument(W,$,Z,J){let X=this.createArgument(W,$);if(typeof Z==="function")X.default(J).argParser(Z);else X.default(Z);return this.addArgument(X),this}arguments(W){return W.trim().split(/ +/).forEach(($)=>{this.argument($)}),this}addArgument(W){let $=this.registeredArguments.slice(-1)[0];if($?.variadic)throw Error(`only the last argument can be variadic '${$.name()}'`);if(W.required&&W.defaultValue!==void 0&&W.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${W.name()}'`);return this.registeredArguments.push(W),this}helpCommand(W,$){if(typeof W==="boolean"){if(this._addImplicitHelpCommand=W,W&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let Z=W??"help [command]",[,J,X]=Z.match(/([^ ]+) *(.*)/),Y=$??"display help for command",M=this.createCommand(J);if(M.helpOption(!1),X)M.arguments(X);if(Y)M.description(Y);if(this._addImplicitHelpCommand=!0,this._helpCommand=M,W||$)this._initCommandGroup(M);return this}addHelpCommand(W,$){if(typeof W!=="object")return this.helpCommand(W,$),this;return this._addImplicitHelpCommand=!0,this._helpCommand=W,this._initCommandGroup(W),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(W,$){let Z=["preSubcommand","preAction","postAction"];if(!Z.includes(W))throw Error(`Unexpected value for event passed to hook : '${W}'.
16
+ Expecting one of '${Z.join("', '")}'`);if(this._lifeCycleHooks[W])this._lifeCycleHooks[W].push($);else this._lifeCycleHooks[W]=[$];return this}exitOverride(W){if(W)this._exitCallback=W;else this._exitCallback=($)=>{if($.code!=="commander.executeSubCommandAsync")throw $};return this}_exit(W,$,Z){if(this._exitCallback)this._exitCallback(new Z6(W,$,Z));H1.exit(W)}action(W){let $=(Z)=>{let J=this.registeredArguments.length,X=Z.slice(0,J);if(this._storeOptionsAsProperties)X[J]=this;else X[J]=this.opts();return X.push(this),W.apply(this,X)};return this._actionHandler=$,this}createOption(W,$){return new b9(W,$)}_callParseArg(W,$,Z,J){try{return W.parseArg($,Z)}catch(X){if(X.code==="commander.invalidArgument"){let Y=`${J} ${X.message}`;this.error(Y,{exitCode:X.exitCode,code:X.code})}throw X}}_registerOption(W){let $=W.short&&this._findOption(W.short)||W.long&&this._findOption(W.long);if($){let Z=W.long&&this._findOption(W.long)?W.long:W.short;throw Error(`Cannot add option '${W.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${Z}'
17
+ - already used by option '${$.flags}'`)}this._initOptionGroup(W),this.options.push(W)}_registerCommand(W){let $=(J)=>{return[J.name()].concat(J.aliases())},Z=$(W).find((J)=>this._findCommand(J));if(Z){let J=$(this._findCommand(Z)).join("|"),X=$(W).join("|");throw Error(`cannot add command '${X}' as already have command '${J}'`)}this._initCommandGroup(W),this.commands.push(W)}addOption(W){this._registerOption(W);let $=W.name(),Z=W.attributeName();if(W.negate){let X=W.long.replace(/^--no-/,"--");if(!this._findOption(X))this.setOptionValueWithSource(Z,W.defaultValue===void 0?!0:W.defaultValue,"default")}else if(W.defaultValue!==void 0)this.setOptionValueWithSource(Z,W.defaultValue,"default");let J=(X,Y,M)=>{if(X==null&&W.presetArg!==void 0)X=W.presetArg;let G=this.getOptionValue(Z);if(X!==null&&W.parseArg)X=this._callParseArg(W,X,G,Y);else if(X!==null&&W.variadic)X=W._collectValue(X,G);if(X==null)if(W.negate)X=!1;else if(W.isBoolean()||W.optional)X=!0;else X="";this.setOptionValueWithSource(Z,X,M)};if(this.on("option:"+$,(X)=>{let Y=`error: option '${W.flags}' argument '${X}' is invalid.`;J(X,Y,"cli")}),W.envVar)this.on("optionEnv:"+$,(X)=>{let Y=`error: option '${W.flags}' value '${X}' from env '${W.envVar}' is invalid.`;J(X,Y,"env")});return this}_optionEx(W,$,Z,J,X){if(typeof $==="object"&&$ instanceof b9)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Y=this.createOption($,Z);if(Y.makeOptionMandatory(!!W.mandatory),typeof J==="function")Y.default(X).argParser(J);else if(J instanceof RegExp){let M=J;J=(G,V)=>{let R=M.exec(G);return R?R[0]:V},Y.default(X).argParser(J)}else Y.default(J);return this.addOption(Y)}option(W,$,Z,J){return this._optionEx({},W,$,Z,J)}requiredOption(W,$,Z,J){return this._optionEx({mandatory:!0},W,$,Z,J)}combineFlagAndOptionalValue(W=!0){return this._combineFlagAndOptionalValue=!!W,this}allowUnknownOption(W=!0){return this._allowUnknownOption=!!W,this}allowExcessArguments(W=!0){return this._allowExcessArguments=!!W,this}enablePositionalOptions(W=!0){return this._enablePositionalOptions=!!W,this}passThroughOptions(W=!0){return this._passThroughOptions=!!W,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(W=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!W,this}getOptionValue(W){if(this._storeOptionsAsProperties)return this[W];return this._optionValues[W]}setOptionValue(W,$){return this.setOptionValueWithSource(W,$,void 0)}setOptionValueWithSource(W,$,Z){if(this._storeOptionsAsProperties)this[W]=$;else this._optionValues[W]=$;return this._optionValueSources[W]=Z,this}getOptionValueSource(W){return this._optionValueSources[W]}getOptionValueSourceWithGlobals(W){let $;return this._getCommandAndAncestors().forEach((Z)=>{if(Z.getOptionValueSource(W)!==void 0)$=Z.getOptionValueSource(W)}),$}_prepareUserArgs(W,$){if(W!==void 0&&!Array.isArray(W))throw Error("first parameter to parse must be array or undefined");if($=$||{},W===void 0&&$.from===void 0){if(H1.versions?.electron)$.from="electron";let J=H1.execArgv??[];if(J.includes("-e")||J.includes("--eval")||J.includes("-p")||J.includes("--print"))$.from="eval"}if(W===void 0)W=H1.argv;this.rawArgs=W.slice();let Z;switch($.from){case void 0:case"node":this._scriptPath=W[1],Z=W.slice(2);break;case"electron":if(H1.defaultApp)this._scriptPath=W[1],Z=W.slice(2);else Z=W.slice(1);break;case"user":Z=W.slice(0);break;case"eval":Z=W.slice(1);break;default:throw Error(`unexpected parse option { from: '${$.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",Z}parse(W,$){this._prepareForParse();let Z=this._prepareUserArgs(W,$);return this._parseCommand([],Z),this}async parseAsync(W,$){this._prepareForParse();let Z=this._prepareUserArgs(W,$);return await this._parseCommand([],Z),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
18
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(W,$,Z){if(eW.existsSync(W))return;let J=$?`searched for local subcommand relative to directory '${$}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",X=`'${W}' does not exist
19
+ - if '${Z}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
20
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
- - ${J}`;throw Error(Z)}_executeSubCommand(W,$){$=$.slice();let k=!1,J=[".js",".ts",".tsx",".mjs",".cjs"];function Z(w,R){let h=A1.resolve(w,R);if(g8.existsSync(h))return h;if(J.includes(A1.extname(R)))return;let _=J.find((D)=>g8.existsSync(`${h}${D}`));if(_)return`${h}${_}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let X=W._executableFile||`${this._name}-${W._name}`,G=this._executableDir||"";if(this._scriptPath){let w;try{w=g8.realpathSync(this._scriptPath)}catch{w=this._scriptPath}G=A1.resolve(A1.dirname(w),G)}if(G){let w=Z(G,X);if(!w&&!W._executableFile&&this._scriptPath){let R=A1.basename(this._scriptPath,A1.extname(this._scriptPath));if(R!==this._name)w=Z(G,`${R}-${W._name}`)}X=w||X}k=J.includes(A1.extname(X));let z;if(XW.platform!=="win32")if(k)$.unshift(X),$=h9(XW.execArgv).concat($),z=m4.spawn(XW.argv[0],$,{stdio:"inherit"});else z=m4.spawn(X,$,{stdio:"inherit"});else this._checkForMissingExecutable(X,G,W._name),$.unshift(X),$=h9(XW.execArgv).concat($),z=m4.spawn(XW.execPath,$,{stdio:"inherit"});if(!z.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((R)=>{XW.on(R,()=>{if(z.killed===!1&&z.exitCode===null)z.kill(R)})});let V=this._exitCallback;z.on("close",(w)=>{if(w=w??1,!V)XW.exit(w);else V(new c4(w,"commander.executeSubCommandAsync","(close)"))}),z.on("error",(w)=>{if(w.code==="ENOENT")this._checkForMissingExecutable(X,G,W._name);else if(w.code==="EACCES")throw Error(`'${X}' not executable`);if(!V)XW.exit(1);else{let R=new c4(1,"commander.executeSubCommandAsync","(error)");R.nestedError=w,V(R)}}),this.runningCommand=z}_dispatchSubcommand(W,$,k){let J=this._findCommand(W);if(!J)this.help({error:!0});J._prepareForParse();let Z;return Z=this._chainOrCallSubCommandHook(Z,J,"preSubcommand"),Z=this._chainOrCall(Z,()=>{if(J._executableHandler)this._executeSubCommand(J,$.concat(k));else return J._parseCommand($,k)}),Z}_dispatchHelpCommand(W){if(!W)this.help();let $=this._findCommand(W);if($&&!$._executableHandler)$.help();return this._dispatchSubcommand(W,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((W,$)=>{if(W.required&&this.args[$]==null)this.missingArgument(W.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let W=(k,J,Z)=>{let X=J;if(J!==null&&k.parseArg){let G=`error: command-argument value '${J}' is invalid for argument '${k.name()}'.`;X=this._callParseArg(k,J,Z,G)}return X};this._checkNumberOfArguments();let $=[];this.registeredArguments.forEach((k,J)=>{let Z=k.defaultValue;if(k.variadic){if(J<this.args.length){if(Z=this.args.slice(J),k.parseArg)Z=Z.reduce((X,G)=>{return W(k,G,X)},k.defaultValue)}else if(Z===void 0)Z=[]}else if(J<this.args.length){if(Z=this.args[J],k.parseArg)Z=W(k,Z,k.defaultValue)}$[J]=Z}),this.processedArgs=$}_chainOrCall(W,$){if(W?.then&&typeof W.then==="function")return W.then(()=>$());return $()}_chainOrCallHooks(W,$){let k=W,J=[];if(this._getCommandAndAncestors().reverse().filter((Z)=>Z._lifeCycleHooks[$]!==void 0).forEach((Z)=>{Z._lifeCycleHooks[$].forEach((X)=>{J.push({hookedCommand:Z,callback:X})})}),$==="postAction")J.reverse();return J.forEach((Z)=>{k=this._chainOrCall(k,()=>{return Z.callback(Z.hookedCommand,this)})}),k}_chainOrCallSubCommandHook(W,$,k){let J=W;if(this._lifeCycleHooks[k]!==void 0)this._lifeCycleHooks[k].forEach((Z)=>{J=this._chainOrCall(J,()=>{return Z(this,$)})});return J}_parseCommand(W,$){let k=this.parseOptions($);if(this._parseOptionsEnv(),this._parseOptionsImplied(),W=W.concat(k.operands),$=k.unknown,this.args=W.concat($),W&&this._findCommand(W[0]))return this._dispatchSubcommand(W[0],W.slice(1),$);if(this._getHelpCommand()&&W[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(W[1]);if(this._defaultCommandName)return this._outputHelpIfRequested($),this._dispatchSubcommand(this._defaultCommandName,W,$);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(k.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let J=()=>{if(k.unknown.length>0)this.unknownOption(k.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,W,$)});return X=this._chainOrCallHooks(X,"postAction"),X}if(this.parent?.listenerCount(Z))J(),this._processArguments(),this.parent.emit(Z,W,$);else if(W.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",W,$);if(this.listenerCount("command:*"))this.emit("command:*",W,$);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(W){if(!W)return;return this.commands.find(($)=>$._name===W||$._aliases.includes(W))}_findOption(W){return this.options.find(($)=>$.is(W))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((W)=>{W.options.forEach(($)=>{if($.mandatory&&W.getOptionValue($.attributeName())===void 0)W.missingMandatoryOptionValue($)})})}_checkForConflictingLocalOptions(){let W=this.options.filter((k)=>{let J=k.attributeName();if(this.getOptionValue(J)===void 0)return!1;return this.getOptionValueSource(J)!=="default"});W.filter((k)=>k.conflictsWith.length>0).forEach((k)=>{let J=W.find((Z)=>k.conflictsWith.includes(Z.attributeName()));if(J)this._conflictingOption(k,J)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((W)=>{W._checkForConflictingLocalOptions()})}parseOptions(W){let $=[],k=[],J=$;function Z(w){return w.length>1&&w[0]==="-"}let X=(w)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(w))return!1;return!this._getCommandAndAncestors().some((R)=>R.options.map((h)=>h.short).some((h)=>/^-\d$/.test(h)))},G=null,z=null,V=0;while(V<W.length||z){let w=z??W[V++];if(z=null,w==="--"){if(J===k)J.push(w);J.push(...W.slice(V));break}if(G&&(!Z(w)||X(w))){this.emit(`option:${G.name()}`,w);continue}if(G=null,Z(w)){let R=this._findOption(w);if(R){if(R.required){let h=W[V++];if(h===void 0)this.optionMissingArgument(R);this.emit(`option:${R.name()}`,h)}else if(R.optional){let h=null;if(V<W.length&&(!Z(W[V])||X(W[V])))h=W[V++];this.emit(`option:${R.name()}`,h)}else this.emit(`option:${R.name()}`);G=R.variadic?R:null;continue}}if(w.length>2&&w[0]==="-"&&w[1]!=="-"){let R=this._findOption(`-${w[1]}`);if(R){if(R.required||R.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${R.name()}`,w.slice(2));else this.emit(`option:${R.name()}`),z=`-${w.slice(2)}`;continue}}if(/^--[^=]+=/.test(w)){let R=w.indexOf("="),h=this._findOption(w.slice(0,R));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,w.slice(R+1));continue}}if(J===$&&Z(w)&&!(this.commands.length===0&&X(w)))J=k;if((this._enablePositionalOptions||this._passThroughOptions)&&$.length===0&&k.length===0){if(this._findCommand(w)){$.push(w),k.push(...W.slice(V));break}else if(this._getHelpCommand()&&w===this._getHelpCommand().name()){$.push(w,...W.slice(V));break}else if(this._defaultCommandName){k.push(w,...W.slice(V));break}}if(this._passThroughOptions){J.push(w,...W.slice(V));break}J.push(w)}return{operands:$,unknown:k}}opts(){if(this._storeOptionsAsProperties){let W={},$=this.options.length;for(let k=0;k<$;k++){let J=this.options[k].attributeName();W[J]=J===this._versionOptionName?this._version:this[J]}return W}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((W,$)=>Object.assign(W,$.opts()),{})}error(W,$){if(this._outputConfiguration.outputError(`${W}
21
+ - ${J}`;throw Error(X)}_executeSubCommand(W,$){$=$.slice();let Z=!1,J=[".js",".ts",".tsx",".mjs",".cjs"];function X(R,P){let w=x0.resolve(R,P);if(eW.existsSync(w))return w;if(J.includes(x0.extname(P)))return;let D=J.find((S)=>eW.existsSync(`${w}${S}`));if(D)return`${w}${D}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Y=W._executableFile||`${this._name}-${W._name}`,M=this._executableDir||"";if(this._scriptPath){let R;try{R=eW.realpathSync(this._scriptPath)}catch{R=this._scriptPath}M=x0.resolve(x0.dirname(R),M)}if(M){let R=X(M,Y);if(!R&&!W._executableFile&&this._scriptPath){let P=x0.basename(this._scriptPath,x0.extname(this._scriptPath));if(P!==this._name)R=X(M,`${P}-${W._name}`)}Y=R||Y}Z=J.includes(x0.extname(Y));let G;if(H1.platform!=="win32")if(Z)$.unshift(Y),$=y9(H1.execArgv).concat($),G=$6.spawn(H1.argv[0],$,{stdio:"inherit"});else G=$6.spawn(Y,$,{stdio:"inherit"});else this._checkForMissingExecutable(Y,M,W._name),$.unshift(Y),$=y9(H1.execArgv).concat($),G=$6.spawn(H1.execPath,$,{stdio:"inherit"});if(!G.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((P)=>{H1.on(P,()=>{if(G.killed===!1&&G.exitCode===null)G.kill(P)})});let V=this._exitCallback;G.on("close",(R)=>{if(R=R??1,!V)H1.exit(R);else V(new Z6(R,"commander.executeSubCommandAsync","(close)"))}),G.on("error",(R)=>{if(R.code==="ENOENT")this._checkForMissingExecutable(Y,M,W._name);else if(R.code==="EACCES")throw Error(`'${Y}' not executable`);if(!V)H1.exit(1);else{let P=new Z6(1,"commander.executeSubCommandAsync","(error)");P.nestedError=R,V(P)}}),this.runningCommand=G}_dispatchSubcommand(W,$,Z){let J=this._findCommand(W);if(!J)this.help({error:!0});J._prepareForParse();let X;return X=this._chainOrCallSubCommandHook(X,J,"preSubcommand"),X=this._chainOrCall(X,()=>{if(J._executableHandler)this._executeSubCommand(J,$.concat(Z));else return J._parseCommand($,Z)}),X}_dispatchHelpCommand(W){if(!W)this.help();let $=this._findCommand(W);if($&&!$._executableHandler)$.help();return this._dispatchSubcommand(W,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((W,$)=>{if(W.required&&this.args[$]==null)this.missingArgument(W.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let W=(Z,J,X)=>{let Y=J;if(J!==null&&Z.parseArg){let M=`error: command-argument value '${J}' is invalid for argument '${Z.name()}'.`;Y=this._callParseArg(Z,J,X,M)}return Y};this._checkNumberOfArguments();let $=[];this.registeredArguments.forEach((Z,J)=>{let X=Z.defaultValue;if(Z.variadic){if(J<this.args.length){if(X=this.args.slice(J),Z.parseArg)X=X.reduce((Y,M)=>{return W(Z,M,Y)},Z.defaultValue)}else if(X===void 0)X=[]}else if(J<this.args.length){if(X=this.args[J],Z.parseArg)X=W(Z,X,Z.defaultValue)}$[J]=X}),this.processedArgs=$}_chainOrCall(W,$){if(W?.then&&typeof W.then==="function")return W.then(()=>$());return $()}_chainOrCallHooks(W,$){let Z=W,J=[];if(this._getCommandAndAncestors().reverse().filter((X)=>X._lifeCycleHooks[$]!==void 0).forEach((X)=>{X._lifeCycleHooks[$].forEach((Y)=>{J.push({hookedCommand:X,callback:Y})})}),$==="postAction")J.reverse();return J.forEach((X)=>{Z=this._chainOrCall(Z,()=>{return X.callback(X.hookedCommand,this)})}),Z}_chainOrCallSubCommandHook(W,$,Z){let J=W;if(this._lifeCycleHooks[Z]!==void 0)this._lifeCycleHooks[Z].forEach((X)=>{J=this._chainOrCall(J,()=>{return X(this,$)})});return J}_parseCommand(W,$){let Z=this.parseOptions($);if(this._parseOptionsEnv(),this._parseOptionsImplied(),W=W.concat(Z.operands),$=Z.unknown,this.args=W.concat($),W&&this._findCommand(W[0]))return this._dispatchSubcommand(W[0],W.slice(1),$);if(this._getHelpCommand()&&W[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(W[1]);if(this._defaultCommandName)return this._outputHelpIfRequested($),this._dispatchSubcommand(this._defaultCommandName,W,$);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(Z.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let J=()=>{if(Z.unknown.length>0)this.unknownOption(Z.unknown[0])},X=`command:${this.name()}`;if(this._actionHandler){J(),this._processArguments();let Y;if(Y=this._chainOrCallHooks(Y,"preAction"),Y=this._chainOrCall(Y,()=>this._actionHandler(this.processedArgs)),this.parent)Y=this._chainOrCall(Y,()=>{this.parent.emit(X,W,$)});return Y=this._chainOrCallHooks(Y,"postAction"),Y}if(this.parent?.listenerCount(X))J(),this._processArguments(),this.parent.emit(X,W,$);else if(W.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",W,$);if(this.listenerCount("command:*"))this.emit("command:*",W,$);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(W){if(!W)return;return this.commands.find(($)=>$._name===W||$._aliases.includes(W))}_findOption(W){return this.options.find(($)=>$.is(W))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((W)=>{W.options.forEach(($)=>{if($.mandatory&&W.getOptionValue($.attributeName())===void 0)W.missingMandatoryOptionValue($)})})}_checkForConflictingLocalOptions(){let W=this.options.filter((Z)=>{let J=Z.attributeName();if(this.getOptionValue(J)===void 0)return!1;return this.getOptionValueSource(J)!=="default"});W.filter((Z)=>Z.conflictsWith.length>0).forEach((Z)=>{let J=W.find((X)=>Z.conflictsWith.includes(X.attributeName()));if(J)this._conflictingOption(Z,J)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((W)=>{W._checkForConflictingLocalOptions()})}parseOptions(W){let $=[],Z=[],J=$;function X(R){return R.length>1&&R[0]==="-"}let Y=(R)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(R))return!1;return!this._getCommandAndAncestors().some((P)=>P.options.map((w)=>w.short).some((w)=>/^-\d$/.test(w)))},M=null,G=null,V=0;while(V<W.length||G){let R=G??W[V++];if(G=null,R==="--"){if(J===Z)J.push(R);J.push(...W.slice(V));break}if(M&&(!X(R)||Y(R))){this.emit(`option:${M.name()}`,R);continue}if(M=null,X(R)){let P=this._findOption(R);if(P){if(P.required){let w=W[V++];if(w===void 0)this.optionMissingArgument(P);this.emit(`option:${P.name()}`,w)}else if(P.optional){let w=null;if(V<W.length&&(!X(W[V])||Y(W[V])))w=W[V++];this.emit(`option:${P.name()}`,w)}else this.emit(`option:${P.name()}`);M=P.variadic?P:null;continue}}if(R.length>2&&R[0]==="-"&&R[1]!=="-"){let P=this._findOption(`-${R[1]}`);if(P){if(P.required||P.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${P.name()}`,R.slice(2));else this.emit(`option:${P.name()}`),G=`-${R.slice(2)}`;continue}}if(/^--[^=]+=/.test(R)){let P=R.indexOf("="),w=this._findOption(R.slice(0,P));if(w&&(w.required||w.optional)){this.emit(`option:${w.name()}`,R.slice(P+1));continue}}if(J===$&&X(R)&&!(this.commands.length===0&&Y(R)))J=Z;if((this._enablePositionalOptions||this._passThroughOptions)&&$.length===0&&Z.length===0){if(this._findCommand(R)){$.push(R),Z.push(...W.slice(V));break}else if(this._getHelpCommand()&&R===this._getHelpCommand().name()){$.push(R,...W.slice(V));break}else if(this._defaultCommandName){Z.push(R,...W.slice(V));break}}if(this._passThroughOptions){J.push(R,...W.slice(V));break}J.push(R)}return{operands:$,unknown:Z}}opts(){if(this._storeOptionsAsProperties){let W={},$=this.options.length;for(let Z=0;Z<$;Z++){let J=this.options[Z].attributeName();W[J]=J===this._versionOptionName?this._version:this[J]}return W}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((W,$)=>Object.assign(W,$.opts()),{})}error(W,$){if(this._outputConfiguration.outputError(`${W}
22
22
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
23
  `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
24
- `),this.outputHelp({error:!0});let k=$||{},J=k.exitCode||1,Z=k.code||"commander.error";this._exit(J,Z,W)}_parseOptionsEnv(){this.options.forEach((W)=>{if(W.envVar&&W.envVar in XW.env){let $=W.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(W.required||W.optional)this.emit(`optionEnv:${W.name()}`,XW.env[W.envVar]);else this.emit(`optionEnv:${W.name()}`)}})}_parseOptionsImplied(){let W=new S$(this.options),$=(k)=>{return this.getOptionValue(k)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(k))};this.options.filter((k)=>k.implied!==void 0&&$(k.attributeName())&&W.valueFromOption(this.getOptionValue(k.attributeName()),k)).forEach((k)=>{Object.keys(k.implied).filter((J)=>!$(J)).forEach((J)=>{this.setOptionValueWithSource(J,k.implied[J],"implied")})})}missingArgument(W){let $=`error: missing required argument '${W}'`;this.error($,{code:"commander.missingArgument"})}optionMissingArgument(W){let $=`error: option '${W.flags}' argument missing`;this.error($,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(W){let $=`error: required option '${W.flags}' not specified`;this.error($,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(W,$){let k=(X)=>{let G=X.attributeName(),z=this.getOptionValue(G),V=this.options.find((R)=>R.negate&&G===R.attributeName()),w=this.options.find((R)=>!R.negate&&G===R.attributeName());if(V&&(V.presetArg===void 0&&z===!1||V.presetArg!==void 0&&z===V.presetArg))return V;return w||X},J=(X)=>{let G=k(X),z=G.attributeName();if(this.getOptionValueSource(z)==="env")return`environment variable '${G.envVar}'`;return`option '${G.flags}'`},Z=`error: ${J(W)} cannot be used with ${J($)}`;this.error(Z,{code:"commander.conflictingOption"})}unknownOption(W){if(this._allowUnknownOption)return;let $="";if(W.startsWith("--")&&this._showSuggestionAfterError){let J=[],Z=this;do{let X=Z.createHelp().visibleOptions(Z).filter((G)=>G.long).map((G)=>G.long);J=J.concat(X),Z=Z.parent}while(Z&&!Z._enablePositionalOptions);$=_9(W,J)}let k=`error: unknown option '${W}'${$}`;this.error(k,{code:"commander.unknownOption"})}_excessArguments(W){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,k=$===1?"":"s",Z=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${k} but got ${W.length}.`;this.error(Z,{code:"commander.excessArguments"})}unknownCommand(){let W=this.args[0],$="";if(this._showSuggestionAfterError){let J=[];this.createHelp().visibleCommands(this).forEach((Z)=>{if(J.push(Z.name()),Z.alias())J.push(Z.alias())}),$=_9(W,J)}let k=`error: unknown command '${W}'${$}`;this.error(k,{code:"commander.unknownCommand"})}version(W,$,k){if(W===void 0)return this._version;this._version=W,$=$||"-V, --version",k=k||"output the version number";let J=this.createOption($,k);return this._versionOptionName=J.attributeName(),this._registerOption(J),this.on("option:"+J.name(),()=>{this._outputConfiguration.writeOut(`${W}
25
- `),this._exit(0,"commander.version",W)}),this}description(W,$){if(W===void 0&&$===void 0)return this._description;if(this._description=W,$)this._argsDescription=$;return this}summary(W){if(W===void 0)return this._summary;return this._summary=W,this}alias(W){if(W===void 0)return this._aliases[0];let $=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)$=this.commands[this.commands.length-1];if(W===$._name)throw Error("Command alias can't be the same as its name");let k=this.parent?._findCommand(W);if(k){let J=[k.name()].concat(k.aliases()).join("|");throw Error(`cannot add alias '${W}' to command '${this.name()}' as already have command '${J}'`)}return $._aliases.push(W),this}aliases(W){if(W===void 0)return this._aliases;return W.forEach(($)=>this.alias($)),this}usage(W){if(W===void 0){if(this._usage)return this._usage;let $=this.registeredArguments.map((k)=>{return T$(k)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?$:[]).join(" ")}return this._usage=W,this}name(W){if(W===void 0)return this._name;return this._name=W,this}helpGroup(W){if(W===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=W,this}commandsGroup(W){if(W===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=W,this}optionsGroup(W){if(W===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=W,this}_initOptionGroup(W){if(this._defaultOptionGroup&&!W.helpGroupHeading)W.helpGroup(this._defaultOptionGroup)}_initCommandGroup(W){if(this._defaultCommandGroup&&!W.helpGroup())W.helpGroup(this._defaultCommandGroup)}nameFromFilename(W){return this._name=A1.basename(W,A1.extname(W)),this}executableDir(W){if(W===void 0)return this._executableDir;return this._executableDir=W,this}helpInformation(W){let $=this.createHelp(),k=this._getOutputContext(W);$.prepareContext({error:k.error,helpWidth:k.helpWidth,outputHasColors:k.hasColors});let J=$.formatHelp(this,$);if(k.hasColors)return J;return this._outputConfiguration.stripColor(J)}_getOutputContext(W){W=W||{};let $=!!W.error,k,J,Z;if($)k=(G)=>this._outputConfiguration.writeErr(G),J=this._outputConfiguration.getErrHasColors(),Z=this._outputConfiguration.getErrHelpWidth();else k=(G)=>this._outputConfiguration.writeOut(G),J=this._outputConfiguration.getOutHasColors(),Z=this._outputConfiguration.getOutHelpWidth();return{error:$,write:(G)=>{if(!J)G=this._outputConfiguration.stripColor(G);return k(G)},hasColors:J,helpWidth:Z}}outputHelp(W){let $;if(typeof W==="function")$=W,W=void 0;let k=this._getOutputContext(W),J={error:k.error,write:k.write,command:this};this._getCommandAndAncestors().reverse().forEach((X)=>X.emit("beforeAllHelp",J)),this.emit("beforeHelp",J);let Z=this.helpInformation({error:k.error});if($){if(Z=$(Z),typeof Z!=="string"&&!Buffer.isBuffer(Z))throw Error("outputHelp callback must return a string or a Buffer")}if(k.write(Z),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",J),this._getCommandAndAncestors().forEach((X)=>X.emit("afterAllHelp",J))}helpOption(W,$){if(typeof W==="boolean"){if(W){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(W??"-h, --help",$??"display help for command"),W||$)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(W){return this._helpOption=W,this._initOptionGroup(W),this}help(W){this.outputHelp(W);let $=Number(XW.exitCode??0);if($===0&&W&&typeof W!=="function"&&W.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(W,$){let k=["beforeAll","before","after","afterAll"];if(!k.includes(W))throw Error(`Unexpected value for position to addHelpText.
26
- Expecting one of '${k.join("', '")}'`);let J=`${W}Help`;return this.on(J,(Z)=>{let X;if(typeof $==="function")X=$({error:Z.error,command:Z.command});else X=$;if(X)Z.write(`${X}
27
- `)}),this}_outputHelpIfRequested(W){let $=this._getHelpOption();if($&&W.find((J)=>$.is(J)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function h9(W){return W.map(($)=>{if(!$.startsWith("--inspect"))return $;let k,J="127.0.0.1",Z="9229",X;if((X=$.match(/^(--inspect(-brk)?)$/))!==null)k=X[1];else if((X=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(k=X[1],/^\d+$/.test(X[3]))Z=X[3];else J=X[3];else if((X=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)k=X[1],J=X[3],Z=X[4];if(k&&Z!=="0")return`${k}=${J}:${parseInt(Z)+1}`;return $})}function u4(){if(XW.env.NO_COLOR||XW.env.FORCE_COLOR==="0"||XW.env.FORCE_COLOR==="false")return!1;if(XW.env.FORCE_COLOR||XW.env.CLICOLOR_FORCE!==void 0)return!0;return}N$.Command=l4;N$.useColor=u4});var E9=X0((Q$)=>{var{Argument:D9}=y8(),{Command:i4}=P9(),{CommanderError:j$,InvalidArgumentError:f9}=k8(),{Help:C$}=y4(),{Option:T9}=g4();Q$.program=new i4;Q$.createCommand=(W)=>new i4(W);Q$.createOption=(W,$)=>new T9(W,$);Q$.createArgument=(W,$)=>new D9(W,$);Q$.Command=i4;Q$.Option=T9;Q$.Argument=D9;Q$.Help=C$;Q$.CommanderError=j$;Q$.InvalidArgumentError=f9;Q$.InvalidOptionArgumentError=f9});var v9=r7(E9(),1),{program:JJ,createCommand:ZJ,createArgument:XJ,createOption:YJ,CommanderError:HJ,InvalidArgumentError:zJ,InvalidOptionArgumentError:GJ,Command:S9,Argument:MJ,Option:LJ,Help:KJ}=v9.default;import j4 from"path";import{fileURLToPath as l2}from"url";import{createRequire as i2}from"module";import{execSync as p2,spawn as t2}from"child_process";function aW(W){return typeof W>"u"||W===void 0}function _W(W){return typeof W==="string"}function u1(W){return typeof W==="number"}function Y0(W){return typeof W==="boolean"}function h0(W){return W===null}function N9(W){return W instanceof Date}function P0(W){return typeof W==="bigint"}function hW(W){return typeof W==="function"}function TW(W){return typeof W==="object"&&W!==null}function O9(W){return W[W.length-1]}function H(W){return Object.freeze(W)}function J8(W){if(bW(W))return W;else return[W]}function bW(W){return Array.isArray(W)}function yW(W){return W}var $W=H({is(W){return W.kind==="AlterTableNode"},create(W){return H({kind:"AlterTableNode",table:W})},cloneWithTableProps(W,$){return H({...W,...$})},cloneWithColumnAlteration(W,$){return H({...W,columnAlterations:W.columnAlterations?[...W.columnAlterations,$]:[$]})}});var i=H({is(W){return W.kind==="IdentifierNode"},create(W){return H({kind:"IdentifierNode",name:W})}});var X1=H({is(W){return W.kind==="CreateIndexNode"},create(W){return H({kind:"CreateIndexNode",name:i.create(W)})},cloneWith(W,$){return H({...W,...$})},cloneWithColumns(W,$){return H({...W,columns:[...W.columns||[],...$]})}});var m8=H({is(W){return W.kind==="CreateSchemaNode"},create(W,$){return H({kind:"CreateSchemaNode",schema:i.create(W),...$})},cloneWith(W,$){return H({...W,...$})}});var A9=["preserve rows","delete rows","drop"],BW=H({is(W){return W.kind==="CreateTableNode"},create(W){return H({kind:"CreateTableNode",table:W,columns:H([])})},cloneWithColumn(W,$){return H({...W,columns:H([...W.columns,$])})},cloneWithConstraint(W,$){return H({...W,constraints:W.constraints?H([...W.constraints,$]):H([$])})},cloneWithFrontModifier(W,$){return H({...W,frontModifiers:W.frontModifiers?H([...W.frontModifiers,$]):H([$])})},cloneWithEndModifier(W,$){return H({...W,endModifiers:W.endModifiers?H([...W.endModifiers,$]):H([$])})},cloneWith(W,$){return H({...W,...$})}});var IW=H({is(W){return W.kind==="SchemableIdentifierNode"},create(W){return H({kind:"SchemableIdentifierNode",identifier:i.create(W)})},createWithSchema(W,$){return H({kind:"SchemableIdentifierNode",schema:i.create(W),identifier:i.create($)})}});var l1=H({is(W){return W.kind==="DropIndexNode"},create(W,$){return H({kind:"DropIndexNode",name:IW.create(W),...$})},cloneWith(W,$){return H({...W,...$})}});var Z8=H({is(W){return W.kind==="DropSchemaNode"},create(W,$){return H({kind:"DropSchemaNode",schema:i.create(W),...$})},cloneWith(W,$){return H({...W,...$})}});var X8=H({is(W){return W.kind==="DropTableNode"},create(W,$){return H({kind:"DropTableNode",table:W,...$})},cloneWith(W,$){return H({...W,...$})}});var AW=H({is(W){return W.kind==="AliasNode"},create(W,$){return H({kind:"AliasNode",node:W,alias:$})}});var mW=H({is(W){return W.kind==="TableNode"},create(W){return H({kind:"TableNode",table:IW.create(W)})},createWithSchema(W,$){return H({kind:"TableNode",table:IW.createWithSchema(W,$)})}});function LW(W){return TW(W)&&hW(W.toOperationNode)}function c8(W){return TW(W)&&"expressionType"in W&&LW(W)}function j9(W){return TW(W)&&"expression"in W&&_W(W.alias)&&LW(W)}var h1=H({is(W){return W.kind==="SelectModifierNode"},create(W,$){return H({kind:"SelectModifierNode",modifier:W,of:$})},createWithExpression(W){return H({kind:"SelectModifierNode",rawModifier:W})}});var cW=H({is(W){return W.kind==="AndNode"},create(W,$){return H({kind:"AndNode",left:W,right:$})}});var Y1=H({is(W){return W.kind==="OrNode"},create(W,$){return H({kind:"OrNode",left:W,right:$})}});var u8=H({is(W){return W.kind==="OnNode"},create(W){return H({kind:"OnNode",on:W})},cloneWithOperation(W,$,k){return H({...W,on:$==="And"?cW.create(W.on,k):Y1.create(W.on,k)})}});var H1=H({is(W){return W.kind==="JoinNode"},create(W,$){return H({kind:"JoinNode",joinType:W,table:$,on:void 0})},createWithOn(W,$,k){return H({kind:"JoinNode",joinType:W,table:$,on:u8.create(k)})},cloneWithOn(W,$){return H({...W,on:W.on?u8.cloneWithOperation(W.on,"And",$):u8.create($)})}});var i1=H({is(W){return W.kind==="BinaryOperationNode"},create(W,$,k){return H({kind:"BinaryOperationNode",leftOperand:W,operator:$,rightOperand:k})}});var i$=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],p$=["+","-","*","/","%","^","&","|","#","<<",">>"],C9=["->","->>"],t$=[...i$,...p$,"&&","||"],s$=["exists","not exists"],a$=["not","-",...s$],Q9=[...t$,...C9,...a$,"between","between symmetric"],dW=H({is(W){return W.kind==="OperatorNode"},create(W){return H({kind:"OperatorNode",operator:W})}});function p4(W){return _W(W)&&C9.includes(W)}var WW=H({is(W){return W.kind==="ColumnNode"},create(W){return H({kind:"ColumnNode",column:i.create(W)})}});var D0=H({is(W){return W.kind==="SelectAllNode"},create(){return H({kind:"SelectAllNode"})}});var f0=H({is(W){return W.kind==="ReferenceNode"},create(W,$){return H({kind:"ReferenceNode",table:$,column:W})},createSelectAll(W){return H({kind:"ReferenceNode",table:W,column:D0.create()})}});class t4{#W;get dynamicReference(){return this.#W}get refType(){return}constructor(W){this.#W=W}toOperationNode(){return s4(this.#W)}}function l8(W){return TW(W)&&LW(W)&&_W(W.dynamicReference)}var z1=H({is(W){return W.kind==="OrderByItemNode"},create(W,$){return H({kind:"OrderByItemNode",orderBy:W,direction:$})},cloneWith(W,$){return H({...W,...$})}});var YW=H({is(W){return W.kind==="RawNode"},create(W,$){return H({kind:"RawNode",sqlFragments:H(W),parameters:H($)})},createWithSql(W){return YW.create([W],[])},createWithChild(W){return YW.create(["",""],[W])},createWithChildren(W){return YW.create(Array(W.length+1).fill(""),W)}});var x9=H({is(W){return W.kind==="CollateNode"},create(W){return H({kind:"CollateNode",collation:i.create(W)})}});class p1{#W;constructor(W){this.#W=H(W)}desc(){return new p1({node:z1.cloneWith(this.#W.node,{direction:YW.createWithSql("desc")})})}asc(){return new p1({node:z1.cloneWith(this.#W.node,{direction:YW.createWithSql("asc")})})}nullsLast(){return new p1({node:z1.cloneWith(this.#W.node,{nulls:"last"})})}nullsFirst(){return new p1({node:z1.cloneWith(this.#W.node,{nulls:"first"})})}collate(W){return new p1({node:z1.cloneWith(this.#W.node,{collation:x9.create(W)})})}toOperationNode(){return this.#W.node}}var q9=new Set;function P1(W){if(q9.has(W))return;q9.add(W),console.log(W)}function d4(W){return W==="asc"||W==="desc"}function oW(W){if(W.length===2)return[a4(W[0],W[1])];if(W.length===1){let[$]=W;if(Array.isArray($))return P1("orderBy(array) is deprecated, use multiple orderBy calls instead."),$.map((k)=>a4(k));return[a4($)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${W.length}`)}function a4(W,$){let k=d$(W);if(z1.is(k)){if($)throw Error("Cannot specify direction twice!");return k}return b9(k,$)}function d$(W){if(j1(W))return uW(W);if(l8(W))return W.toOperationNode();let[$,k]=W.split(" ");if(k)return P1("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),b9(nW($),k);return nW(W)}function b9(W,$){if(typeof $==="string"){if(!d4($))throw Error(`Invalid order by direction: ${$}`);return z1.create(W,YW.createWithSql($))}if(c8($))return P1("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),z1.create(W,$.toOperationNode());let k=z1.create(W);if(!$)return k;return $(new p1({node:k})).toOperationNode()}var T0=H({is(W){return W.kind==="JSONReferenceNode"},create(W,$){return H({kind:"JSONReferenceNode",reference:W,traversal:$})},cloneWithTraversal(W,$){return H({...W,traversal:$})}});var i8=H({is(W){return W.kind==="JSONOperatorChainNode"},create(W){return H({kind:"JSONOperatorChainNode",operator:W,values:H([])})},cloneWithValue(W,$){return H({...W,values:H([...W.values,$])})}});var t1=H({is(W){return W.kind==="JSONPathNode"},create(W){return H({kind:"JSONPathNode",inOperator:W,pathLegs:H([])})},cloneWithLeg(W,$){return H({...W,pathLegs:H([...W.pathLegs,$])})}});function s4(W){if(_W(W))return nW(W);return W.toOperationNode()}function C1(W){if(bW(W))return W.map(($)=>xW($));else return[xW(W)]}function xW(W){if(j1(W))return uW(W);return s4(W)}function B9(W,$){let k=nW(W);if(p4($))return T0.create(k,i8.create(dW.create($)));let J=$.slice(0,-1);if(p4(J))return T0.create(k,t1.create(dW.create(J)));throw Error(`Invalid JSON operator: ${$}`)}function nW(W){if(!W.includes("."))return f0.create(WW.create(W));let k=W.split(".").map(o4);if(k.length===3)return n$(k);if(k.length===2)return o$(k);throw Error(`invalid column reference ${W}`)}function I9(W){if(W.includes(" as ")){let[k,J]=W.split(" as ").map(o4);return AW.create(nW(k),i.create(J))}else return nW(W)}function n4(W){return WW.create(W)}function E0(W){if(W.includes(" ")){let[k,J]=W.split(" ").map(o4);if(!d4(J))throw Error(`invalid order direction "${J}" next to "${k}"`);return oW([k,J])[0]}else return n4(W)}function n$(W){let[$,k,J]=W;return f0.create(WW.create(J),mW.createWithSchema($,k))}function o$(W){let[$,k]=W;return f0.create(WW.create(k),mW.create($))}function o4(W){return W.trim()}var p8=H({is(W){return W.kind==="PrimitiveValueListNode"},create(W){return H({kind:"PrimitiveValueListNode",values:H([...W])})}});var s1=H({is(W){return W.kind==="ValueListNode"},create(W){return H({kind:"ValueListNode",values:H(W)})}});var vW=H({is(W){return W.kind==="ValueNode"},create(W){return H({kind:"ValueNode",value:W})},createImmediate(W){return H({kind:"ValueNode",value:W,immediate:!0})}});function y9(W){if(bW(W))return r$(W);return zW(W)}function zW(W){if(j1(W))return uW(W);return vW.create(W)}function t8(W){return u1(W)||Y0(W)||h0(W)}function Y8(W){if(!t8(W))throw Error(`unsafe immediate value ${JSON.stringify(W)}`);return vW.createImmediate(W)}function r$(W){if(W.some(j1))return s1.create(W.map(($)=>zW($)));return p8.create(W)}var rW=H({is(W){return W.kind==="ParensNode"},create(W){return H({kind:"ParensNode",node:W})}});function MW(W){if(W.length===3)return s8(W[0],W[1],W[2]);else if(W.length===1)return zW(W[0]);throw Error(`invalid arguments: ${JSON.stringify(W)}`)}function s8(W,$,k){if(e$($)&&m9(k))return i1.create(xW(W),r4($),vW.createImmediate(k));return i1.create(xW(W),r4($),y9(k))}function jW(W,$,k){return i1.create(xW(W),r4($),xW(k))}function e4(W,$){return v0(Object.entries(W).filter(([,k])=>!aW(k)).map(([k,J])=>s8(k,m9(J)?"is":"=",J)),$)}function v0(W,$,k=!0){let J=$==="and"?cW.create:Y1.create;if(W.length===0)return i1.create(vW.createImmediate(1),dW.create("="),vW.createImmediate($==="and"?1:0));let Z=g9(W[0]);for(let X=1;X<W.length;++X)Z=J(Z,g9(W[X]));if(W.length>1&&k)return rW.create(Z);return Z}function e$(W){return W==="is"||W==="is not"}function m9(W){return h0(W)||Y0(W)}function r4(W){if(_W(W)&&Q9.includes(W))return dW.create(W);if(LW(W))return W.toOperationNode();throw Error(`invalid operator ${JSON.stringify(W)}`)}function g9(W){return LW(W)?W.toOperationNode():W}var Q1=H({is(W){return W.kind==="OrderByNode"},create(W){return H({kind:"OrderByNode",items:H([...W])})},cloneWithItems(W,$){return H({...W,items:H([...W.items,...$])})}});var W6=H({is(W){return W.kind==="PartitionByNode"},create(W){return H({kind:"PartitionByNode",items:H(W)})},cloneWithItems(W,$){return H({...W,items:H([...W.items,...$])})}});var H8=H({is(W){return W.kind==="OverNode"},create(){return H({kind:"OverNode"})},cloneWithOrderByItems(W,$){return H({...W,orderBy:W.orderBy?Q1.cloneWithItems(W.orderBy,$):Q1.create($)})},cloneWithPartitionByItems(W,$){return H({...W,partitionBy:W.partitionBy?W6.cloneWithItems(W.partitionBy,$):W6.create($)})}});var H0=H({is(W){return W.kind==="FromNode"},create(W){return H({kind:"FromNode",froms:H(W)})},cloneWithFroms(W,$){return H({...W,froms:H([...W.froms,...$])})}});var $6=H({is(W){return W.kind==="GroupByNode"},create(W){return H({kind:"GroupByNode",items:H(W)})},cloneWithItems(W,$){return H({...W,items:H([...W.items,...$])})}});var k6=H({is(W){return W.kind==="HavingNode"},create(W){return H({kind:"HavingNode",having:W})},cloneWithOperation(W,$,k){return H({...W,having:$==="And"?cW.create(W.having,k):Y1.create(W.having,k)})}});var fW=H({is(W){return W.kind==="InsertQueryNode"},create(W,$,k){return H({kind:"InsertQueryNode",into:W,...$&&{with:$},replace:k})},createWithoutInto(){return H({kind:"InsertQueryNode"})},cloneWith(W,$){return H({...W,...$})}});var a8=H({is(W){return W.kind==="ListNode"},create(W){return H({kind:"ListNode",items:H(W)})}});var D1=H({is(W){return W.kind==="UpdateQueryNode"},create(W,$){return H({kind:"UpdateQueryNode",table:W.length===1?W[0]:a8.create(W),...$&&{with:$}})},createWithoutTable(){return H({kind:"UpdateQueryNode"})},cloneWithFromItems(W,$){return H({...W,from:W.from?H0.cloneWithFroms(W.from,$):H0.create($)})},cloneWithUpdates(W,$){return H({...W,updates:W.updates?H([...W.updates,...$]):$})},cloneWithLimit(W,$){return H({...W,limit:$})}});var z8=H({is(W){return W.kind==="UsingNode"},create(W){return H({kind:"UsingNode",tables:H(W)})},cloneWithTables(W,$){return H({...W,tables:H([...W.tables,...$])})}});var a1=H({is(W){return W.kind==="DeleteQueryNode"},create(W,$){return H({kind:"DeleteQueryNode",from:H0.create(W),...$&&{with:$}})},cloneWithOrderByItems:(W,$)=>g.cloneWithOrderByItems(W,$),cloneWithoutOrderBy:(W)=>g.cloneWithoutOrderBy(W),cloneWithLimit(W,$){return H({...W,limit:$})},cloneWithoutLimit(W){return H({...W,limit:void 0})},cloneWithUsing(W,$){return H({...W,using:W.using!==void 0?z8.cloneWithTables(W.using,$):z8.create($)})}});var qW=H({is(W){return W.kind==="WhereNode"},create(W){return H({kind:"WhereNode",where:W})},cloneWithOperation(W,$,k){return H({...W,where:$==="And"?cW.create(W.where,k):Y1.create(W.where,k)})}});var J6=H({is(W){return W.kind==="ReturningNode"},create(W){return H({kind:"ReturningNode",selections:H(W)})},cloneWithSelections(W,$){return H({...W,selections:W.selections?H([...W.selections,...$]):H($)})}});var c9=H({is(W){return W.kind==="ExplainNode"},create(W,$){return H({kind:"ExplainNode",format:W,options:$})}});var k1=H({is(W){return W.kind==="WhenNode"},create(W){return H({kind:"WhenNode",condition:W})},cloneWithResult(W,$){return H({...W,result:$})}});var eW=H({is(W){return W.kind==="MergeQueryNode"},create(W,$){return H({kind:"MergeQueryNode",into:W,...$&&{with:$}})},cloneWithUsing(W,$){return H({...W,using:$})},cloneWithWhen(W,$){return H({...W,whens:W.whens?H([...W.whens,$]):H([$])})},cloneWithThen(W,$){return H({...W,whens:W.whens?H([...W.whens.slice(0,-1),k1.cloneWithResult(W.whens[W.whens.length-1],$)]):void 0})}});var Z6=H({is(W){return W.kind==="OutputNode"},create(W){return H({kind:"OutputNode",selections:H(W)})},cloneWithSelections(W,$){return H({...W,selections:W.selections?H([...W.selections,...$]):H($)})}});var g=H({is(W){return HW.is(W)||fW.is(W)||D1.is(W)||a1.is(W)||eW.is(W)},cloneWithEndModifier(W,$){return H({...W,endModifiers:W.endModifiers?H([...W.endModifiers,$]):H([$])})},cloneWithWhere(W,$){return H({...W,where:W.where?qW.cloneWithOperation(W.where,"And",$):qW.create($)})},cloneWithJoin(W,$){return H({...W,joins:W.joins?H([...W.joins,$]):H([$])})},cloneWithReturning(W,$){return H({...W,returning:W.returning?J6.cloneWithSelections(W.returning,$):J6.create($)})},cloneWithoutReturning(W){return H({...W,returning:void 0})},cloneWithoutWhere(W){return H({...W,where:void 0})},cloneWithExplain(W,$,k){return H({...W,explain:c9.create($,k?.toOperationNode())})},cloneWithTop(W,$){return H({...W,top:$})},cloneWithOutput(W,$){return H({...W,output:W.output?Z6.cloneWithSelections(W.output,$):Z6.create($)})},cloneWithOrderByItems(W,$){return H({...W,orderBy:W.orderBy?Q1.cloneWithItems(W.orderBy,$):Q1.create($)})},cloneWithoutOrderBy(W){return H({...W,orderBy:void 0})}});var HW=H({is(W){return W.kind==="SelectQueryNode"},create(W){return H({kind:"SelectQueryNode",...W&&{with:W}})},createFrom(W,$){return H({kind:"SelectQueryNode",from:H0.create(W),...$&&{with:$}})},cloneWithSelections(W,$){return H({...W,selections:W.selections?H([...W.selections,...$]):H($)})},cloneWithDistinctOn(W,$){return H({...W,distinctOn:W.distinctOn?H([...W.distinctOn,...$]):H($)})},cloneWithFrontModifier(W,$){return H({...W,frontModifiers:W.frontModifiers?H([...W.frontModifiers,$]):H([$])})},cloneWithOrderByItems:(W,$)=>g.cloneWithOrderByItems(W,$),cloneWithGroupByItems(W,$){return H({...W,groupBy:W.groupBy?$6.cloneWithItems(W.groupBy,$):$6.create($)})},cloneWithLimit(W,$){return H({...W,limit:$})},cloneWithOffset(W,$){return H({...W,offset:$})},cloneWithFetch(W,$){return H({...W,fetch:$})},cloneWithHaving(W,$){return H({...W,having:W.having?k6.cloneWithOperation(W.having,"And",$):k6.create($)})},cloneWithSetOperations(W,$){return H({...W,setOperations:W.setOperations?H([...W.setOperations,...$]):H([...$])})},cloneWithoutSelections(W){return H({...W,selections:[]})},cloneWithoutLimit(W){return H({...W,limit:void 0})},cloneWithoutOffset(W){return H({...W,offset:void 0})},cloneWithoutOrderBy:(W)=>g.cloneWithoutOrderBy(W),cloneWithoutGroupBy(W){return H({...W,groupBy:void 0})}});class S0{#W;constructor(W){this.#W=H(W)}on(...W){return new S0({...this.#W,joinNode:H1.cloneWithOn(this.#W.joinNode,MW(W))})}onRef(W,$,k){return new S0({...this.#W,joinNode:H1.cloneWithOn(this.#W.joinNode,jW(W,$,k))})}onTrue(){return new S0({...this.#W,joinNode:H1.cloneWithOn(this.#W.joinNode,YW.createWithSql("true"))})}$call(W){return W(this)}toOperationNode(){return this.#W.joinNode}}var u9=H({is(W){return W.kind==="PartitionByItemNode"},create(W){return H({kind:"PartitionByItemNode",partitionBy:W})}});function l9(W){return C1(W).map(u9.create)}class N0{#W;constructor(W){this.#W=H(W)}orderBy(...W){return new N0({overNode:H8.cloneWithOrderByItems(this.#W.overNode,oW(W))})}clearOrderBy(){return new N0({overNode:g.cloneWithoutOrderBy(this.#W.overNode)})}partitionBy(W){return new N0({overNode:H8.cloneWithPartitionByItems(this.#W.overNode,l9(W))})}$call(W){return W(this)}toOperationNode(){return this.#W.overNode}}var O0=H({is(W){return W.kind==="SelectionNode"},create(W){return H({kind:"SelectionNode",selection:W})},createSelectAll(){return H({kind:"SelectionNode",selection:D0.create()})},createSelectAllFromTable(W){return H({kind:"SelectionNode",selection:f0.createSelectAll(W)})}});function NW(W){if(hW(W))return NW(W(G1()));else if(bW(W))return W.map(($)=>i9($));else return[i9(W)]}function i9(W){if(_W(W))return O0.create(I9(W));else if(l8(W))return O0.create(W.toOperationNode());else return O0.create(d8(W))}function CW(W){if(!W)return[O0.createSelectAll()];else if(Array.isArray(W))return W.map(p9);else return[p9(W)]}function p9(W){if(_W(W))return O0.createSelectAllFromTable(kW(W));throw Error(`invalid value selectAll expression: ${JSON.stringify(W)}`)}var t9=H({is(W){return W.kind==="ValuesNode"},create(W){return H({kind:"ValuesNode",values:H(W)})}});var s9=H({is(W){return W.kind==="DefaultInsertValueNode"},create(){return H({kind:"DefaultInsertValueNode"})}});function n8(W){let $=hW(W)?W(G1()):W,k=bW($)?$:H([$]);return Wk(k)}function Wk(W){let $=$k(W);return[H([...$.keys()].map(WW.create)),t9.create(W.map((k)=>kk(k,$)))]}function $k(W){let $=new Map;for(let k of W){let J=Object.keys(k);for(let Z of J)if(!$.has(Z)&&k[Z]!==void 0)$.set(Z,$.size)}return $}function kk(W,$){let k=Object.keys(W),J=Array.from({length:$.size}),Z=!1,X=k.length;for(let z of k){let V=$.get(z);if(aW(V)){X--;continue}let w=W[z];if(aW(w)||j1(w))Z=!0;J[V]=w}if(X<$.size||Z){let z=s9.create();return s1.create(J.map((V)=>aW(V)?z:zW(V)))}return p8.create(J)}var X6=H({is(W){return W.kind==="ColumnUpdateNode"},create(W,$){return H({kind:"ColumnUpdateNode",column:W,value:$})}});function a9(...W){if(W.length===2)return[X6.create(xW(W[0]),zW(W[1]))];return G8(W[0])}function G8(W){let $=hW(W)?W(G1()):W;return Object.entries($).filter(([k,J])=>J!==void 0).map(([k,J])=>{return X6.create(WW.create(k),zW(J))})}var d9=H({is(W){return W.kind==="OnDuplicateKeyNode"},create(W){return H({kind:"OnDuplicateKeyNode",updates:W})}});class Y6{insertId;numInsertedOrUpdatedRows;constructor(W,$){this.insertId=W,this.numInsertedOrUpdatedRows=$}}class M1 extends Error{node;constructor(W){super("no result");this.node=W}}function f1(W){return Object.prototype.hasOwnProperty.call(W,"prototype")}var gW=H({is(W){return W.kind==="OnConflictNode"},create(){return H({kind:"OnConflictNode"})},cloneWith(W,$){return H({...W,...$})},cloneWithIndexWhere(W,$){return H({...W,indexWhere:W.indexWhere?qW.cloneWithOperation(W.indexWhere,"And",$):qW.create($)})},cloneWithIndexOrWhere(W,$){return H({...W,indexWhere:W.indexWhere?qW.cloneWithOperation(W.indexWhere,"Or",$):qW.create($)})},cloneWithUpdateWhere(W,$){return H({...W,updateWhere:W.updateWhere?qW.cloneWithOperation(W.updateWhere,"And",$):qW.create($)})},cloneWithUpdateOrWhere(W,$){return H({...W,updateWhere:W.updateWhere?qW.cloneWithOperation(W.updateWhere,"Or",$):qW.create($)})},cloneWithoutIndexWhere(W){return H({...W,indexWhere:void 0})},cloneWithoutUpdateWhere(W){return H({...W,updateWhere:void 0})}});class T1{#W;constructor(W){this.#W=H(W)}column(W){let $=WW.create(W);return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?H([...this.#W.onConflictNode.columns,$]):H([$])})})}columns(W){let $=W.map(WW.create);return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?H([...this.#W.onConflictNode.columns,...$]):H($)})})}constraint(W){return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{constraint:i.create(W)})})}expression(W){return new T1({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{indexExpression:W.toOperationNode()})})}where(...W){return new T1({...this.#W,onConflictNode:gW.cloneWithIndexWhere(this.#W.onConflictNode,MW(W))})}whereRef(W,$,k){return new T1({...this.#W,onConflictNode:gW.cloneWithIndexWhere(this.#W.onConflictNode,jW(W,$,k))})}clearWhere(){return new T1({...this.#W,onConflictNode:gW.cloneWithoutIndexWhere(this.#W.onConflictNode)})}doNothing(){return new n9({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{doNothing:!0})})}doUpdateSet(W){return new M8({...this.#W,onConflictNode:gW.cloneWith(this.#W.onConflictNode,{updates:G8(W)})})}$call(W){return W(this)}}class n9{#W;constructor(W){this.#W=H(W)}toOperationNode(){return this.#W.onConflictNode}}class M8{#W;constructor(W){this.#W=H(W)}where(...W){return new M8({...this.#W,onConflictNode:gW.cloneWithUpdateWhere(this.#W.onConflictNode,MW(W))})}whereRef(W,$,k){return new M8({...this.#W,onConflictNode:gW.cloneWithUpdateWhere(this.#W.onConflictNode,jW(W,$,k))})}clearWhere(){return new M8({...this.#W,onConflictNode:gW.cloneWithoutUpdateWhere(this.#W.onConflictNode)})}$call(W){return W(this)}toOperationNode(){return this.#W.onConflictNode}}var o9=H({is(W){return W.kind==="TopNode"},create(W,$){return H({kind:"TopNode",expression:W,modifiers:$})}});function L1(W,$){if(!u1(W)&&!P0(W))throw Error(`Invalid top expression: ${W}`);if(!aW($)&&!Jk($))throw Error(`Invalid top modifiers: ${$}`);return o9.create(W,$)}function Jk(W){return W==="percent"||W==="with ties"||W==="percent with ties"}var z0=H({is(W){return W.kind==="OrActionNode"},create(W){return H({kind:"OrActionNode",action:W})}});class GW{#W;constructor(W){this.#W=H(W)}values(W){let[$,k]=n8(W);return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{columns:$,values:k})})}columns(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{columns:H(W.map(WW.create))})})}expression(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{values:uW(W)})})}defaultValues(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{defaultValues:!0})})}modifyEnd(W){return new GW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}ignore(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("ignore")})})}orIgnore(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("ignore")})})}orAbort(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("abort")})})}orFail(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("fail")})})}orReplace(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("replace")})})}orRollback(){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{orAction:z0.create("rollback")})})}top(W,$){return new GW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}onConflict(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{onConflict:W(new T1({onConflictNode:gW.create()})).toOperationNode()})})}onDuplicateKeyUpdate(W){return new GW({...this.#W,queryNode:fW.cloneWith(this.#W.queryNode,{onDuplicateKey:d9.create(G8(W))})})}returning(W){return new GW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(){return new GW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW())})}output(W){return new GW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new GW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}clearReturning(){return new GW({...this.#W,queryNode:g.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new GW({...this.#W})}$castTo(){return new GW(this.#W)}$narrowType(){return new GW(this.#W)}$assertType(){return new GW(this.#W)}withPlugin(W){return new GW({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new Y6($.insertId,$.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new GW({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}class H6{numDeletedRows;constructor(W){this.numDeletedRows=W}}var A0=H({is(W){return W.kind==="LimitNode"},create(W){return H({kind:"LimitNode",limit:W})}});class PW{#W;constructor(W){this.#W=H(W)}where(...W){return new PW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,MW(W))})}whereRef(W,$,k){return new PW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,jW(W,$,k))})}clearWhere(){return new PW({...this.#W,queryNode:g.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new PW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}using(W){return new PW({...this.#W,queryNode:a1.cloneWithUsing(this.#W.queryNode,K1(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}#$(W,$){return new PW({...this.#W,queryNode:g.cloneWithJoin(this.#W.queryNode,d1(W,$))})}returning(W){return new PW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new PW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new PW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new PW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}clearReturning(){return new PW({...this.#W,queryNode:g.cloneWithoutReturning(this.#W.queryNode)})}clearLimit(){return new PW({...this.#W,queryNode:a1.cloneWithoutLimit(this.#W.queryNode)})}orderBy(...W){return new PW({...this.#W,queryNode:g.cloneWithOrderByItems(this.#W.queryNode,oW(W))})}clearOrderBy(){return new PW({...this.#W,queryNode:g.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new PW({...this.#W,queryNode:a1.cloneWithLimit(this.#W.queryNode,A0.create(zW(W)))})}modifyEnd(W){return new PW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new PW({...this.#W})}$castTo(){return new PW(this.#W)}$narrowType(){return new PW(this.#W)}$assertType(){return new PW(this.#W)}withPlugin(W){return new PW({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new H6($.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new PW({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}class z6{numUpdatedRows;numChangedRows;constructor(W,$){this.numUpdatedRows=W,this.numChangedRows=$}}class KW{#W;constructor(W){this.#W=H(W)}where(...W){return new KW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,MW(W))})}whereRef(W,$,k){return new KW({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,jW(W,$,k))})}clearWhere(){return new KW({...this.#W,queryNode:g.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new KW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}from(W){return new KW({...this.#W,queryNode:D1.cloneWithFromItems(this.#W.queryNode,K1(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}#$(W,$){return new KW({...this.#W,queryNode:g.cloneWithJoin(this.#W.queryNode,d1(W,$))})}orderBy(...W){return new KW({...this.#W,queryNode:g.cloneWithOrderByItems(this.#W.queryNode,oW(W))})}clearOrderBy(){return new KW({...this.#W,queryNode:g.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new KW({...this.#W,queryNode:D1.cloneWithLimit(this.#W.queryNode,A0.create(zW(W)))})}set(...W){return new KW({...this.#W,queryNode:D1.cloneWithUpdates(this.#W.queryNode,a9(...W))})}returning(W){return new KW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new KW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new KW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new KW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}modifyEnd(W){return new KW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}clearReturning(){return new KW({...this.#W,queryNode:g.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new KW({...this.#W})}$castTo(){return new KW(this.#W)}$narrowType(){return new KW(this.#W)}$assertType(){return new KW(this.#W)}withPlugin(W){return new KW({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new z6($.numAffectedRows??BigInt(0),$.numChangedRows)]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new KW({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}var G6=H({is(W){return W.kind==="CommonTableExpressionNameNode"},create(W,$){return H({kind:"CommonTableExpressionNameNode",table:mW.create(W),columns:$?H($.map(WW.create)):void 0})}});var j0=H({is(W){return W.kind==="CommonTableExpressionNode"},create(W,$){return H({kind:"CommonTableExpressionNode",name:W,expression:$})},cloneWith(W,$){return H({...W,...$})}});class L8{#W;constructor(W){this.#W=H(W)}materialized(){return new L8({...this.#W,node:j0.cloneWith(this.#W.node,{materialized:!0})})}notMaterialized(){return new L8({...this.#W,node:j0.cloneWith(this.#W.node,{materialized:!1})})}toOperationNode(){return this.#W.node}}function M6(W,$){let k=$(e9()).toOperationNode();if(hW(W))return W(Zk(k)).toOperationNode();return j0.create(r9(W),k)}function Zk(W){return($)=>{return new L8({node:j0.create(r9($),W)})}}function r9(W){if(W.includes("(")){let $=W.split(/[\(\)]/),k=$[0],J=$[1].split(",").map((Z)=>Z.trim());return G6.create(k,J)}else return G6.create(W)}var K8=H({is(W){return W.kind==="WithNode"},create(W,$){return H({kind:"WithNode",expressions:H([W]),...$})},cloneWithExpression(W,$){return H({...W,expressions:H([...W.expressions,$])})}});var W5=["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 $5(W){let $="";for(let k=0;k<W;++k)$+=Xk();return $}function Xk(){return W5[~~(Math.random()*W5.length)]}function e(){return new k5}class k5{#W;get queryId(){if(this.#W===void 0)this.#W=$5(8);return this.#W}}function I(W){return W}class U8{nodeStack=[];#W=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),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.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),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this)});transformNode(W,$){if(!W)return W;this.nodeStack.push(W);let k=this.transformNodeImpl(W,$);return this.nodeStack.pop(),H(k)}transformNodeImpl(W,$){return this.#W[W.kind](W,$)}transformNodeList(W,$){if(!W)return W;return H(W.map((k)=>this.transformNode(k,$)))}transformSelectQuery(W,$){return I({kind:"SelectQueryNode",from:this.transformNode(W.from,$),selections:this.transformNodeList(W.selections,$),distinctOn:this.transformNodeList(W.distinctOn,$),joins:this.transformNodeList(W.joins,$),groupBy:this.transformNode(W.groupBy,$),orderBy:this.transformNode(W.orderBy,$),where:this.transformNode(W.where,$),frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),limit:this.transformNode(W.limit,$),offset:this.transformNode(W.offset,$),with:this.transformNode(W.with,$),having:this.transformNode(W.having,$),explain:this.transformNode(W.explain,$),setOperations:this.transformNodeList(W.setOperations,$),fetch:this.transformNode(W.fetch,$),top:this.transformNode(W.top,$)})}transformSelection(W,$){return I({kind:"SelectionNode",selection:this.transformNode(W.selection,$)})}transformColumn(W,$){return I({kind:"ColumnNode",column:this.transformNode(W.column,$)})}transformAlias(W,$){return I({kind:"AliasNode",node:this.transformNode(W.node,$),alias:this.transformNode(W.alias,$)})}transformTable(W,$){return I({kind:"TableNode",table:this.transformNode(W.table,$)})}transformFrom(W,$){return I({kind:"FromNode",froms:this.transformNodeList(W.froms,$)})}transformReference(W,$){return I({kind:"ReferenceNode",column:this.transformNode(W.column,$),table:this.transformNode(W.table,$)})}transformAnd(W,$){return I({kind:"AndNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)})}transformOr(W,$){return I({kind:"OrNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)})}transformValueList(W,$){return I({kind:"ValueListNode",values:this.transformNodeList(W.values,$)})}transformParens(W,$){return I({kind:"ParensNode",node:this.transformNode(W.node,$)})}transformJoin(W,$){return I({kind:"JoinNode",joinType:W.joinType,table:this.transformNode(W.table,$),on:this.transformNode(W.on,$)})}transformRaw(W,$){return I({kind:"RawNode",sqlFragments:H([...W.sqlFragments]),parameters:this.transformNodeList(W.parameters,$)})}transformWhere(W,$){return I({kind:"WhereNode",where:this.transformNode(W.where,$)})}transformInsertQuery(W,$){return I({kind:"InsertQueryNode",into:this.transformNode(W.into,$),columns:this.transformNodeList(W.columns,$),values:this.transformNode(W.values,$),returning:this.transformNode(W.returning,$),onConflict:this.transformNode(W.onConflict,$),onDuplicateKey:this.transformNode(W.onDuplicateKey,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),ignore:W.ignore,orAction:this.transformNode(W.orAction,$),replace:W.replace,explain:this.transformNode(W.explain,$),defaultValues:W.defaultValues,top:this.transformNode(W.top,$),output:this.transformNode(W.output,$)})}transformValues(W,$){return I({kind:"ValuesNode",values:this.transformNodeList(W.values,$)})}transformDeleteQuery(W,$){return I({kind:"DeleteQueryNode",from:this.transformNode(W.from,$),using:this.transformNode(W.using,$),joins:this.transformNodeList(W.joins,$),where:this.transformNode(W.where,$),returning:this.transformNode(W.returning,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),orderBy:this.transformNode(W.orderBy,$),limit:this.transformNode(W.limit,$),explain:this.transformNode(W.explain,$),top:this.transformNode(W.top,$),output:this.transformNode(W.output,$)})}transformReturning(W,$){return I({kind:"ReturningNode",selections:this.transformNodeList(W.selections,$)})}transformCreateTable(W,$){return I({kind:"CreateTableNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),constraints:this.transformNodeList(W.constraints,$),temporary:W.temporary,ifNotExists:W.ifNotExists,onCommit:W.onCommit,frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),selectQuery:this.transformNode(W.selectQuery,$)})}transformColumnDefinition(W,$){return I({kind:"ColumnDefinitionNode",column:this.transformNode(W.column,$),dataType:this.transformNode(W.dataType,$),references:this.transformNode(W.references,$),primaryKey:W.primaryKey,autoIncrement:W.autoIncrement,unique:W.unique,notNull:W.notNull,unsigned:W.unsigned,defaultTo:this.transformNode(W.defaultTo,$),check:this.transformNode(W.check,$),generated:this.transformNode(W.generated,$),frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),nullsNotDistinct:W.nullsNotDistinct,identity:W.identity,ifNotExists:W.ifNotExists})}transformAddColumn(W,$){return I({kind:"AddColumnNode",column:this.transformNode(W.column,$)})}transformDropTable(W,$){return I({kind:"DropTableNode",table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade})}transformOrderBy(W,$){return I({kind:"OrderByNode",items:this.transformNodeList(W.items,$)})}transformOrderByItem(W,$){return I({kind:"OrderByItemNode",orderBy:this.transformNode(W.orderBy,$),direction:this.transformNode(W.direction,$),collation:this.transformNode(W.collation,$),nulls:W.nulls})}transformGroupBy(W,$){return I({kind:"GroupByNode",items:this.transformNodeList(W.items,$)})}transformGroupByItem(W,$){return I({kind:"GroupByItemNode",groupBy:this.transformNode(W.groupBy,$)})}transformUpdateQuery(W,$){return I({kind:"UpdateQueryNode",table:this.transformNode(W.table,$),from:this.transformNode(W.from,$),joins:this.transformNodeList(W.joins,$),where:this.transformNode(W.where,$),updates:this.transformNodeList(W.updates,$),returning:this.transformNode(W.returning,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),explain:this.transformNode(W.explain,$),limit:this.transformNode(W.limit,$),top:this.transformNode(W.top,$),output:this.transformNode(W.output,$),orderBy:this.transformNode(W.orderBy,$)})}transformColumnUpdate(W,$){return I({kind:"ColumnUpdateNode",column:this.transformNode(W.column,$),value:this.transformNode(W.value,$)})}transformLimit(W,$){return I({kind:"LimitNode",limit:this.transformNode(W.limit,$)})}transformOffset(W,$){return I({kind:"OffsetNode",offset:this.transformNode(W.offset,$)})}transformOnConflict(W,$){return I({kind:"OnConflictNode",columns:this.transformNodeList(W.columns,$),constraint:this.transformNode(W.constraint,$),indexExpression:this.transformNode(W.indexExpression,$),indexWhere:this.transformNode(W.indexWhere,$),updates:this.transformNodeList(W.updates,$),updateWhere:this.transformNode(W.updateWhere,$),doNothing:W.doNothing})}transformOnDuplicateKey(W,$){return I({kind:"OnDuplicateKeyNode",updates:this.transformNodeList(W.updates,$)})}transformCreateIndex(W,$){return I({kind:"CreateIndexNode",name:this.transformNode(W.name,$),table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),unique:W.unique,using:this.transformNode(W.using,$),ifNotExists:W.ifNotExists,where:this.transformNode(W.where,$),nullsNotDistinct:W.nullsNotDistinct})}transformList(W,$){return I({kind:"ListNode",items:this.transformNodeList(W.items,$)})}transformDropIndex(W,$){return I({kind:"DropIndexNode",name:this.transformNode(W.name,$),table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade})}transformPrimaryKeyConstraint(W,$){return I({kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred})}transformUniqueConstraint(W,$){return I({kind:"UniqueConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),nullsNotDistinct:W.nullsNotDistinct,deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred})}transformForeignKeyConstraint(W,$){return I({kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(W.columns,$),references:this.transformNode(W.references,$),name:this.transformNode(W.name,$),onDelete:W.onDelete,onUpdate:W.onUpdate,deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred})}transformSetOperation(W,$){return I({kind:"SetOperationNode",operator:W.operator,expression:this.transformNode(W.expression,$),all:W.all})}transformReferences(W,$){return I({kind:"ReferencesNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),onDelete:W.onDelete,onUpdate:W.onUpdate})}transformCheckConstraint(W,$){return I({kind:"CheckConstraintNode",expression:this.transformNode(W.expression,$),name:this.transformNode(W.name,$)})}transformWith(W,$){return I({kind:"WithNode",expressions:this.transformNodeList(W.expressions,$),recursive:W.recursive})}transformCommonTableExpression(W,$){return I({kind:"CommonTableExpressionNode",name:this.transformNode(W.name,$),materialized:W.materialized,expression:this.transformNode(W.expression,$)})}transformCommonTableExpressionName(W,$){return I({kind:"CommonTableExpressionNameNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$)})}transformHaving(W,$){return I({kind:"HavingNode",having:this.transformNode(W.having,$)})}transformCreateSchema(W,$){return I({kind:"CreateSchemaNode",schema:this.transformNode(W.schema,$),ifNotExists:W.ifNotExists})}transformDropSchema(W,$){return I({kind:"DropSchemaNode",schema:this.transformNode(W.schema,$),ifExists:W.ifExists,cascade:W.cascade})}transformAlterTable(W,$){return I({kind:"AlterTableNode",table:this.transformNode(W.table,$),renameTo:this.transformNode(W.renameTo,$),setSchema:this.transformNode(W.setSchema,$),columnAlterations:this.transformNodeList(W.columnAlterations,$),addConstraint:this.transformNode(W.addConstraint,$),dropConstraint:this.transformNode(W.dropConstraint,$),renameConstraint:this.transformNode(W.renameConstraint,$),addIndex:this.transformNode(W.addIndex,$),dropIndex:this.transformNode(W.dropIndex,$)})}transformDropColumn(W,$){return I({kind:"DropColumnNode",column:this.transformNode(W.column,$)})}transformRenameColumn(W,$){return I({kind:"RenameColumnNode",column:this.transformNode(W.column,$),renameTo:this.transformNode(W.renameTo,$)})}transformAlterColumn(W,$){return I({kind:"AlterColumnNode",column:this.transformNode(W.column,$),dataType:this.transformNode(W.dataType,$),dataTypeExpression:this.transformNode(W.dataTypeExpression,$),setDefault:this.transformNode(W.setDefault,$),dropDefault:W.dropDefault,setNotNull:W.setNotNull,dropNotNull:W.dropNotNull})}transformModifyColumn(W,$){return I({kind:"ModifyColumnNode",column:this.transformNode(W.column,$)})}transformAddConstraint(W,$){return I({kind:"AddConstraintNode",constraint:this.transformNode(W.constraint,$)})}transformDropConstraint(W,$){return I({kind:"DropConstraintNode",constraintName:this.transformNode(W.constraintName,$),ifExists:W.ifExists,modifier:W.modifier})}transformRenameConstraint(W,$){return I({kind:"RenameConstraintNode",oldName:this.transformNode(W.oldName,$),newName:this.transformNode(W.newName,$)})}transformCreateView(W,$){return I({kind:"CreateViewNode",name:this.transformNode(W.name,$),temporary:W.temporary,orReplace:W.orReplace,ifNotExists:W.ifNotExists,materialized:W.materialized,columns:this.transformNodeList(W.columns,$),as:this.transformNode(W.as,$)})}transformRefreshMaterializedView(W,$){return I({kind:"RefreshMaterializedViewNode",name:this.transformNode(W.name,$),concurrently:W.concurrently,withNoData:W.withNoData})}transformDropView(W,$){return I({kind:"DropViewNode",name:this.transformNode(W.name,$),ifExists:W.ifExists,materialized:W.materialized,cascade:W.cascade})}transformGenerated(W,$){return I({kind:"GeneratedNode",byDefault:W.byDefault,always:W.always,identity:W.identity,stored:W.stored,expression:this.transformNode(W.expression,$)})}transformDefaultValue(W,$){return I({kind:"DefaultValueNode",defaultValue:this.transformNode(W.defaultValue,$)})}transformOn(W,$){return I({kind:"OnNode",on:this.transformNode(W.on,$)})}transformSelectModifier(W,$){return I({kind:"SelectModifierNode",modifier:W.modifier,rawModifier:this.transformNode(W.rawModifier,$),of:this.transformNodeList(W.of,$)})}transformCreateType(W,$){return I({kind:"CreateTypeNode",name:this.transformNode(W.name,$),enum:this.transformNode(W.enum,$)})}transformDropType(W,$){return I({kind:"DropTypeNode",name:this.transformNode(W.name,$),ifExists:W.ifExists})}transformExplain(W,$){return I({kind:"ExplainNode",format:W.format,options:this.transformNode(W.options,$)})}transformSchemableIdentifier(W,$){return I({kind:"SchemableIdentifierNode",schema:this.transformNode(W.schema,$),identifier:this.transformNode(W.identifier,$)})}transformAggregateFunction(W,$){return I({kind:"AggregateFunctionNode",func:W.func,aggregated:this.transformNodeList(W.aggregated,$),distinct:W.distinct,orderBy:this.transformNode(W.orderBy,$),withinGroup:this.transformNode(W.withinGroup,$),filter:this.transformNode(W.filter,$),over:this.transformNode(W.over,$)})}transformOver(W,$){return I({kind:"OverNode",orderBy:this.transformNode(W.orderBy,$),partitionBy:this.transformNode(W.partitionBy,$)})}transformPartitionBy(W,$){return I({kind:"PartitionByNode",items:this.transformNodeList(W.items,$)})}transformPartitionByItem(W,$){return I({kind:"PartitionByItemNode",partitionBy:this.transformNode(W.partitionBy,$)})}transformBinaryOperation(W,$){return I({kind:"BinaryOperationNode",leftOperand:this.transformNode(W.leftOperand,$),operator:this.transformNode(W.operator,$),rightOperand:this.transformNode(W.rightOperand,$)})}transformUnaryOperation(W,$){return I({kind:"UnaryOperationNode",operator:this.transformNode(W.operator,$),operand:this.transformNode(W.operand,$)})}transformUsing(W,$){return I({kind:"UsingNode",tables:this.transformNodeList(W.tables,$)})}transformFunction(W,$){return I({kind:"FunctionNode",func:W.func,arguments:this.transformNodeList(W.arguments,$)})}transformCase(W,$){return I({kind:"CaseNode",value:this.transformNode(W.value,$),when:this.transformNodeList(W.when,$),else:this.transformNode(W.else,$),isStatement:W.isStatement})}transformWhen(W,$){return I({kind:"WhenNode",condition:this.transformNode(W.condition,$),result:this.transformNode(W.result,$)})}transformJSONReference(W,$){return I({kind:"JSONReferenceNode",reference:this.transformNode(W.reference,$),traversal:this.transformNode(W.traversal,$)})}transformJSONPath(W,$){return I({kind:"JSONPathNode",inOperator:this.transformNode(W.inOperator,$),pathLegs:this.transformNodeList(W.pathLegs,$)})}transformJSONPathLeg(W,$){return I({kind:"JSONPathLegNode",type:W.type,value:W.value})}transformJSONOperatorChain(W,$){return I({kind:"JSONOperatorChainNode",operator:this.transformNode(W.operator,$),values:this.transformNodeList(W.values,$)})}transformTuple(W,$){return I({kind:"TupleNode",values:this.transformNodeList(W.values,$)})}transformMergeQuery(W,$){return I({kind:"MergeQueryNode",into:this.transformNode(W.into,$),using:this.transformNode(W.using,$),whens:this.transformNodeList(W.whens,$),with:this.transformNode(W.with,$),top:this.transformNode(W.top,$),endModifiers:this.transformNodeList(W.endModifiers,$),output:this.transformNode(W.output,$),returning:this.transformNode(W.returning,$)})}transformMatched(W,$){return I({kind:"MatchedNode",not:W.not,bySource:W.bySource})}transformAddIndex(W,$){return I({kind:"AddIndexNode",name:this.transformNode(W.name,$),columns:this.transformNodeList(W.columns,$),unique:W.unique,using:this.transformNode(W.using,$),ifNotExists:W.ifNotExists})}transformCast(W,$){return I({kind:"CastNode",expression:this.transformNode(W.expression,$),dataType:this.transformNode(W.dataType,$)})}transformFetch(W,$){return I({kind:"FetchNode",rowCount:this.transformNode(W.rowCount,$),modifier:W.modifier})}transformTop(W,$){return I({kind:"TopNode",expression:W.expression,modifiers:W.modifiers})}transformOutput(W,$){return I({kind:"OutputNode",selections:this.transformNodeList(W.selections,$)})}transformDataType(W,$){return W}transformSelectAll(W,$){return W}transformIdentifier(W,$){return W}transformValue(W,$){return W}transformPrimitiveValueList(W,$){return W}transformOperator(W,$){return W}transformDefaultInsertValue(W,$){return W}transformOrAction(W,$){return W}transformCollate(W,$){return W}}var Yk=H({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,RefreshMaterializedViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),Hk={json_agg:!0,to_json:!0};class L6 extends U8{#W;#$=new Set;#k=new Set;constructor(W){super();this.#W=W}transformNodeImpl(W,$){if(!this.#Z(W))return super.transformNodeImpl(W,$);let k=this.#X(W);for(let X of k)this.#k.add(X);let J=this.#z(W);for(let X of J)this.#$.add(X);let Z=super.transformNodeImpl(W,$);for(let X of J)this.#$.delete(X);for(let X of k)this.#k.delete(X);return Z}transformSchemableIdentifier(W,$){let k=super.transformSchemableIdentifier(W,$);if(k.schema||!this.#$.has(W.identifier.name))return k;return{...k,schema:i.create(this.#W)}}transformReferences(W,$){let k=super.transformReferences(W,$);if(k.table.table.schema)return k;return{...k,table:mW.createWithSchema(this.#W,k.table.table.identifier.name)}}transformAggregateFunction(W,$){return{...super.transformAggregateFunction({...W,aggregated:[]},$),aggregated:this.#J(W,$,"aggregated")}}transformFunction(W,$){return{...super.transformFunction({...W,arguments:[]},$),arguments:this.#J(W,$,"arguments")}}transformSelectModifier(W,$){return{...super.transformSelectModifier({...W,of:void 0},$),of:W.of?.map((k)=>mW.is(k)&&!k.table.schema?{...k,table:this.transformIdentifier(k.table.identifier,$)}:this.transformNode(k,$))}}#J(W,$,k){return Hk[W.func]?W[k].map((J)=>!mW.is(J)||J.table.schema?this.transformNode(J,$):{...J,table:this.transformIdentifier(J.table.identifier,$)}):this.transformNodeList(W[k],$)}#Z(W){return W.kind in Yk}#z(W){let $=new Set;if("name"in W&&W.name&&IW.is(W.name))this.#H(W.name,$);if("from"in W&&W.from)for(let k of W.from.froms)this.#Y(k,$);if("into"in W&&W.into)this.#Y(W.into,$);if("table"in W&&W.table)this.#Y(W.table,$);if("joins"in W&&W.joins)for(let k of W.joins)this.#Y(k.table,$);if("using"in W&&W.using)if(H1.is(W.using))this.#Y(W.using.table,$);else this.#Y(W.using,$);return $}#X(W){let $=new Set;if("with"in W&&W.with)this.#G(W.with,$);return $}#Y(W,$){if(mW.is(W))return this.#H(W.table,$);if(AW.is(W)&&mW.is(W.node))return this.#H(W.node.table,$);if(a8.is(W)){for(let k of W.items)this.#Y(k,$);return}if(z8.is(W)){for(let k of W.tables)this.#Y(k,$);return}}#H(W,$){let k=W.identifier.name;if(!this.#$.has(k)&&!this.#k.has(k))$.add(k)}#G(W,$){for(let k of W.expressions){let J=k.name.table.table.identifier.name;if(!this.#k.has(J))$.add(J)}}}class W1{#W;constructor(W){this.#W=new L6(W)}transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}async transformResult(W){return W.result}}var J5=H({is(W){return W.kind==="MatchedNode"},create(W,$=!1){return H({kind:"MatchedNode",not:W,bySource:$})}});function K6(W,$,k){return k1.create(v0([J5.create(!W.isMatched,W.bySource),...$&&$.length>0?[$.length===3&&k?jW($[0],$[1],$[2]):MW($)]:[]],"and",!1))}function C0(W){if(_W(W))return YW.create([W],[]);if(LW(W))return W.toOperationNode();return W}class o8{#W;#$;#k;constructor(){this.#W=new Promise((W,$)=>{this.#k=$,this.#$=W})}get promise(){return this.#W}resolve=(W)=>{if(this.#$)this.#$(W)};reject=(W)=>{if(this.#k)this.#k(W)}}async function r8(W){let $=new o8,k=new o8;return W.provideConnection(async(J)=>{return $.resolve(J),await k.promise}).catch((J)=>$.reject(J)),H({connection:await $.promise,release:k.resolve})}var zk=H([]);class V8{#W;constructor(W=zk){this.#W=W}get plugins(){return this.#W}transformQuery(W,$){for(let k of this.#W){let J=k.transformQuery({node:W,queryId:$});if(J.kind===W.kind)W=J;else throw Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${W.kind}`,`but it returned a ${J.kind}`].join(" "))}return W}async executeQuery(W){return await this.provideConnection(async($)=>{let k=await $.executeQuery(W);if("numUpdatedOrDeletedRows"in k)P1("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.");return await this.#$(k,W.queryId)})}async*stream(W,$){let{connection:k,release:J}=await r8(this);try{for await(let Z of k.streamQuery(W,$))yield await this.#$(Z,W.queryId)}finally{J()}}async#$(W,$){for(let k of this.#W)W=await k.transformResult({result:W,queryId:$});return W}}class Q0 extends V8{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin(W){return new Q0([...this.plugins,W])}withPlugins(W){return new Q0([...this.plugins,...W])}withPluginAtFront(W){return new Q0([W,...this.plugins])}withoutPlugins(){return new Q0([])}}var n1=new Q0;class U6{numChangedRows;constructor(W){this.numChangedRows=W}}class x1{#W;constructor(W){this.#W=H(W)}modifyEnd(W){return new x1({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new x1({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}using(...W){return new lW({...this.#W,queryNode:eW.cloneWithUsing(this.#W.queryNode,d1("Using",W))})}returning(W){return new x1({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new x1({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new x1({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new x1({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}}class lW{#W;constructor(W){this.#W=H(W)}modifyEnd(W){return new lW({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new lW({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}whenMatched(){return this.#$([])}whenMatchedAnd(...W){return this.#$(W)}whenMatchedAndRef(W,$,k){return this.#$([W,$,k],!0)}#$(W,$){return new V6({...this.#W,queryNode:eW.cloneWithWhen(this.#W.queryNode,K6({isMatched:!0},W,$))})}whenNotMatched(){return this.#k([])}whenNotMatchedAnd(...W){return this.#k(W)}whenNotMatchedAndRef(W,$,k){return this.#k([W,$,k],!0)}whenNotMatchedBySource(){return this.#k([],!1,!0)}whenNotMatchedBySourceAnd(...W){return this.#k(W,!1,!0)}whenNotMatchedBySourceAndRef(W,$,k){return this.#k([W,$,k],!0,!0)}returning(W){return new lW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,NW(W))})}returningAll(W){return new lW({...this.#W,queryNode:g.cloneWithReturning(this.#W.queryNode,CW(W))})}output(W){return new lW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,NW(W))})}outputAll(W){return new lW({...this.#W,queryNode:g.cloneWithOutput(this.#W.queryNode,CW(W))})}#k(W,$=!1,k=!1){let J={...this.#W,queryNode:eW.cloneWithWhen(this.#W.queryNode,K6({isMatched:!1,bySource:k},W,$))};return new(k?V6:Z5)(J)}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new lW({...this.#W})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){let W=this.compile(),$=await this.#W.executor.executeQuery(W),{adapter:k}=this.#W.executor,J=W.query;if(J.returning&&k.supportsReturning||J.output&&k.supportsOutput)return $.rows;return[new U6($.numAffectedRows)]}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}}class V6{#W;constructor(W){this.#W=H(W)}thenDelete(){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0("delete"))})}thenDoNothing(){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0("do nothing"))})}thenUpdate(W){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0(W(new KW({queryId:this.#W.queryId,executor:n1,queryNode:D1.createWithoutTable()}))))})}thenUpdateSet(...W){return this.thenUpdate(($)=>$.set(...W))}}class Z5{#W;constructor(W){this.#W=H(W)}thenDoNothing(){return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0("do nothing"))})}thenInsertValues(W){let[$,k]=n8(W);return new lW({...this.#W,queryNode:eW.cloneWithThen(this.#W.queryNode,C0(fW.cloneWith(fW.createWithoutInto(),{columns:$,values:k})))})}}class E1{#W;constructor(W){this.#W=H(W)}selectFrom(W){return x0({queryId:e(),executor:this.#W.executor,queryNode:HW.createFrom(K1(W),this.#W.withNode)})}selectNoFrom(W){return x0({queryId:e(),executor:this.#W.executor,queryNode:HW.cloneWithSelections(HW.create(this.#W.withNode),NW(W))})}insertInto(W){return new GW({queryId:e(),executor:this.#W.executor,queryNode:fW.create(kW(W),this.#W.withNode)})}replaceInto(W){return new GW({queryId:e(),executor:this.#W.executor,queryNode:fW.create(kW(W),this.#W.withNode,!0)})}deleteFrom(W){return new PW({queryId:e(),executor:this.#W.executor,queryNode:a1.create(K1(W),this.#W.withNode)})}updateTable(W){return new KW({queryId:e(),executor:this.#W.executor,queryNode:D1.create(K1(W),this.#W.withNode)})}mergeInto(W){return new x1({queryId:e(),executor:this.#W.executor,queryNode:eW.create(R6(W),this.#W.withNode)})}with(W,$){let k=M6(W,$);return new E1({...this.#W,withNode:this.#W.withNode?K8.cloneWithExpression(this.#W.withNode,k):K8.create(k)})}withRecursive(W,$){let k=M6(W,$);return new E1({...this.#W,withNode:this.#W.withNode?K8.cloneWithExpression(this.#W.withNode,k):K8.create(k,{recursive:!0})})}withPlugin(W){return new E1({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new E1({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new E1({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}}function e9(){return new E1({executor:n1})}function X5(W,$){return new S0({joinNode:H1.create(W,G0($))})}function Y5(){return new N0({overNode:H8.create()})}function d1(W,$){if($.length===3)return Mk(W,$[0],$[1],$[2]);else if($.length===2)return Gk(W,$[0],$[1]);else if($.length===1)return Lk(W,$[0]);else throw Error("not implemented")}function Gk(W,$,k){return k(X5(W,$)).toOperationNode()}function Mk(W,$,k,J){return H1.createWithOn(W,G0($),jW(k,"=",J))}function Lk(W,$){return H1.create(W,G0($))}var H5=H({is(W){return W.kind==="OffsetNode"},create(W){return H({kind:"OffsetNode",offset:W})}});var z5=H({is(W){return W.kind==="GroupByItemNode"},create(W){return H({kind:"GroupByItemNode",groupBy:W})}});function G5(W){return W=hW(W)?W(G1()):W,C1(W).map(z5.create)}var e8=H({is(W){return W.kind==="SetOperationNode"},create(W,$,k){return H({kind:"SetOperationNode",operator:W,expression:$,all:k})}});function M0(W,$,k){if(hW($))$=$(W4());if(!bW($))$=[$];return $.map((J)=>e8.create(W,uW(J),k))}class ZW{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new J4(this,W)}or(...W){return new $4(Y1.create(this.#W,MW(W)))}and(...W){return new k4(cW.create(this.#W,MW(W)))}$castTo(){return new ZW(this.#W)}$notNull(){return new ZW(this.#W)}toOperationNode(){return this.#W}}class J4{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return AW.create(this.#W.toOperationNode(),LW(this.#$)?this.#$.toOperationNode():i.create(this.#$))}}class $4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new J4(this,W)}or(...W){return new $4(Y1.create(this.#W,MW(W)))}$castTo(){return new $4(this.#W)}toOperationNode(){return rW.create(this.#W)}}class k4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new J4(this,W)}and(...W){return new k4(cW.create(this.#W,MW(W)))}$castTo(){return new k4(this.#W)}toOperationNode(){return rW.create(this.#W)}}var M5=H({is(W){return W.kind==="FetchNode"},create(W,$){return{kind:"FetchNode",rowCount:vW.create(W),modifier:$}}});function L5(W,$){if(!u1(W)&&!P0(W))throw Error(`Invalid fetch row count: ${W}`);if(!Kk($))throw Error(`Invalid fetch modifier: ${$}`);return M5.create(W,$)}function Kk(W){return W==="only"||W==="with ties"}class d{#W;constructor(W){this.#W=H(W)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...W){return new d({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,MW(W))})}whereRef(W,$,k){return new d({...this.#W,queryNode:g.cloneWithWhere(this.#W.queryNode,jW(W,$,k))})}having(...W){return new d({...this.#W,queryNode:HW.cloneWithHaving(this.#W.queryNode,MW(W))})}havingRef(W,$,k){return new d({...this.#W,queryNode:HW.cloneWithHaving(this.#W.queryNode,jW(W,$,k))})}select(W){return new d({...this.#W,queryNode:HW.cloneWithSelections(this.#W.queryNode,NW(W))})}distinctOn(W){return new d({...this.#W,queryNode:HW.cloneWithDistinctOn(this.#W.queryNode,C1(W))})}modifyFront(W){return new d({...this.#W,queryNode:HW.cloneWithFrontModifier(this.#W.queryNode,h1.createWithExpression(W.toOperationNode()))})}modifyEnd(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.createWithExpression(W.toOperationNode()))})}distinct(){return new d({...this.#W,queryNode:HW.cloneWithFrontModifier(this.#W.queryNode,h1.create("Distinct"))})}forUpdate(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForUpdate",W?J8(W).map(kW):void 0))})}forShare(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForShare",W?J8(W).map(kW):void 0))})}forKeyShare(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForKeyShare",W?J8(W).map(kW):void 0))})}forNoKeyUpdate(W){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("ForNoKeyUpdate",W?J8(W).map(kW):void 0))})}skipLocked(){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("SkipLocked"))})}noWait(){return new d({...this.#W,queryNode:g.cloneWithEndModifier(this.#W.queryNode,h1.create("NoWait"))})}selectAll(W){return new d({...this.#W,queryNode:HW.cloneWithSelections(this.#W.queryNode,CW(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}crossJoin(...W){return this.#$("CrossJoin",W)}innerJoinLateral(...W){return this.#$("LateralInnerJoin",W)}leftJoinLateral(...W){return this.#$("LateralLeftJoin",W)}crossJoinLateral(...W){return this.#$("LateralCrossJoin",W)}crossApply(...W){return this.#$("CrossApply",W)}outerApply(...W){return this.#$("OuterApply",W)}#$(W,$){return new d({...this.#W,queryNode:g.cloneWithJoin(this.#W.queryNode,d1(W,$))})}orderBy(...W){return new d({...this.#W,queryNode:g.cloneWithOrderByItems(this.#W.queryNode,oW(W))})}groupBy(W){return new d({...this.#W,queryNode:HW.cloneWithGroupByItems(this.#W.queryNode,G5(W))})}limit(W){return new d({...this.#W,queryNode:HW.cloneWithLimit(this.#W.queryNode,A0.create(zW(W)))})}offset(W){return new d({...this.#W,queryNode:HW.cloneWithOffset(this.#W.queryNode,H5.create(zW(W)))})}fetch(W,$="only"){return new d({...this.#W,queryNode:HW.cloneWithFetch(this.#W.queryNode,L5(W,$))})}top(W,$){return new d({...this.#W,queryNode:g.cloneWithTop(this.#W.queryNode,L1(W,$))})}union(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("union",W,!1))})}unionAll(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("union",W,!0))})}intersect(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("intersect",W,!1))})}intersectAll(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("intersect",W,!0))})}except(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("except",W,!1))})}exceptAll(W){return new d({...this.#W,queryNode:HW.cloneWithSetOperations(this.#W.queryNode,M0("except",W,!0))})}as(W){return new K5(this,W)}clearSelect(){return new d({...this.#W,queryNode:HW.cloneWithoutSelections(this.#W.queryNode)})}clearWhere(){return new d({...this.#W,queryNode:g.cloneWithoutWhere(this.#W.queryNode)})}clearLimit(){return new d({...this.#W,queryNode:HW.cloneWithoutLimit(this.#W.queryNode)})}clearOffset(){return new d({...this.#W,queryNode:HW.cloneWithoutOffset(this.#W.queryNode)})}clearOrderBy(){return new d({...this.#W,queryNode:g.cloneWithoutOrderBy(this.#W.queryNode)})}clearGroupBy(){return new d({...this.#W,queryNode:HW.cloneWithoutGroupBy(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new d({...this.#W})}$castTo(){return new d(this.#W)}$narrowType(){return new d(this.#W)}$assertType(){return new d(this.#W)}$asTuple(){return new ZW(this.toOperationNode())}$asScalar(){return new ZW(this.toOperationNode())}withPlugin(W){return new d({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){let W=this.compile();return(await this.#W.executor.executeQuery(W)).rows}async executeTakeFirst(){let[W]=await this.execute();return W}async executeTakeFirstOrThrow(W=M1){let $=await this.executeTakeFirst();if($===void 0)throw f1(W)?new W(this.toOperationNode()):W(this.toOperationNode());return $}async*stream(W=100){let $=this.compile(),k=this.#W.executor.stream($,W);for await(let J of k)yield*J.rows}async explain(W,$){return await new d({...this.#W,queryNode:g.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}function x0(W){return new d(W)}class K5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return AW.create(this.#W.toOperationNode(),i.create(this.#$))}}var v1=H({is(W){return W.kind==="AggregateFunctionNode"},create(W,$=[]){return H({kind:"AggregateFunctionNode",func:W,aggregated:$})},cloneWithDistinct(W){return H({...W,distinct:!0})},cloneWithOrderBy(W,$,k=!1){let J=k?"withinGroup":"orderBy";return H({...W,[J]:W[J]?Q1.cloneWithItems(W[J],$):Q1.create($)})},cloneWithFilter(W,$){return H({...W,filter:W.filter?qW.cloneWithOperation(W.filter,"And",$):qW.create($)})},cloneWithOrFilter(W,$){return H({...W,filter:W.filter?qW.cloneWithOperation(W.filter,"Or",$):qW.create($)})},cloneWithOver(W,$){return H({...W,over:$})}});var F6=H({is(W){return W.kind==="FunctionNode"},create(W,$){return H({kind:"FunctionNode",func:W,arguments:$})}});class iW{#W;constructor(W){this.#W=H(W)}get expressionType(){return}as(W){return new U5(this,W)}distinct(){return new iW({...this.#W,aggregateFunctionNode:v1.cloneWithDistinct(this.#W.aggregateFunctionNode)})}orderBy(...W){return new iW({...this.#W,aggregateFunctionNode:g.cloneWithOrderByItems(this.#W.aggregateFunctionNode,oW(W))})}clearOrderBy(){return new iW({...this.#W,aggregateFunctionNode:g.cloneWithoutOrderBy(this.#W.aggregateFunctionNode)})}withinGroupOrderBy(...W){return new iW({...this.#W,aggregateFunctionNode:v1.cloneWithOrderBy(this.#W.aggregateFunctionNode,oW(W),!0)})}filterWhere(...W){return new iW({...this.#W,aggregateFunctionNode:v1.cloneWithFilter(this.#W.aggregateFunctionNode,MW(W))})}filterWhereRef(W,$,k){return new iW({...this.#W,aggregateFunctionNode:v1.cloneWithFilter(this.#W.aggregateFunctionNode,jW(W,$,k))})}over(W){let $=Y5();return new iW({...this.#W,aggregateFunctionNode:v1.cloneWithOver(this.#W.aggregateFunctionNode,(W?W($):$).toOperationNode())})}$call(W){return W(this)}$castTo(){return new iW(this.#W)}$notNull(){return new iW(this.#W)}toOperationNode(){return this.#W.aggregateFunctionNode}}class U5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return AW.create(this.#W.toOperationNode(),i.create(this.#$))}}function Z4(){let W=(k,J)=>{return new ZW(F6.create(k,C1(J??[])))},$=(k,J)=>{return new iW({aggregateFunctionNode:v1.create(k,J?C1(J):void 0)})};return Object.assign(W,{agg:$,avg(k){return $("avg",[k])},coalesce(...k){return W("coalesce",k)},count(k){return $("count",[k])},countAll(k){return new iW({aggregateFunctionNode:v1.create("count",CW(k))})},max(k){return $("max",[k])},min(k){return $("min",[k])},sum(k){return $("sum",[k])},any(k){return W("any",[k])},jsonAgg(k){return new iW({aggregateFunctionNode:v1.create("json_agg",[_W(k)?kW(k):k.toOperationNode()])})},toJson(k){return new ZW(F6.create("to_json",[_W(k)?kW(k):k.toOperationNode()]))}})}var V5=H({is(W){return W.kind==="UnaryOperationNode"},create(W,$){return H({kind:"UnaryOperationNode",operator:W,operand:$})}});function R5(W,$){return V5.create(dW.create(W),xW($))}var $1=H({is(W){return W.kind==="CaseNode"},create(W){return H({kind:"CaseNode",value:W})},cloneWithWhen(W,$){return H({...W,when:H(W.when?[...W.when,$]:[$])})},cloneWithThen(W,$){return H({...W,when:W.when?H([...W.when.slice(0,-1),k1.cloneWithResult(W.when[W.when.length-1],$)]):void 0})},cloneWith(W,$){return H({...W,...$})}});class R8{#W;constructor(W){this.#W=H(W)}when(...W){return new w6({...this.#W,node:$1.cloneWithWhen(this.#W.node,k1.create(MW(W)))})}}class w6{#W;constructor(W){this.#W=H(W)}then(W){return new F5({...this.#W,node:$1.cloneWithThen(this.#W.node,t8(W)?Y8(W):zW(W))})}}class F5{#W;constructor(W){this.#W=H(W)}when(...W){return new w6({...this.#W,node:$1.cloneWithWhen(this.#W.node,k1.create(MW(W)))})}else(W){return new w5({...this.#W,node:$1.cloneWith(this.#W.node,{else:t8(W)?Y8(W):zW(W)})})}end(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!0}))}}class w5{#W;constructor(W){this.#W=H(W)}end(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new ZW($1.cloneWith(this.#W.node,{isStatement:!0}))}}var _6=H({is(W){return W.kind==="JSONPathLegNode"},create(W,$){return H({kind:"JSONPathLegNode",type:W,value:$})}});class w8{#W;constructor(W){this.#W=W}at(W){return this.#$("ArrayLocation",W)}key(W){return this.#$("Member",W)}#$(W,$){if(T0.is(this.#W))return new F8(T0.cloneWithTraversal(this.#W,t1.is(this.#W.traversal)?t1.cloneWithLeg(this.#W.traversal,_6.create(W,$)):i8.cloneWithValue(this.#W.traversal,vW.createImmediate($))));return new F8(t1.cloneWithLeg(this.#W,_6.create(W,$)))}}class F8 extends w8{#W;constructor(W){super(W);this.#W=W}get expressionType(){return}as(W){return new _5(this,W)}$castTo(){return new F8(this.#W)}$notNull(){return new F8(this.#W)}toOperationNode(){return this.#W}}class _5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return AW.create(this.#W.toOperationNode(),LW(this.#$)?this.#$.toOperationNode():i.create(this.#$))}}var h6=H({is(W){return W.kind==="TupleNode"},create(W){return H({kind:"TupleNode",values:H(W)})}});var Uk=["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"],Vk=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],h5=H({is(W){return W.kind==="DataTypeNode"},create(W){return H({kind:"DataTypeNode",dataType:W})}});function P5(W){if(Uk.includes(W))return!0;if(Vk.some(($)=>$.test(W)))return!0;return!1}function U1(W){if(LW(W))return W.toOperationNode();if(P5(W))return h5.create(W);throw Error(`invalid column data type ${JSON.stringify(W)}`)}var D5=H({is(W){return W.kind==="CastNode"},create(W,$){return H({kind:"CastNode",expression:W,dataType:$})}});function W4(W=n1){function $(Z,X,G){return new ZW(s8(Z,X,G))}function k(Z,X){return new ZW(R5(Z,X))}let J=Object.assign($,{fn:void 0,eb:void 0,selectFrom(Z){return x0({queryId:e(),executor:W,queryNode:HW.createFrom(K1(Z))})},case(Z){return new R8({node:$1.create(aW(Z)?void 0:xW(Z))})},ref(Z,X){if(aW(X))return new ZW(nW(Z));return new w8(B9(Z,X))},jsonPath(){return new w8(t1.create())},table(Z){return new ZW(kW(Z))},val(Z){return new ZW(zW(Z))},refTuple(...Z){return new ZW(h6.create(Z.map(xW)))},tuple(...Z){return new ZW(h6.create(Z.map(zW)))},lit(Z){return new ZW(Y8(Z))},unary:k,not(Z){return k("not",Z)},exists(Z){return k("exists",Z)},neg(Z){return k("-",Z)},between(Z,X,G){return new ZW(i1.create(xW(Z),dW.create("between"),cW.create(zW(X),zW(G))))},betweenSymmetric(Z,X,G){return new ZW(i1.create(xW(Z),dW.create("between symmetric"),cW.create(zW(X),zW(G))))},and(Z){if(bW(Z))return new ZW(v0(Z,"and"));return new ZW(e4(Z,"and"))},or(Z){if(bW(Z))return new ZW(v0(Z,"or"));return new ZW(e4(Z,"or"))},parens(...Z){let X=MW(Z);if(rW.is(X))return new ZW(X);else return new ZW(rW.create(X))},cast(Z,X){return new ZW(D5.create(xW(Z),U1(X)))},withSchema(Z){return W4(W.withPluginAtFront(new W1(Z)))}});return J.fn=Z4(),J.eb=J,J}function G1(W){return W4()}function uW(W){if(LW(W))return W.toOperationNode();else if(hW(W))return W(G1()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(W)}`)}function d8(W){if(LW(W))return W.toOperationNode();else if(hW(W))return W(G1()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(W)}`)}function j1(W){return c8(W)||j9(W)||hW(W)}class P6{#W;get table(){return this.#W}constructor(W){this.#W=W}as(W){return new f5(this.#W,W)}}class f5{#W;#$;get table(){return this.#W}get alias(){return this.#$}constructor(W,$){this.#W=W,this.#$=$}toOperationNode(){return AW.create(kW(this.#W),i.create(this.#$))}}function T5(W){return TW(W)&&LW(W)&&_W(W.table)&&_W(W.alias)}function K1(W){if(bW(W))return W.map(($)=>G0($));else return[G0(W)]}function G0(W){if(_W(W))return R6(W);else if(T5(W))return W.toOperationNode();else return d8(W)}function R6(W){if(W.includes(" as ")){let[k,J]=W.split(" as ").map(E5);return AW.create(kW(k),i.create(J))}else return kW(W)}function kW(W){if(W.includes(".")){let[k,J]=W.split(".").map(E5);return mW.createWithSchema(k,J)}else return mW.create(W)}function E5(W){return W.trim()}var D6=H({is(W){return W.kind==="AddColumnNode"},create(W){return H({kind:"AddColumnNode",column:W})}});var UW=H({is(W){return W.kind==="ColumnDefinitionNode"},create(W,$){return H({kind:"ColumnDefinitionNode",column:WW.create(W),dataType:$})},cloneWithFrontModifier(W,$){return H({...W,frontModifiers:W.frontModifiers?H([...W.frontModifiers,$]):[$]})},cloneWithEndModifier(W,$){return H({...W,endModifiers:W.endModifiers?H([...W.endModifiers,$]):[$]})},cloneWith(W,$){return H({...W,...$})}});var f6=H({is(W){return W.kind==="DropColumnNode"},create(W){return H({kind:"DropColumnNode",column:WW.create(W)})}});var T6=H({is(W){return W.kind==="RenameColumnNode"},create(W,$){return H({kind:"RenameColumnNode",column:WW.create(W),renameTo:WW.create($)})}});var q0=H({is(W){return W.kind==="CheckConstraintNode"},create(W,$){return H({kind:"CheckConstraintNode",expression:W,name:$?i.create($):void 0})}});var v5=["no action","restrict","cascade","set null","set default"],b0=H({is(W){return W.kind==="ReferencesNode"},create(W,$){return H({kind:"ReferencesNode",table:W,columns:H([...$])})},cloneWithOnDelete(W,$){return H({...W,onDelete:$})},cloneWithOnUpdate(W,$){return H({...W,onUpdate:$})}});function X4(W){return LW(W)?W.toOperationNode():vW.createImmediate(W)}var _8=H({is(W){return W.kind==="GeneratedNode"},create(W){return H({kind:"GeneratedNode",...W})},createWithExpression(W){return H({kind:"GeneratedNode",always:!0,expression:W})},cloneWith(W,$){return H({...W,...$})}});var S5=H({is(W){return W.kind==="DefaultValueNode"},create(W){return H({kind:"DefaultValueNode",defaultValue:W})}});function B0(W){if(v5.includes(W))return W;throw Error(`invalid OnModifyForeignAction ${W}`)}class VW{#W;constructor(W){this.#W=W}autoIncrement(){return new VW(UW.cloneWith(this.#W,{autoIncrement:!0}))}identity(){return new VW(UW.cloneWith(this.#W,{identity:!0}))}primaryKey(){return new VW(UW.cloneWith(this.#W,{primaryKey:!0}))}references(W){let $=nW(W);if(!$.table||D0.is($.column))throw Error(`invalid call references('${W}'). The reference must have format table.column or schema.table.column`);return new VW(UW.cloneWith(this.#W,{references:b0.create($.table,[$.column])}))}onDelete(W){if(!this.#W.references)throw Error("on delete constraint can only be added for foreign keys");return new VW(UW.cloneWith(this.#W,{references:b0.cloneWithOnDelete(this.#W.references,B0(W))}))}onUpdate(W){if(!this.#W.references)throw Error("on update constraint can only be added for foreign keys");return new VW(UW.cloneWith(this.#W,{references:b0.cloneWithOnUpdate(this.#W.references,B0(W))}))}unique(){return new VW(UW.cloneWith(this.#W,{unique:!0}))}notNull(){return new VW(UW.cloneWith(this.#W,{notNull:!0}))}unsigned(){return new VW(UW.cloneWith(this.#W,{unsigned:!0}))}defaultTo(W){return new VW(UW.cloneWith(this.#W,{defaultTo:S5.create(X4(W))}))}check(W){return new VW(UW.cloneWith(this.#W,{check:q0.create(W.toOperationNode())}))}generatedAlwaysAs(W){return new VW(UW.cloneWith(this.#W,{generated:_8.createWithExpression(W.toOperationNode())}))}generatedAlwaysAsIdentity(){return new VW(UW.cloneWith(this.#W,{generated:_8.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new VW(UW.cloneWith(this.#W,{generated:_8.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#W.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new VW(UW.cloneWith(this.#W,{generated:_8.cloneWith(this.#W.generated,{stored:!0})}))}modifyFront(W){return new VW(UW.cloneWithFrontModifier(this.#W,W.toOperationNode()))}nullsNotDistinct(){return new VW(UW.cloneWith(this.#W,{nullsNotDistinct:!0}))}ifNotExists(){return new VW(UW.cloneWith(this.#W,{ifNotExists:!0}))}modifyEnd(W){return new VW(UW.cloneWithEndModifier(this.#W,W.toOperationNode()))}$call(W){return W(this)}toOperationNode(){return this.#W}}var E6=H({is(W){return W.kind==="ModifyColumnNode"},create(W){return H({kind:"ModifyColumnNode",column:W})}});var V1=H({is(W){return W.kind==="ForeignKeyConstraintNode"},create(W,$,k,J){return H({kind:"ForeignKeyConstraintNode",columns:W,references:b0.create($,k),name:J?i.create(J):void 0})},cloneWith(W,$){return H({...W,...$})}});class R1{#W;constructor(W){this.#W=W}onDelete(W){return new R1(V1.cloneWith(this.#W,{onDelete:B0(W)}))}onUpdate(W){return new R1(V1.cloneWith(this.#W,{onUpdate:B0(W)}))}deferrable(){return new R1(V1.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new R1(V1.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new R1(V1.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new R1(V1.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}var I0=H({is(W){return W.kind==="AddConstraintNode"},create(W){return H({kind:"AddConstraintNode",constraint:W})}});var S1=H({is(W){return W.kind==="UniqueConstraintNode"},create(W,$,k){return H({kind:"UniqueConstraintNode",columns:H(W.map(WW.create)),name:$?i.create($):void 0,nullsNotDistinct:k})},cloneWith(W,$){return H({...W,...$})}});var y0=H({is(W){return W.kind==="DropConstraintNode"},create(W){return H({kind:"DropConstraintNode",constraintName:i.create(W)})},cloneWith(W,$){return H({...W,...$})}});var g0=H({is(W){return W.kind==="AlterColumnNode"},create(W,$,k){return H({kind:"AlterColumnNode",column:WW.create(W),[$]:k})}});class Y4{#W;constructor(W){this.#W=W}setDataType(W){return new m0(g0.create(this.#W,"dataType",U1(W)))}setDefault(W){return new m0(g0.create(this.#W,"setDefault",X4(W)))}dropDefault(){return new m0(g0.create(this.#W,"dropDefault",!0))}setNotNull(){return new m0(g0.create(this.#W,"setNotNull",!0))}dropNotNull(){return new m0(g0.create(this.#W,"dropNotNull",!0))}$call(W){return W(this)}}class m0{#W;constructor(W){this.#W=W}toOperationNode(){return this.#W}}class o1{#W;constructor(W){this.#W=H(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class q1{#W;constructor(W){this.#W=H(W)}onDelete(W){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.onDelete(W)})}onUpdate(W){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.onUpdate(W)})}deferrable(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.deferrable()})}notDeferrable(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new q1({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyImmediate()})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery($W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(this.#W.constraintBuilder.toOperationNode())}),this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class L0{#W;constructor(W){this.#W=H(W)}ifExists(){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.cloneWith(this.#W.node.dropConstraint,{ifExists:!0})})})}cascade(){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.cloneWith(this.#W.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.cloneWith(this.#W.node.dropConstraint,{modifier:"restrict"})})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}var b1=H({is(W){return W.kind==="PrimaryKeyConstraintNode"},create(W,$){return H({kind:"PrimaryKeyConstraintNode",columns:H(W.map(WW.create)),name:$?i.create($):void 0})},cloneWith(W,$){return H({...W,...$})}});var r1=H({is(W){return W.kind==="AddIndexNode"},create(W){return H({kind:"AddIndexNode",name:i.create(W)})},cloneWith(W,$){return H({...W,...$})},cloneWithColumns(W,$){return H({...W,columns:[...W.columns||[],...$]})}});class e1{#W;constructor(W){this.#W=H(W)}unique(){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWith(this.#W.node.addIndex,{unique:!0})})})}column(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWithColumns(this.#W.node.addIndex,[E0(W)])})})}columns(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWithColumns(this.#W.node.addIndex,W.map(E0))})})}expression(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWithColumns(this.#W.node.addIndex,[W.toOperationNode()])})})}using(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.cloneWith(this.#W.node.addIndex,{using:YW.createWithSql(W)})})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class N1{#W;constructor(W){this.#W=W}nullsNotDistinct(){return new N1(S1.cloneWith(this.#W,{nullsNotDistinct:!0}))}deferrable(){return new N1(S1.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new N1(S1.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new N1(S1.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new N1(S1.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class B1{#W;constructor(W){this.#W=W}deferrable(){return new B1(b1.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new B1(b1.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new B1(b1.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new B1(b1.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class h8{#W;constructor(W){this.#W=W}$call(W){return W(this)}toOperationNode(){return this.#W}}var N5=H({is(W){return W.kind==="RenameConstraintNode"},create(W,$){return H({kind:"RenameConstraintNode",oldName:i.create(W),newName:i.create($)})}});class v6{#W;constructor(W){this.#W=H(W)}renameTo(W){return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{renameTo:kW(W)})})}setSchema(W){return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{setSchema:i.create(W)})})}alterColumn(W,$){let k=$(new Y4(W));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,k.toOperationNode())})}dropColumn(W){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,f6.create(W))})}renameColumn(W,$){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,T6.create(W,$))})}addColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,D6.create(J.toOperationNode()))})}modifyColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,E6.create(J.toOperationNode()))})}addUniqueConstraint(W,$,k=yW){let J=k(new N1(S1.create($,W)));return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(J.toOperationNode())})})}addCheckConstraint(W,$,k=yW){let J=k(new h8(q0.create($.toOperationNode(),W)));return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(J.toOperationNode())})})}addForeignKeyConstraint(W,$,k,J,Z=yW){let X=Z(new R1(V1.create($.map(WW.create),kW(k),J.map(WW.create),W)));return new q1({...this.#W,constraintBuilder:X})}addPrimaryKeyConstraint(W,$,k=yW){let J=k(new B1(b1.create($,W)));return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addConstraint:I0.create(J.toOperationNode())})})}dropConstraint(W){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropConstraint:y0.create(W)})})}renameConstraint(W,$){return new L0({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{renameConstraint:N5.create(W,$)})})}addIndex(W){return new e1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{addIndex:r1.create(W)})})}dropIndex(W){return new o1({...this.#W,node:$W.cloneWithTableProps(this.#W.node,{dropIndex:l1.create(W)})})}$call(W){return W(this)}}class F1{#W;constructor(W){this.#W=H(W)}alterColumn(W,$){let k=$(new Y4(W));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,k.toOperationNode())})}dropColumn(W){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,f6.create(W))})}renameColumn(W,$){return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,T6.create(W,$))})}addColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,D6.create(J.toOperationNode()))})}modifyColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new F1({...this.#W,node:$W.cloneWithColumnAlteration(this.#W.node,E6.create(J.toOperationNode()))})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class P8 extends U8{transformPrimitiveValueList(W){return s1.create(W.values.map(vW.createImmediate))}transformValue(W){return vW.createImmediate(W.value)}}class J1{#W;constructor(W){this.#W=H(W)}ifNotExists(){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{ifNotExists:!0})})}unique(){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{unique:!0})})}nullsNotDistinct(){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{nullsNotDistinct:!0})})}on(W){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{table:kW(W)})})}column(W){return new J1({...this.#W,node:X1.cloneWithColumns(this.#W.node,[E0(W)])})}columns(W){return new J1({...this.#W,node:X1.cloneWithColumns(this.#W.node,W.map(E0))})}expression(W){return new J1({...this.#W,node:X1.cloneWithColumns(this.#W.node,[W.toOperationNode()])})}using(W){return new J1({...this.#W,node:X1.cloneWith(this.#W.node,{using:YW.createWithSql(W)})})}where(...W){let $=new P8;return new J1({...this.#W,node:g.cloneWithWhere(this.#W.node,$.transformNode(MW(W),this.#W.queryId))})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class H4{#W;constructor(W){this.#W=H(W)}ifNotExists(){return new H4({...this.#W,node:m8.cloneWith(this.#W.node,{ifNotExists:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}function O5(W){if(A9.includes(W))return W;throw Error(`invalid OnCommitAction ${W}`)}class pW{#W;constructor(W){this.#W=H(W)}temporary(){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{temporary:!0})})}onCommit(W){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{onCommit:O5(W)})})}ifNotExists(){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{ifNotExists:!0})})}addColumn(W,$,k=yW){let J=k(new VW(UW.create(W,U1($))));return new pW({...this.#W,node:BW.cloneWithColumn(this.#W.node,J.toOperationNode())})}addPrimaryKeyConstraint(W,$,k=yW){let J=k(new B1(b1.create($,W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addUniqueConstraint(W,$,k=yW){let J=k(new N1(S1.create($,W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addCheckConstraint(W,$,k=yW){let J=k(new h8(q0.create($.toOperationNode(),W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addForeignKeyConstraint(W,$,k,J,Z=yW){let X=Z(new R1(V1.create($.map(WW.create),kW(k),J.map(WW.create),W)));return new pW({...this.#W,node:BW.cloneWithConstraint(this.#W.node,X.toOperationNode())})}modifyFront(W){return new pW({...this.#W,node:BW.cloneWithFrontModifier(this.#W.node,W.toOperationNode())})}modifyEnd(W){return new pW({...this.#W,node:BW.cloneWithEndModifier(this.#W.node,W.toOperationNode())})}as(W){return new pW({...this.#W,node:BW.cloneWith(this.#W.node,{selectQuery:uW(W)})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class c0{#W;constructor(W){this.#W=H(W)}on(W){return new c0({...this.#W,node:l1.cloneWith(this.#W.node,{table:kW(W)})})}ifExists(){return new c0({...this.#W,node:l1.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new c0({...this.#W,node:l1.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class D8{#W;constructor(W){this.#W=H(W)}ifExists(){return new D8({...this.#W,node:Z8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new D8({...this.#W,node:Z8.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class f8{#W;constructor(W){this.#W=H(W)}ifExists(){return new f8({...this.#W,node:X8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new f8({...this.#W,node:X8.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}var w1=H({is(W){return W.kind==="CreateViewNode"},create(W){return H({kind:"CreateViewNode",name:IW.create(W)})},cloneWith(W,$){return H({...W,...$})}});class S6{#W=new P8;transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}transformResult(W){return Promise.resolve(W.result)}}class I1{#W;constructor(W){this.#W=H(W)}temporary(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{temporary:!0})})}materialized(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{materialized:!0})})}ifNotExists(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{ifNotExists:!0})})}orReplace(){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{orReplace:!0})})}columns(W){return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{columns:W.map(n4)})})}as(W){let $=W.withPlugin(new S6).toOperationNode();return new I1({...this.#W,node:w1.cloneWith(this.#W.node,{as:$})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}var u0=H({is(W){return W.kind==="DropViewNode"},create(W){return H({kind:"DropViewNode",name:IW.create(W)})},cloneWith(W,$){return H({...W,...$})}});class l0{#W;constructor(W){this.#W=H(W)}materialized(){return new l0({...this.#W,node:u0.cloneWith(this.#W.node,{materialized:!0})})}ifExists(){return new l0({...this.#W,node:u0.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new l0({...this.#W,node:u0.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}var z4=H({is(W){return W.kind==="CreateTypeNode"},create(W){return H({kind:"CreateTypeNode",name:W})},cloneWithEnum(W,$){return H({...W,enum:s1.create($.map(vW.createImmediate))})}});class G4{#W;constructor(W){this.#W=H(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}asEnum(W){return new G4({...this.#W,node:z4.cloneWithEnum(this.#W.node,W)})}$call(W){return W(this)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}var M4=H({is(W){return W.kind==="DropTypeNode"},create(W){return H({kind:"DropTypeNode",name:W})},cloneWith(W,$){return H({...W,...$})}});class L4{#W;constructor(W){this.#W=H(W)}ifExists(){return new L4({...this.#W,node:M4.cloneWith(this.#W.node,{ifExists:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}function N6(W){if(W.includes(".")){let k=W.split(".").map(Rk);if(k.length===2)return IW.createWithSchema(k[0],k[1]);else throw Error(`invalid schemable identifier ${W}`)}else return IW.create(W)}function Rk(W){return W.trim()}var i0=H({is(W){return W.kind==="RefreshMaterializedViewNode"},create(W){return H({kind:"RefreshMaterializedViewNode",name:IW.create(W)})},cloneWith(W,$){return H({...W,...$})}});class p0{#W;constructor(W){this.#W=H(W)}concurrently(){return new p0({...this.#W,node:i0.cloneWith(this.#W.node,{concurrently:!0,withNoData:!1})})}withData(){return new p0({...this.#W,node:i0.cloneWith(this.#W.node,{withNoData:!1})})}withNoData(){return new p0({...this.#W,node:i0.cloneWith(this.#W.node,{withNoData:!0,concurrently:!1})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(){await this.#W.executor.executeQuery(this.compile())}}class t0{#W;constructor(W){this.#W=W}createTable(W){return new pW({queryId:e(),executor:this.#W,node:BW.create(kW(W))})}dropTable(W){return new f8({queryId:e(),executor:this.#W,node:X8.create(kW(W))})}createIndex(W){return new J1({queryId:e(),executor:this.#W,node:X1.create(W)})}dropIndex(W){return new c0({queryId:e(),executor:this.#W,node:l1.create(W)})}createSchema(W){return new H4({queryId:e(),executor:this.#W,node:m8.create(W)})}dropSchema(W){return new D8({queryId:e(),executor:this.#W,node:Z8.create(W)})}alterTable(W){return new v6({queryId:e(),executor:this.#W,node:$W.create(kW(W))})}createView(W){return new I1({queryId:e(),executor:this.#W,node:w1.create(W)})}refreshMaterializedView(W){return new p0({queryId:e(),executor:this.#W,node:i0.create(W)})}dropView(W){return new l0({queryId:e(),executor:this.#W,node:u0.create(W)})}createType(W){return new G4({queryId:e(),executor:this.#W,node:z4.create(N6(W))})}dropType(W){return new L4({queryId:e(),executor:this.#W,node:M4.create(N6(W))})}withPlugin(W){return new t0(this.#W.withPlugin(W))}withoutPlugins(){return new t0(this.#W.withoutPlugins())}withSchema(W){return new t0(this.#W.withPluginAtFront(new W1(W)))}}class O6{ref(W){return new t4(W)}table(W){return new P6(W)}}class A6{#W;constructor(W){this.#W=W}async provideConnection(W){let $=await this.#W.acquireConnection();try{return await W($)}finally{await this.#W.releaseConnection($)}}}class W0 extends V8{#W;#$;#k;constructor(W,$,k,J=[]){super(J);this.#W=W,this.#$=$,this.#k=k}get adapter(){return this.#$}compileQuery(W,$){return this.#W.compileQuery(W,$)}provideConnection(W){return this.#k.provideConnection(W)}withPlugins(W){return new W0(this.#W,this.#$,this.#k,[...this.plugins,...W])}withPlugin(W){return new W0(this.#W,this.#$,this.#k,[...this.plugins,W])}withPluginAtFront(W){return new W0(this.#W,this.#$,this.#k,[W,...this.plugins])}withConnectionProvider(W){return new W0(this.#W,this.#$,W,[...this.plugins])}withoutPlugins(){return new W0(this.#W,this.#$,this.#k,[])}}function K4(){if(typeof performance<"u"&&hW(performance.now))return performance.now();else return Date.now()}class j6{#W;#$;#k;#J;#Z;#z=new WeakSet;constructor(W,$){this.#J=!1,this.#W=W,this.#$=$}async init(){if(this.#Z)throw Error("driver has already been destroyed");if(!this.#k)this.#k=this.#W.init().then(()=>{this.#J=!0}).catch((W)=>{return this.#k=void 0,Promise.reject(W)});await this.#k}async acquireConnection(){if(this.#Z)throw Error("driver has already been destroyed");if(!this.#J)await this.init();let W=await this.#W.acquireConnection();if(!this.#z.has(W)){if(this.#X())this.#Y(W);this.#z.add(W)}return W}async releaseConnection(W){await this.#W.releaseConnection(W)}beginTransaction(W,$){return this.#W.beginTransaction(W,$)}commitTransaction(W){return this.#W.commitTransaction(W)}rollbackTransaction(W){return this.#W.rollbackTransaction(W)}savepoint(W,$,k){if(this.#W.savepoint)return this.#W.savepoint(W,$,k);throw Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(W,$,k){if(this.#W.rollbackToSavepoint)return this.#W.rollbackToSavepoint(W,$,k);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(W,$,k){if(this.#W.releaseSavepoint)return this.#W.releaseSavepoint(W,$,k);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){if(!this.#k)return;if(await this.#k,!this.#Z)this.#Z=this.#W.destroy().catch((W)=>{return this.#Z=void 0,Promise.reject(W)});await this.#Z}#X(){return this.#$.isLevelEnabled("query")||this.#$.isLevelEnabled("error")}#Y(W){let{executeQuery:$,streamQuery:k}=W,J=this;W.executeQuery=async(Z)=>{let X,G=K4();try{return await $.call(W,Z)}catch(z){throw X=z,await J.#H(z,Z,G),z}finally{if(!X)await J.#G(Z,G)}},W.streamQuery=async function*(Z,X){let G,z=K4();try{for await(let V of k.call(W,Z,X))yield V}catch(V){throw G=V,await J.#H(V,Z,z),V}finally{if(!G)await J.#G(Z,z,!0)}}}async#H(W,$,k){await this.#$.error(()=>({level:"error",error:W,query:$,queryDurationMillis:this.#L(k)}))}async#G(W,$,k=!1){await this.#$.query(()=>({level:"query",isStream:k,query:W,queryDurationMillis:this.#L($)}))}#L(W){return K4()-W}}var Fk=()=>{};class T8{#W;#$;constructor(W){this.#W=W}async provideConnection(W){while(this.#$)await this.#$.catch(Fk);return this.#$=this.#k(W).finally(()=>{this.#$=void 0}),this.#$}async#k(W){return await W(this.#W)}}var wk=["read only","read write"],_k=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function C6(W){if(W.accessMode&&!wk.includes(W.accessMode))throw Error(`invalid transaction access mode ${W.accessMode}`);if(W.isolationLevel&&!_k.includes(W.isolationLevel))throw Error(`invalid transaction isolation level ${W.isolationLevel}`)}var hk=["query","error"],Ew=H(hk);class Q6{#W;#$;constructor(W){if(hW(W))this.#$=W,this.#W=H({query:!0,error:!0});else this.#$=Pk,this.#W=H({query:W.includes("query"),error:W.includes("error")})}isLevelEnabled(W){return this.#W[W]}async query(W){if(this.#W.query)await this.#$(W())}async error(W){if(this.#W.error)await this.#$(W())}}function Pk(W){if(W.level==="query"){let $=`kysely:query:${W.isStream?"stream:":""}`;console.log(`${$} ${W.query.sql}`),console.log(`${$} duration: ${W.queryDurationMillis.toFixed(1)}ms`)}else if(W.level==="error")if(W.error instanceof Error)console.error(`kysely:error: ${W.error.stack??W.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:W.error,query:W.query.sql,queryDurationMillis:W.queryDurationMillis})}`)}function A5(W){return TW(W)&&hW(W.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class g1 extends E1{#W;constructor(W){let $,k;if(Dk(W))$={executor:W.executor},k={...W};else{let J=W.dialect,Z=J.createDriver(),X=J.createQueryCompiler(),G=J.createAdapter(),z=new Q6(W.log??[]),V=new j6(Z,z),w=new A6(V),R=new W0(X,G,w,W.plugins??[]);$={executor:R},k={config:W,executor:R,dialect:J,driver:V}}super($);this.#W=H(k)}get schema(){return new t0(this.#W.executor)}get dynamic(){return new O6}get introspection(){return this.#W.dialect.createIntrospector(this.withoutPlugins())}case(W){return new R8({node:$1.create(aW(W)?void 0:uW(W))})}get fn(){return Z4()}transaction(){return new U4({...this.#W})}startTransaction(){return new V4({...this.#W})}connection(){return new j5({...this.#W})}withPlugin(W){return new g1({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new g1({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new g1({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}withTables(){return new g1({...this.#W})}async destroy(){await this.#W.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#W.executor}executeQuery(W,$){if($!==void 0)P1("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");let k=A5(W)?W.compile():W;return this.getExecutor().executeQuery(k)}async[Symbol.asyncDispose](){await this.destroy()}}class U0 extends g1{#W;constructor(W){super(W);this.#W=W}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}async destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(W){return new U0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new U0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new U0({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}withTables(){return new U0({...this.#W})}}function Dk(W){return TW(W)&&TW(W.config)&&TW(W.driver)&&TW(W.executor)&&TW(W.dialect)}class j5{#W;constructor(W){this.#W=H(W)}async execute(W){return this.#W.executor.provideConnection(async($)=>{let k=this.#W.executor.withConnectionProvider(new T8($)),J=new g1({...this.#W,executor:k});return await W(J)})}}class U4{#W;constructor(W){this.#W=H(W)}setAccessMode(W){return new U4({...this.#W,accessMode:W})}setIsolationLevel(W){return new U4({...this.#W,isolationLevel:W})}async execute(W){let{isolationLevel:$,accessMode:k,...J}=this.#W,Z={isolationLevel:$,accessMode:k};return C6(Z),this.#W.executor.provideConnection(async(X)=>{let G=this.#W.executor.withConnectionProvider(new T8(X)),z=new U0({...J,executor:G}),V=!1;try{await this.#W.driver.beginTransaction(X,Z),V=!0;let w=await W(z);return await this.#W.driver.commitTransaction(X),w}catch(w){if(V)await this.#W.driver.rollbackTransaction(X);throw w}})}}class V4{#W;constructor(W){this.#W=H(W)}setAccessMode(W){return new V4({...this.#W,accessMode:W})}setIsolationLevel(W){return new V4({...this.#W,isolationLevel:W})}async execute(){let{isolationLevel:W,accessMode:$,...k}=this.#W,J={isolationLevel:W,accessMode:$};C6(J);let Z=await r8(this.#W.executor);return await this.#W.driver.beginTransaction(Z.connection,J),new y1({...k,connection:Z,executor:this.#W.executor.withConnectionProvider(new T8(Z.connection))})}}class y1 extends U0{#W;#$;#k;constructor(W){let $={isCommitted:!1,isRolledBack:!1};W={...W,executor:new $0(W.executor,$)};let{connection:k,...J}=W;super(J);this.#W=H(W),this.#k=$;let Z=e();this.#$=(X)=>W.executor.compileQuery(X,Z)}get isCommitted(){return this.#k.isCommitted}get isRolledBack(){return this.#k.isRolledBack}commit(){return K0(this.#k),new s0(async()=>{await this.#W.driver.commitTransaction(this.#W.connection.connection),this.#k.isCommitted=!0,this.#W.connection.release()})}rollback(){return K0(this.#k),new s0(async()=>{await this.#W.driver.rollbackTransaction(this.#W.connection.connection),this.#k.isRolledBack=!0,this.#W.connection.release()})}savepoint(W){return K0(this.#k),new s0(async()=>{return await this.#W.driver.savepoint?.(this.#W.connection.connection,W,this.#$),new y1({...this.#W})})}rollbackToSavepoint(W){return K0(this.#k),new s0(async()=>{return await this.#W.driver.rollbackToSavepoint?.(this.#W.connection.connection,W,this.#$),new y1({...this.#W})})}releaseSavepoint(W){return K0(this.#k),new s0(async()=>{return await this.#W.driver.releaseSavepoint?.(this.#W.connection.connection,W,this.#$),new y1({...this.#W})})}withPlugin(W){return new y1({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new y1({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new y1({...this.#W,executor:this.#W.executor.withPluginAtFront(new W1(W))})}withTables(){return new y1({...this.#W})}}class s0{#W;constructor(W){this.#W=W}async execute(){return await this.#W()}}function K0(W){if(W.isCommitted)throw Error("Transaction is already committed");if(W.isRolledBack)throw Error("Transaction is already rolled back")}class $0{#W;#$;constructor(W,$){if(W instanceof $0)this.#W=W.#W;else this.#W=W;this.#$=$}get adapter(){return this.#W.adapter}get plugins(){return this.#W.plugins}transformQuery(W,$){return this.#W.transformQuery(W,$)}compileQuery(W,$){return this.#W.compileQuery(W,$)}provideConnection(W){return this.#W.provideConnection(W)}executeQuery(W){return K0(this.#$),this.#W.executeQuery(W)}stream(W,$){return K0(this.#$),this.#W.stream(W,$)}withConnectionProvider(W){return new $0(this.#W.withConnectionProvider(W),this.#$)}withPlugin(W){return new $0(this.#W.withPlugin(W),this.#$)}withPlugins(W){return new $0(this.#W.withPlugins(W),this.#$)}withPluginAtFront(W){return new $0(this.#W.withPluginAtFront(W),this.#$)}withoutPlugins(){return new $0(this.#W.withoutPlugins(),this.#$)}}class E8{#W;constructor(W){this.#W=H(W)}get expressionType(){return}get isRawBuilder(){return!0}as(W){return new C5(this,W)}$castTo(){return new E8({...this.#W})}$notNull(){return new E8(this.#W)}withPlugin(W){return new E8({...this.#W,plugins:this.#W.plugins!==void 0?H([...this.#W.plugins,W]):H([W])})}toOperationNode(){return this.#k(this.#$())}compile(W){return this.#J(this.#$(W))}async execute(W){let $=this.#$(W);return $.executeQuery(this.#J($))}#$(W){let $=W!==void 0?W.getExecutor():n1;return this.#W.plugins!==void 0?$.withPlugins(this.#W.plugins):$}#k(W){return W.transformQuery(this.#W.rawNode,this.#W.queryId)}#J(W){return W.compileQuery(this.#k(W),this.#W.queryId)}}function m1(W){return new E8(W)}class C5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}get rawBuilder(){return this.#W}toOperationNode(){return AW.create(this.#W.toOperationNode(),LW(this.#$)?this.#$.toOperationNode():i.create(this.#$))}}var k0=Object.assign((W,...$)=>{return m1({queryId:e(),rawNode:YW.create(W,$?.map(Q5)??[])})},{ref(W){return m1({queryId:e(),rawNode:YW.createWithChild(nW(W))})},val(W){return m1({queryId:e(),rawNode:YW.createWithChild(zW(W))})},value(W){return this.val(W)},table(W){return m1({queryId:e(),rawNode:YW.createWithChild(kW(W))})},id(...W){let $=Array(W.length+1).fill(".");return $[0]="",$[$.length-1]="",m1({queryId:e(),rawNode:YW.create($,W.map(i.create))})},lit(W){return m1({queryId:e(),rawNode:YW.createWithChild(vW.createImmediate(W))})},literal(W){return this.lit(W)},raw(W){return m1({queryId:e(),rawNode:YW.createWithSql(W)})},join(W,$=k0`, `){let k=Array(Math.max(2*W.length-1,0)),J=$.toOperationNode();for(let Z=0;Z<W.length;++Z)if(k[2*Z]=Q5(W[Z]),Z!==W.length-1)k[2*Z+1]=J;return m1({queryId:e(),rawNode:YW.createWithChildren(k)})}});function Q5(W){if(LW(W))return W.toOperationNode();return zW(W)}class x6{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#W=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),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.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),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this)});visitNode=(W)=>{this.nodeStack.push(W),this.#W[W.kind](W),this.nodeStack.pop()}}var fk=/'/g;class q6 extends x6{#W="";#$=[];get numParameters(){return this.#$.length}compileQuery(W,$){return this.#W="",this.#$=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(W),H({query:W,queryId:$,sql:this.getSql(),parameters:[...this.#$]})}getSql(){return this.#W}visitSelectQuery(W){let $=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!fW.is(this.parentNode)&&!BW.is(this.parentNode)&&!w1.is(this.parentNode)&&!e8.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("select"),W.distinctOn)this.append(" "),this.compileDistinctOn(W.distinctOn);if(W.frontModifiers?.length)this.append(" "),this.compileList(W.frontModifiers," ");if(W.top)this.append(" "),this.visitNode(W.top);if(W.selections)this.append(" "),this.compileList(W.selections);if(W.from)this.append(" "),this.visitNode(W.from);if(W.joins)this.append(" "),this.compileList(W.joins," ");if(W.where)this.append(" "),this.visitNode(W.where);if(W.groupBy)this.append(" "),this.visitNode(W.groupBy);if(W.having)this.append(" "),this.visitNode(W.having);if(W.setOperations)this.append(" "),this.compileList(W.setOperations," ");if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if(W.offset)this.append(" "),this.visitNode(W.offset);if(W.fetch)this.append(" "),this.visitNode(W.fetch);if(W.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers([...W.endModifiers])," ");if($)this.append(")")}visitFrom(W){this.append("from "),this.compileList(W.froms)}visitSelection(W){this.visitNode(W.selection)}visitColumn(W){this.visitNode(W.column)}compileDistinctOn(W){this.append("distinct on ("),this.compileList(W),this.append(")")}compileList(W,$=", "){let k=W.length-1;for(let J=0;J<=k;J++)if(this.visitNode(W[J]),J<k)this.append($)}visitWhere(W){this.append("where "),this.visitNode(W.where)}visitHaving(W){this.append("having "),this.visitNode(W.having)}visitInsertQuery(W){let $=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!YW.is(this.parentNode)&&!k1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append(W.replace?"replace":"insert"),W.ignore)P1("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore");if(W.orAction)this.append(" "),this.visitNode(W.orAction);if(W.top)this.append(" "),this.visitNode(W.top);if(W.into)this.append(" into "),this.visitNode(W.into);if(W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.output)this.append(" "),this.visitNode(W.output);if(W.values)this.append(" "),this.visitNode(W.values);if(W.defaultValues)this.append(" "),this.append("default values");if(W.onConflict)this.append(" "),this.visitNode(W.onConflict);if(W.onDuplicateKey)this.append(" "),this.visitNode(W.onDuplicateKey);if(W.returning)this.append(" "),this.visitNode(W.returning);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitValues(W){this.append("values "),this.compileList(W.values)}visitDeleteQuery(W){let $=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!YW.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("delete "),W.top)this.visitNode(W.top),this.append(" ");if(this.visitNode(W.from),W.output)this.append(" "),this.visitNode(W.output);if(W.using)this.append(" "),this.visitNode(W.using);if(W.joins)this.append(" "),this.compileList(W.joins," ");if(W.where)this.append(" "),this.visitNode(W.where);if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if(W.returning)this.append(" "),this.visitNode(W.returning);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitReturning(W){this.append("returning "),this.compileList(W.selections)}visitAlias(W){this.visitNode(W.node),this.append(" as "),this.visitNode(W.alias)}visitReference(W){if(W.table)this.visitNode(W.table),this.append(".");this.visitNode(W.column)}visitSelectAll(W){this.append("*")}visitIdentifier(W){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(W),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(W){if(!_W(W.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(W.name))}visitAnd(W){this.visitNode(W.left),this.append(" and "),this.visitNode(W.right)}visitOr(W){this.visitNode(W.left),this.append(" or "),this.visitNode(W.right)}visitValue(W){if(W.immediate)this.appendImmediateValue(W.value);else this.appendValue(W.value)}visitValueList(W){this.append("("),this.compileList(W.values),this.append(")")}visitTuple(W){this.append("("),this.compileList(W.values),this.append(")")}visitPrimitiveValueList(W){this.append("(");let{values:$}=W;for(let k=0;k<$.length;++k)if(this.appendValue($[k]),k!==$.length-1)this.append(", ");this.append(")")}visitParens(W){this.append("("),this.visitNode(W.node),this.append(")")}visitJoin(W){if(this.append(Ek[W.joinType]),this.append(" "),this.visitNode(W.table),W.on)this.append(" "),this.visitNode(W.on)}visitOn(W){this.append("on "),this.visitNode(W.on)}visitRaw(W){let{sqlFragments:$,parameters:k}=W;for(let J=0;J<$.length;++J)if(this.append($[J]),k.length>J)this.visitNode(k[J])}visitOperator(W){this.append(W.operator)}visitTable(W){this.visitNode(W.table)}visitSchemableIdentifier(W){if(W.schema)this.visitNode(W.schema),this.append(".");this.visitNode(W.identifier)}visitCreateTable(W){if(this.append("create "),W.frontModifiers&&W.frontModifiers.length>0)this.compileList(W.frontModifiers," "),this.append(" ");if(W.temporary)this.append("temporary ");if(this.append("table "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.table),W.selectQuery)this.append(" as "),this.visitNode(W.selectQuery);else{if(this.append(" ("),this.compileList([...W.columns,...W.constraints??[]]),this.append(")"),W.onCommit)this.append(" on commit "),this.append(W.onCommit);if(W.endModifiers&&W.endModifiers.length>0)this.append(" "),this.compileList(W.endModifiers," ")}}visitColumnDefinition(W){if(W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.column),this.append(" "),this.visitNode(W.dataType),W.unsigned)this.append(" unsigned");if(W.frontModifiers&&W.frontModifiers.length>0)this.append(" "),this.compileList(W.frontModifiers," ");if(W.generated)this.append(" "),this.visitNode(W.generated);if(W.identity)this.append(" identity");if(W.defaultTo)this.append(" "),this.visitNode(W.defaultTo);if(W.notNull)this.append(" not null");if(W.unique)this.append(" unique");if(W.nullsNotDistinct)this.append(" nulls not distinct");if(W.primaryKey)this.append(" primary key");if(W.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if(W.references)this.append(" "),this.visitNode(W.references);if(W.check)this.append(" "),this.visitNode(W.check);if(W.endModifiers&&W.endModifiers.length>0)this.append(" "),this.compileList(W.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences(W){if(this.append("references "),this.visitNode(W.table),this.append(" ("),this.compileList(W.columns),this.append(")"),W.onDelete)this.append(" on delete "),this.append(W.onDelete);if(W.onUpdate)this.append(" on update "),this.append(W.onUpdate)}visitDropTable(W){if(this.append("drop table "),W.ifExists)this.append("if exists ");if(this.visitNode(W.table),W.cascade)this.append(" cascade")}visitDataType(W){this.append(W.dataType)}visitOrderBy(W){this.append("order by "),this.compileList(W.items)}visitOrderByItem(W){if(this.visitNode(W.orderBy),W.collation)this.append(" "),this.visitNode(W.collation);if(W.direction)this.append(" "),this.visitNode(W.direction);if(W.nulls)this.append(" nulls "),this.append(W.nulls)}visitGroupBy(W){this.append("group by "),this.compileList(W.items)}visitGroupByItem(W){this.visitNode(W.groupBy)}visitUpdateQuery(W){let $=this.parentNode!==void 0&&!rW.is(this.parentNode)&&!YW.is(this.parentNode)&&!k1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("update "),W.top)this.visitNode(W.top),this.append(" ");if(W.table)this.visitNode(W.table),this.append(" ");if(this.append("set "),W.updates)this.compileList(W.updates);if(W.output)this.append(" "),this.visitNode(W.output);if(W.from)this.append(" "),this.visitNode(W.from);if(W.joins){if(!W.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(W.joins," ")}if(W.where)this.append(" "),this.visitNode(W.where);if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if(W.returning)this.append(" "),this.visitNode(W.returning);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitColumnUpdate(W){this.visitNode(W.column),this.append(" = "),this.visitNode(W.value)}visitLimit(W){this.append("limit "),this.visitNode(W.limit)}visitOffset(W){this.append("offset "),this.visitNode(W.offset)}visitOnConflict(W){if(this.append("on conflict"),W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");else if(W.constraint)this.append(" on constraint "),this.visitNode(W.constraint);else if(W.indexExpression)this.append(" ("),this.visitNode(W.indexExpression),this.append(")");if(W.indexWhere)this.append(" "),this.visitNode(W.indexWhere);if(W.doNothing===!0)this.append(" do nothing");else if(W.updates){if(this.append(" do update set "),this.compileList(W.updates),W.updateWhere)this.append(" "),this.visitNode(W.updateWhere)}}visitOnDuplicateKey(W){this.append("on duplicate key update "),this.compileList(W.updates)}visitCreateIndex(W){if(this.append("create "),W.unique)this.append("unique ");if(this.append("index "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.name),W.table)this.append(" on "),this.visitNode(W.table);if(W.using)this.append(" using "),this.visitNode(W.using);if(W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.nullsNotDistinct)this.append(" nulls not distinct");if(W.where)this.append(" "),this.visitNode(W.where)}visitDropIndex(W){if(this.append("drop index "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.table)this.append(" on "),this.visitNode(W.table);if(W.cascade)this.append(" cascade")}visitCreateSchema(W){if(this.append("create schema "),W.ifNotExists)this.append("if not exists ");this.visitNode(W.schema)}visitDropSchema(W){if(this.append("drop schema "),W.ifExists)this.append("if exists ");if(this.visitNode(W.schema),W.cascade)this.append(" cascade")}visitPrimaryKeyConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");this.append("primary key ("),this.compileList(W.columns),this.append(")"),this.buildDeferrable(W)}buildDeferrable(W){if(W.deferrable!==void 0)if(W.deferrable)this.append(" deferrable");else this.append(" not deferrable");if(W.initiallyDeferred!==void 0)if(W.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");if(this.append("unique"),W.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList(W.columns),this.append(")"),this.buildDeferrable(W)}visitCheckConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");this.append("check ("),this.visitNode(W.expression),this.append(")")}visitForeignKeyConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");if(this.append("foreign key ("),this.compileList(W.columns),this.append(") "),this.visitNode(W.references),W.onDelete)this.append(" on delete "),this.append(W.onDelete);if(W.onUpdate)this.append(" on update "),this.append(W.onUpdate);this.buildDeferrable(W)}visitList(W){this.compileList(W.items)}visitWith(W){if(this.append("with "),W.recursive)this.append("recursive ");this.compileList(W.expressions)}visitCommonTableExpression(W){if(this.visitNode(W.name),this.append(" as "),Y0(W.materialized)){if(!W.materialized)this.append("not ");this.append("materialized ")}this.visitNode(W.expression)}visitCommonTableExpressionName(W){if(this.visitNode(W.table),W.columns)this.append("("),this.compileList(W.columns),this.append(")")}visitAlterTable(W){if(this.append("alter table "),this.visitNode(W.table),this.append(" "),W.renameTo)this.append("rename to "),this.visitNode(W.renameTo);if(W.setSchema)this.append("set schema "),this.visitNode(W.setSchema);if(W.addConstraint)this.visitNode(W.addConstraint);if(W.dropConstraint)this.visitNode(W.dropConstraint);if(W.renameConstraint)this.visitNode(W.renameConstraint);if(W.columnAlterations)this.compileColumnAlterations(W.columnAlterations);if(W.addIndex)this.visitNode(W.addIndex);if(W.dropIndex)this.visitNode(W.dropIndex)}visitAddColumn(W){this.append("add column "),this.visitNode(W.column)}visitRenameColumn(W){this.append("rename column "),this.visitNode(W.column),this.append(" to "),this.visitNode(W.renameTo)}visitDropColumn(W){this.append("drop column "),this.visitNode(W.column)}visitAlterColumn(W){if(this.append("alter column "),this.visitNode(W.column),this.append(" "),W.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode(W.dataType),W.dataTypeExpression)this.append("using "),this.visitNode(W.dataTypeExpression)}if(W.setDefault)this.append("set default "),this.visitNode(W.setDefault);if(W.dropDefault)this.append("drop default");if(W.setNotNull)this.append("set not null");if(W.dropNotNull)this.append("drop not null")}visitModifyColumn(W){this.append("modify column "),this.visitNode(W.column)}visitAddConstraint(W){this.append("add "),this.visitNode(W.constraint)}visitDropConstraint(W){if(this.append("drop constraint "),W.ifExists)this.append("if exists ");if(this.visitNode(W.constraintName),W.modifier==="cascade")this.append(" cascade");else if(W.modifier==="restrict")this.append(" restrict")}visitRenameConstraint(W){this.append("rename constraint "),this.visitNode(W.oldName),this.append(" to "),this.visitNode(W.newName)}visitSetOperation(W){if(this.append(W.operator),this.append(" "),W.all)this.append("all ");this.visitNode(W.expression)}visitCreateView(W){if(this.append("create "),W.orReplace)this.append("or replace ");if(W.materialized)this.append("materialized ");if(W.temporary)this.append("temporary ");if(this.append("view "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.name),this.append(" "),W.columns)this.append("("),this.compileList(W.columns),this.append(") ");if(W.as)this.append("as "),this.visitNode(W.as)}visitRefreshMaterializedView(W){if(this.append("refresh materialized view "),W.concurrently)this.append("concurrently ");if(this.visitNode(W.name),W.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView(W){if(this.append("drop "),W.materialized)this.append("materialized ");if(this.append("view "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.cascade)this.append(" cascade")}visitGenerated(W){if(this.append("generated "),W.always)this.append("always ");if(W.byDefault)this.append("by default ");if(this.append("as "),W.identity)this.append("identity");if(W.expression)this.append("("),this.visitNode(W.expression),this.append(")");if(W.stored)this.append(" stored")}visitDefaultValue(W){this.append("default "),this.visitNode(W.defaultValue)}visitSelectModifier(W){if(W.rawModifier)this.visitNode(W.rawModifier);else this.append(Tk[W.modifier]);if(W.of)this.append(" of "),this.compileList(W.of,", ")}visitCreateType(W){if(this.append("create type "),this.visitNode(W.name),W.enum)this.append(" as enum "),this.visitNode(W.enum)}visitDropType(W){if(this.append("drop type "),W.ifExists)this.append("if exists ");this.visitNode(W.name)}visitExplain(W){if(this.append("explain"),W.options||W.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),W.options){if(this.visitNode(W.options),W.format)this.append(this.getExplainOptionsDelimiter())}if(W.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(W.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue(W){this.append("default")}visitAggregateFunction(W){if(this.append(W.func),this.append("("),W.distinct)this.append("distinct ");if(this.compileList(W.aggregated),W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(this.append(")"),W.withinGroup)this.append(" within group ("),this.visitNode(W.withinGroup),this.append(")");if(W.filter)this.append(" filter("),this.visitNode(W.filter),this.append(")");if(W.over)this.append(" "),this.visitNode(W.over)}visitOver(W){if(this.append("over("),W.partitionBy){if(this.visitNode(W.partitionBy),W.orderBy)this.append(" ")}if(W.orderBy)this.visitNode(W.orderBy);this.append(")")}visitPartitionBy(W){this.append("partition by "),this.compileList(W.items)}visitPartitionByItem(W){this.visitNode(W.partitionBy)}visitBinaryOperation(W){this.visitNode(W.leftOperand),this.append(" "),this.visitNode(W.operator),this.append(" "),this.visitNode(W.rightOperand)}visitUnaryOperation(W){if(this.visitNode(W.operator),!this.isMinusOperator(W.operator))this.append(" ");this.visitNode(W.operand)}isMinusOperator(W){return dW.is(W)&&W.operator==="-"}visitUsing(W){this.append("using "),this.compileList(W.tables)}visitFunction(W){this.append(W.func),this.append("("),this.compileList(W.arguments),this.append(")")}visitCase(W){if(this.append("case"),W.value)this.append(" "),this.visitNode(W.value);if(W.when)this.append(" "),this.compileList(W.when," ");if(W.else)this.append(" else "),this.visitNode(W.else);if(this.append(" end"),W.isStatement)this.append(" case")}visitWhen(W){if(this.append("when "),this.visitNode(W.condition),W.result)this.append(" then "),this.visitNode(W.result)}visitJSONReference(W){this.visitNode(W.reference),this.visitNode(W.traversal)}visitJSONPath(W){if(W.inOperator)this.visitNode(W.inOperator);this.append("'$");for(let $ of W.pathLegs)this.visitNode($);this.append("'")}visitJSONPathLeg(W){let $=W.type==="ArrayLocation";if(this.append($?"[":"."),this.append(String(W.value)),$)this.append("]")}visitJSONOperatorChain(W){for(let $=0,k=W.values.length;$<k;$++){if($===k-1)this.visitNode(W.operator);else this.append("->");this.visitNode(W.values[$])}}visitMergeQuery(W){if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("merge "),W.top)this.visitNode(W.top),this.append(" ");if(this.append("into "),this.visitNode(W.into),W.using)this.append(" "),this.visitNode(W.using);if(W.whens)this.append(" "),this.compileList(W.whens," ");if(W.returning)this.append(" "),this.visitNode(W.returning);if(W.output)this.append(" "),this.visitNode(W.output);if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitMatched(W){if(W.not)this.append("not ");if(this.append("matched"),W.bySource)this.append(" by source")}visitAddIndex(W){if(this.append("add "),W.unique)this.append("unique ");if(this.append("index "),this.visitNode(W.name),W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.using)this.append(" using "),this.visitNode(W.using)}visitCast(W){this.append("cast("),this.visitNode(W.expression),this.append(" as "),this.visitNode(W.dataType),this.append(")")}visitFetch(W){this.append("fetch next "),this.visitNode(W.rowCount),this.append(` rows ${W.modifier}`)}visitOutput(W){this.append("output "),this.compileList(W.selections)}visitTop(W){if(this.append(`top(${W.expression})`),W.modifiers)this.append(` ${W.modifiers}`)}visitOrAction(W){this.append(W.action)}visitCollate(W){this.append("collate "),this.visitNode(W.collation)}append(W){this.#W+=W}appendValue(W){this.addParameter(W),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(W){let $=this.getLeftIdentifierWrapper(),k=this.getRightIdentifierWrapper(),J="";for(let Z of W)if(J+=Z,Z===$)J+=$;else if(Z===k)J+=k;return J}sanitizeStringLiteral(W){return W.replace(fk,"''")}addParameter(W){this.#$.push(W)}appendImmediateValue(W){if(_W(W))this.appendStringLiteral(W);else if(u1(W)||Y0(W)||P0(W))this.append(W.toString());else if(h0(W))this.append("null");else if(N9(W))this.appendImmediateValue(W.toISOString());else throw Error(`invalid immediate value ${W}`)}appendStringLiteral(W){this.append("'"),this.append(this.sanitizeStringLiteral(W)),this.append("'")}sortSelectModifiers(W){return W.sort(($,k)=>$.modifier&&k.modifier?x5[$.modifier]-x5[k.modifier]:1),H(W)}compileColumnAlterations(W){this.compileList(W)}announcesNewColumnDataType(){return!0}}var Tk=H({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),x5=H({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),Ek=H({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"});var v8=H({raw(W,$=[]){return H({sql:W,query:YW.createWithSql(W),parameters:H($),queryId:e()})}});class b6{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}class B6{transformQuery(W){return W.node}async transformResult(W){return W.result}}var y6="kysely_migration",F4="kysely_migration_lock",vk=!1,I6="migration_lock",x_=H({__noMigrations__:!0});class g6{#W;constructor(W){this.#W=H(W)}async getMigrations(){let $=await this.#M(this.#J)?await this.#W.db.withPlugin(this.#X).selectFrom(this.#J).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#R()).map(({name:J,...Z})=>{let X=$.find((G)=>G.name===J);return{name:J,migration:Z,executedAt:X?new Date(X.timestamp):void 0}})}async migrateToLatest(){return this.#$(()=>({direction:"Up",step:1/0}))}async migrateTo(W){return this.#$(({migrations:$,executedMigrations:k,pendingMigrations:J})=>{if(TW(W)&&W.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!$.find((G)=>G.name===W))throw Error(`migration "${W}" doesn't exist`);let Z=k.indexOf(W),X=J.findIndex((G)=>G.name===W);if(Z!==-1)return{direction:"Down",step:k.length-Z-1};else if(X!==-1)return{direction:"Up",step:X+1};else throw Error(`migration "${W}" isn't executed or pending`)})}async migrateUp(){return this.#$(()=>({direction:"Up",step:1}))}async migrateDown(){return this.#$(()=>({direction:"Down",step:1}))}async#$(W){try{return await this.#Y(),await this.#H(),await this.#G(),await this.#L(),await this.#F(W)}catch($){if($ instanceof R4)return $.resultSet;return{error:$}}}get#k(){return this.#W.migrationTableSchema}get#J(){return this.#W.migrationTableName??y6}get#Z(){return this.#W.migrationLockTableName??F4}get#z(){return this.#W.allowUnorderedMigrations??vk}get#X(){if(this.#k)return new W1(this.#k);return new B6}async#Y(){if(!this.#k)return;if(await this.#U())return;try{await this.#K(this.#W.db.schema.createSchema(this.#k))}catch($){if(!await this.#U())throw $}}async#H(){if(await this.#M(this.#J))return;try{await this.#K(this.#W.db.schema.withPlugin(this.#X).createTable(this.#J).addColumn("name","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("timestamp","varchar(255)",($)=>$.notNull()))}catch($){if(!await this.#M(this.#J))throw $}}async#G(){if(await this.#M(this.#Z))return;try{await this.#K(this.#W.db.schema.withPlugin(this.#X).createTable(this.#Z).addColumn("id","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("is_locked","integer",($)=>$.notNull().defaultTo(0)))}catch($){if(!await this.#M(this.#Z))throw $}}async#L(){if(await this.#V())return;try{await this.#W.db.withPlugin(this.#X).insertInto(this.#Z).values({id:I6,is_locked:0}).execute()}catch($){if(!await this.#V())throw $}}async#U(){return(await this.#W.db.introspection.getSchemas()).some(($)=>$.name===this.#k)}async#M(W){let $=this.#k;return(await this.#W.db.introspection.getTables({withInternalKyselyTables:!0})).some((J)=>J.name===W&&(!$||J.schema===$))}async#V(){return!!await this.#W.db.withPlugin(this.#X).selectFrom(this.#Z).where("id","=",I6).select("id").executeTakeFirst()}async#F(W){let $=this.#W.db.getExecutor().adapter,k=H({lockTable:this.#W.migrationLockTableName??F4,lockRowId:I6,lockTableSchema:this.#W.migrationTableSchema}),J=async(Z)=>{try{await $.acquireMigrationLock(Z,k);let X=await this.#w(Z);if(X.migrations.length===0)return{results:[]};let{direction:G,step:z}=W(X);if(z<=0)return{results:[]};if(G==="Down")return await this.#f(Z,X,z);else if(G==="Up")return await this.#T(Z,X,z);return{results:[]}}finally{await $.releaseMigrationLock(Z,k)}};if($.supportsTransactionalDdl&&!this.#W.disableTransactions)return this.#W.db.transaction().execute(J);else return this.#W.db.connection().execute(J)}async#w(W){let $=await this.#R(),k=await this.#h(W);if(this.#P($,k),!this.#z)this.#D($,k);let J=this.#_($,k);return H({migrations:$,executedMigrations:k,lastMigration:O9(k),pendingMigrations:J})}#_(W,$){return W.filter((k)=>{return!$.includes(k.name)})}async#R(){let W=await this.#W.provider.getMigrations();return Object.keys(W).sort().map(($)=>({...W[$],name:$}))}async#h(W){let $=await W.withPlugin(this.#X).selectFrom(this.#J).select(["name","timestamp"]).$narrowType().execute(),k=this.#W.nameComparator||((J,Z)=>J.localeCompare(Z));return $.sort((J,Z)=>{if(J.timestamp===Z.timestamp)return k(J.name,Z.name);return new Date(J.timestamp).getTime()-new Date(Z.timestamp).getTime()}).map((J)=>J.name)}#P(W,$){for(let k of $)if(!W.some((J)=>J.name===k))throw Error(`corrupted migrations: previously executed migration ${k} is missing`)}#D(W,$){for(let k=0;k<$.length;++k)if(W[k].name!==$[k])throw Error(`corrupted migrations: expected previously executed migration ${$[k]} to be at index ${k} but ${W[k].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#f(W,$,k){let J=$.executedMigrations.slice().reverse().slice(0,k).map((X)=>{return $.migrations.find((G)=>G.name===X)}),Z=J.map((X)=>{return{migrationName:X.name,direction:"Down",status:"NotExecuted"}});for(let X=0;X<Z.length;++X){let G=J[X];try{if(G.down)await G.down(W),await W.withPlugin(this.#X).deleteFrom(this.#J).where("name","=",G.name).execute(),Z[X]={migrationName:G.name,direction:"Down",status:"Success"}}catch(z){throw Z[X]={migrationName:G.name,direction:"Down",status:"Error"},new R4({error:z,results:Z})}}return{results:Z}}async#T(W,$,k){let Z=$.pendingMigrations.slice(0,k).map((X)=>{return{migrationName:X.name,direction:"Up",status:"NotExecuted"}});for(let X=0;X<Z.length;X++){let G=$.pendingMigrations[X];try{await G.up(W),await W.withPlugin(this.#X).insertInto(this.#J).values({name:G.name,timestamp:new Date().toISOString()}).execute(),Z[X]={migrationName:G.name,direction:"Up",status:"Success"}}catch(z){throw Z[X]={migrationName:G.name,direction:"Up",status:"Error"},new R4({error:z,results:Z})}}return{results:Z}}async#K(W){if(this.#W.db.getExecutor().adapter.supportsCreateIfNotExists)W=W.ifNotExists();await W.execute()}}class R4 extends Error{#W;constructor(W){super();this.#W=W}get resultSet(){return this.#W}}var Sk=/"/g;class S8 extends q6{sanitizeIdentifier(W){return W.replace(Sk,'""')}}class N8{#W;constructor(W){this.#W=W}async getSchemas(){return(await this.#W.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map(($)=>({name:$.nspname}))}async getTables(W={withInternalKyselyTables:!1}){let $=this.#W.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",k0`col_description(a.attrelid, a.attnum)`.as("column_description"),k0`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(k0`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!W.withInternalKyselyTables)$=$.where("c.relname","!=",y6).where("c.relname","!=",F4);let k=await $.execute();return this.#$(k)}async getMetadata(W){return{tables:await this.getTables(W)}}#$(W){return W.reduce(($,k)=>{let J=$.find((Z)=>Z.name===k.table&&Z.schema===k.schema);if(!J)J=H({name:k.table,isView:k.table_type==="v",schema:k.schema,columns:[]}),$.push(J);return J.columns.push(H({name:k.column,dataType:k.type,dataTypeSchema:k.type_schema,isNullable:!k.not_null,isAutoIncrementing:k.auto_incrementing!==null,hasDefaultValue:k.has_default,comment:k.column_description??void 0})),$},[])}}var Nk=BigInt("3853314791062309107");class O8 extends b6{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(W,$){await k0`select pg_advisory_xact_lock(${k0.lit(Nk)})`.execute(W)}async releaseMigrationLock(W,$){}}class m6{#W;constructor(W){this.#W=W}async getMigrations(){let W={},$=await this.#W.fs.readdir(this.#W.migrationFolder);for(let k of $)if(k.endsWith(".js")||k.endsWith(".ts")&&!k.endsWith(".d.ts")||k.endsWith(".mjs")||k.endsWith(".mts")&&!k.endsWith(".d.mts")){let J=await import(this.#W.path.join(this.#W.migrationFolder,k)),Z=k.substring(0,k.lastIndexOf("."));if(q5(J?.default))W[Z]=J.default;else if(q5(J))W[Z]=J}return W}}function q5(W){return TW(W)&&hW(W.up)}var{create:Ok,defineProperty:d0,getOwnPropertyDescriptor:Ak,getOwnPropertyNames:jk,getPrototypeOf:Ck}=Object,Qk=Object.prototype.hasOwnProperty,xk=(W,$,k)=>($ in W)?d0(W,$,{enumerable:!0,configurable:!0,writable:!0,value:k}):W[$]=k,U=(W,$)=>d0(W,"name",{value:$,configurable:!0}),tW=(W,$)=>()=>(W&&($=W(W=0)),$),r=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports),_1=(W,$)=>{for(var k in $)d0(W,k,{get:$[k],enumerable:!0})},c5=(W,$,k,J)=>{if($&&typeof $=="object"||typeof $=="function")for(let Z of jk($))!Qk.call(W,Z)&&Z!==k&&d0(W,Z,{get:()=>$[Z],enumerable:!(J=Ak($,Z))||J.enumerable});return W},R0=(W,$,k)=>(k=W!=null?Ok(Ck(W)):{},c5($||!W||!W.__esModule?d0(k,"default",{value:W,enumerable:!0}):k,W)),QW=(W)=>c5(d0({},"__esModule",{value:!0}),W),s=(W,$,k)=>xk(W,typeof $!="symbol"?$+"":$,k),qk=r((W)=>{l(),W.byteLength=V,W.toByteArray=R,W.fromByteArray=D;var $=[],k=[],J=typeof Uint8Array<"u"?Uint8Array:Array,Z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(X=0,G=Z.length;X<G;++X)$[X]=Z[X],k[Z.charCodeAt(X)]=X;var X,G;k[45]=62,k[95]=63;function z(F){var M=F.length;if(M%4>0)throw Error("Invalid string. Length must be a multiple of 4");var P=F.indexOf("=");P===-1&&(P=M);var f=P===M?0:4-P%4;return[P,f]}U(z,"getLens");function V(F){var M=z(F),P=M[0],f=M[1];return(P+f)*3/4-f}U(V,"byteLength");function w(F,M,P){return(M+P)*3/4-P}U(w,"_byteLength");function R(F){var M,P=z(F),f=P[0],T=P[1],S=new J(w(F,f,T)),q=0,Q=T>0?f-4:f,E;for(E=0;E<Q;E+=4)M=k[F.charCodeAt(E)]<<18|k[F.charCodeAt(E+1)]<<12|k[F.charCodeAt(E+2)]<<6|k[F.charCodeAt(E+3)],S[q++]=M>>16&255,S[q++]=M>>8&255,S[q++]=M&255;return T===2&&(M=k[F.charCodeAt(E)]<<2|k[F.charCodeAt(E+1)]>>4,S[q++]=M&255),T===1&&(M=k[F.charCodeAt(E)]<<10|k[F.charCodeAt(E+1)]<<4|k[F.charCodeAt(E+2)]>>2,S[q++]=M>>8&255,S[q++]=M&255),S}U(R,"toByteArray");function h(F){return $[F>>18&63]+$[F>>12&63]+$[F>>6&63]+$[F&63]}U(h,"tripletToBase64");function _(F,M,P){for(var f,T=[],S=M;S<P;S+=3)f=(F[S]<<16&16711680)+(F[S+1]<<8&65280)+(F[S+2]&255),T.push(h(f));return T.join("")}U(_,"encodeChunk");function D(F){for(var M,P=F.length,f=P%3,T=[],S=16383,q=0,Q=P-f;q<Q;q+=S)T.push(_(F,q,q+S>Q?Q:q+S));return f===1?(M=F[P-1],T.push($[M>>2]+$[M<<4&63]+"==")):f===2&&(M=(F[P-2]<<8)+F[P-1],T.push($[M>>10]+$[M>>4&63]+$[M<<2&63]+"=")),T.join("")}U(D,"fromByteArray")}),bk=r((W)=>{l(),W.read=function($,k,J,Z,X){var G,z,V=X*8-Z-1,w=(1<<V)-1,R=w>>1,h=-7,_=J?X-1:0,D=J?-1:1,F=$[k+_];for(_+=D,G=F&(1<<-h)-1,F>>=-h,h+=V;h>0;G=G*256+$[k+_],_+=D,h-=8);for(z=G&(1<<-h)-1,G>>=-h,h+=Z;h>0;z=z*256+$[k+_],_+=D,h-=8);if(G===0)G=1-R;else{if(G===w)return z?NaN:(F?-1:1)*(1/0);z=z+Math.pow(2,Z),G=G-R}return(F?-1:1)*z*Math.pow(2,G-Z)},W.write=function($,k,J,Z,X,G){var z,V,w,R=G*8-X-1,h=(1<<R)-1,_=h>>1,D=X===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=Z?0:G-1,M=Z?1:-1,P=k<0||k===0&&1/k<0?1:0;for(k=Math.abs(k),isNaN(k)||k===1/0?(V=isNaN(k)?1:0,z=h):(z=Math.floor(Math.log(k)/Math.LN2),k*(w=Math.pow(2,-z))<1&&(z--,w*=2),z+_>=1?k+=D/w:k+=D*Math.pow(2,1-_),k*w>=2&&(z++,w/=2),z+_>=h?(V=0,z=h):z+_>=1?(V=(k*w-1)*Math.pow(2,X),z=z+_):(V=k*Math.pow(2,_-1)*Math.pow(2,X),z=0));X>=8;$[J+F]=V&255,F+=M,V/=256,X-=8);for(z=z<<X|V,R+=X;R>0;$[J+F]=z&255,F+=M,z/=256,R-=8);$[J+F-M]|=P*128}}),Bk=r((W)=>{l();var $=qk(),k=bk(),J=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;W.Buffer=z,W.SlowBuffer=T,W.INSPECT_MAX_BYTES=50;var Z=2147483647;W.kMaxLength=Z,z.TYPED_ARRAY_SUPPORT=X(),!z.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function X(){try{let Y=new Uint8Array(1),L={foo:U(function(){return 42},"foo")};return Object.setPrototypeOf(L,Uint8Array.prototype),Object.setPrototypeOf(Y,L),Y.foo()===42}catch{return!1}}U(X,"typedArraySupport"),Object.defineProperty(z.prototype,"parent",{enumerable:!0,get:U(function(){if(z.isBuffer(this))return this.buffer},"get")}),Object.defineProperty(z.prototype,"offset",{enumerable:!0,get:U(function(){if(z.isBuffer(this))return this.byteOffset},"get")});function G(Y){if(Y>Z)throw RangeError('The value "'+Y+'" is invalid for option "size"');let L=new Uint8Array(Y);return Object.setPrototypeOf(L,z.prototype),L}U(G,"createBuffer");function z(Y,L,K){if(typeof Y=="number"){if(typeof L=="string")throw TypeError('The "string" argument must be of type string. Received type number');return h(Y)}return V(Y,L,K)}U(z,"Buffer"),z.poolSize=8192;function V(Y,L,K){if(typeof Y=="string")return _(Y,L);if(ArrayBuffer.isView(Y))return F(Y);if(Y==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Y);if(Z1(Y,ArrayBuffer)||Y&&Z1(Y.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Z1(Y,SharedArrayBuffer)||Y&&Z1(Y.buffer,SharedArrayBuffer)))return M(Y,L,K);if(typeof Y=="number")throw TypeError('The "value" argument must not be of type number. Received type number');let v=Y.valueOf&&Y.valueOf();if(v!=null&&v!==Y)return z.from(v,L,K);let O=P(Y);if(O)return O;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof Y[Symbol.toPrimitive]=="function")return z.from(Y[Symbol.toPrimitive]("string"),L,K);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Y)}U(V,"from"),z.from=function(Y,L,K){return V(Y,L,K)},Object.setPrototypeOf(z.prototype,Uint8Array.prototype),Object.setPrototypeOf(z,Uint8Array);function w(Y){if(typeof Y!="number")throw TypeError('"size" argument must be of type number');if(Y<0)throw RangeError('The value "'+Y+'" is invalid for option "size"')}U(w,"assertSize");function R(Y,L,K){return w(Y),Y<=0?G(Y):L!==void 0?typeof K=="string"?G(Y).fill(L,K):G(Y).fill(L):G(Y)}U(R,"alloc"),z.alloc=function(Y,L,K){return R(Y,L,K)};function h(Y){return w(Y),G(Y<0?0:f(Y)|0)}U(h,"allocUnsafe"),z.allocUnsafe=function(Y){return h(Y)},z.allocUnsafeSlow=function(Y){return h(Y)};function _(Y,L){if((typeof L!="string"||L==="")&&(L="utf8"),!z.isEncoding(L))throw TypeError("Unknown encoding: "+L);let K=S(Y,L)|0,v=G(K),O=v.write(Y,L);return O!==K&&(v=v.slice(0,O)),v}U(_,"fromString");function D(Y){let L=Y.length<0?0:f(Y.length)|0,K=G(L);for(let v=0;v<L;v+=1)K[v]=Y[v]&255;return K}U(D,"fromArrayLike");function F(Y){if(Z1(Y,Uint8Array)){let L=new Uint8Array(Y);return M(L.buffer,L.byteOffset,L.byteLength)}return D(Y)}U(F,"fromArrayView");function M(Y,L,K){if(L<0||Y.byteLength<L)throw RangeError('"offset" is outside of buffer bounds');if(Y.byteLength<L+(K||0))throw RangeError('"length" is outside of buffer bounds');let v;return L===void 0&&K===void 0?v=new Uint8Array(Y):K===void 0?v=new Uint8Array(Y,L):v=new Uint8Array(Y,L,K),Object.setPrototypeOf(v,z.prototype),v}U(M,"fromArrayBuffer");function P(Y){if(z.isBuffer(Y)){let L=f(Y.length)|0,K=G(L);return K.length===0||Y.copy(K,0,0,L),K}if(Y.length!==void 0)return typeof Y.length!="number"||I8(Y.length)?G(0):D(Y);if(Y.type==="Buffer"&&Array.isArray(Y.data))return D(Y.data)}U(P,"fromObject");function f(Y){if(Y>=Z)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Z.toString(16)+" bytes");return Y|0}U(f,"checked");function T(Y){return+Y!=Y&&(Y=0),z.alloc(+Y)}U(T,"SlowBuffer"),z.isBuffer=U(function(Y){return Y!=null&&Y._isBuffer===!0&&Y!==z.prototype},"isBuffer"),z.compare=U(function(Y,L){if(Z1(Y,Uint8Array)&&(Y=z.from(Y,Y.offset,Y.byteLength)),Z1(L,Uint8Array)&&(L=z.from(L,L.offset,L.byteLength)),!z.isBuffer(Y)||!z.isBuffer(L))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(Y===L)return 0;let K=Y.length,v=L.length;for(let O=0,x=Math.min(K,v);O<x;++O)if(Y[O]!==L[O]){K=Y[O],v=L[O];break}return K<v?-1:v<K?1:0},"compare"),z.isEncoding=U(function(Y){switch(String(Y).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},"isEncoding"),z.concat=U(function(Y,L){if(!Array.isArray(Y))throw TypeError('"list" argument must be an Array of Buffers');if(Y.length===0)return z.alloc(0);let K;if(L===void 0)for(L=0,K=0;K<Y.length;++K)L+=Y[K].length;let v=z.allocUnsafe(L),O=0;for(K=0;K<Y.length;++K){let x=Y[K];if(Z1(x,Uint8Array))O+x.length>v.length?(z.isBuffer(x)||(x=z.from(x)),x.copy(v,O)):Uint8Array.prototype.set.call(v,x,O);else if(z.isBuffer(x))x.copy(v,O);else throw TypeError('"list" argument must be an Array of Buffers');O+=x.length}return v},"concat");function S(Y,L){if(z.isBuffer(Y))return Y.length;if(ArrayBuffer.isView(Y)||Z1(Y,ArrayBuffer))return Y.byteLength;if(typeof Y!="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof Y);let K=Y.length,v=arguments.length>2&&arguments[2]===!0;if(!v&&K===0)return 0;let O=!1;for(;;)switch(L){case"ascii":case"latin1":case"binary":return K;case"utf8":case"utf-8":return B8(Y).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K*2;case"hex":return K>>>1;case"base64":return B4(Y).length;default:if(O)return v?-1:B8(Y).length;L=(""+L).toLowerCase(),O=!0}}U(S,"byteLength"),z.byteLength=S;function q(Y,L,K){let v=!1;if((L===void 0||L<0)&&(L=0),L>this.length||((K===void 0||K>this.length)&&(K=this.length),K<=0)||(K>>>=0,L>>>=0,K<=L))return"";for(Y||(Y="utf8");;)switch(Y){case"hex":return n(this,L,K);case"utf8":case"utf-8":return B(this,L,K);case"ascii":return a(this,L,K);case"latin1":case"binary":return JW(this,L,K);case"base64":return c(this,L,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return sW(this,L,K);default:if(v)throw TypeError("Unknown encoding: "+Y);Y=(Y+"").toLowerCase(),v=!0}}U(q,"slowToString"),z.prototype._isBuffer=!0;function Q(Y,L,K){let v=Y[L];Y[L]=Y[K],Y[K]=v}U(Q,"swap"),z.prototype.swap16=U(function(){let Y=this.length;if(Y%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let L=0;L<Y;L+=2)Q(this,L,L+1);return this},"swap16"),z.prototype.swap32=U(function(){let Y=this.length;if(Y%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let L=0;L<Y;L+=4)Q(this,L,L+3),Q(this,L+1,L+2);return this},"swap32"),z.prototype.swap64=U(function(){let Y=this.length;if(Y%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(let L=0;L<Y;L+=8)Q(this,L,L+7),Q(this,L+1,L+6),Q(this,L+2,L+5),Q(this,L+3,L+4);return this},"swap64"),z.prototype.toString=U(function(){let Y=this.length;return Y===0?"":arguments.length===0?B(this,0,Y):q.apply(this,arguments)},"toString"),z.prototype.toLocaleString=z.prototype.toString,z.prototype.equals=U(function(Y){if(!z.isBuffer(Y))throw TypeError("Argument must be a Buffer");return this===Y?!0:z.compare(this,Y)===0},"equals"),z.prototype.inspect=U(function(){let Y="",L=W.INSPECT_MAX_BYTES;return Y=this.toString("hex",0,L).replace(/(.{2})/g,"$1 ").trim(),this.length>L&&(Y+=" ... "),"<Buffer "+Y+">"},"inspect"),J&&(z.prototype[J]=z.prototype.inspect),z.prototype.compare=U(function(Y,L,K,v,O){if(Z1(Y,Uint8Array)&&(Y=z.from(Y,Y.offset,Y.byteLength)),!z.isBuffer(Y))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof Y);if(L===void 0&&(L=0),K===void 0&&(K=Y?Y.length:0),v===void 0&&(v=0),O===void 0&&(O=this.length),L<0||K>Y.length||v<0||O>this.length)throw RangeError("out of range index");if(v>=O&&L>=K)return 0;if(v>=O)return-1;if(L>=K)return 1;if(L>>>=0,K>>>=0,v>>>=0,O>>>=0,this===Y)return 0;let x=O-v,y=K-L,FW=Math.min(x,y),OW=this.slice(v,O),DW=Y.slice(L,K);for(let wW=0;wW<FW;++wW)if(OW[wW]!==DW[wW]){x=OW[wW],y=DW[wW];break}return x<y?-1:y<x?1:0},"compare");function E(Y,L,K,v,O){if(Y.length===0)return-1;if(typeof K=="string"?(v=K,K=0):K>2147483647?K=2147483647:K<-2147483648&&(K=-2147483648),K=+K,I8(K)&&(K=O?0:Y.length-1),K<0&&(K=Y.length+K),K>=Y.length){if(O)return-1;K=Y.length-1}else if(K<0)if(O)K=0;else return-1;if(typeof L=="string"&&(L=z.from(L,v)),z.isBuffer(L))return L.length===0?-1:j(Y,L,K,v,O);if(typeof L=="number")return L=L&255,typeof Uint8Array.prototype.indexOf=="function"?O?Uint8Array.prototype.indexOf.call(Y,L,K):Uint8Array.prototype.lastIndexOf.call(Y,L,K):j(Y,[L],K,v,O);throw TypeError("val must be string, number or Buffer")}U(E,"bidirectionalIndexOf");function j(Y,L,K,v,O){let x=1,y=Y.length,FW=L.length;if(v!==void 0&&(v=String(v).toLowerCase(),v==="ucs2"||v==="ucs-2"||v==="utf16le"||v==="utf-16le")){if(Y.length<2||L.length<2)return-1;x=2,y/=2,FW/=2,K/=2}function OW(wW,EW){return x===1?wW[EW]:wW.readUInt16BE(EW*x)}U(OW,"read");let DW;if(O){let wW=-1;for(DW=K;DW<y;DW++)if(OW(Y,DW)===OW(L,wW===-1?0:DW-wW)){if(wW===-1&&(wW=DW),DW-wW+1===FW)return wW*x}else wW!==-1&&(DW-=DW-wW),wW=-1}else for(K+FW>y&&(K=y-FW),DW=K;DW>=0;DW--){let wW=!0;for(let EW=0;EW<FW;EW++)if(OW(Y,DW+EW)!==OW(L,EW)){wW=!1;break}if(wW)return DW}return-1}U(j,"arrayIndexOf"),z.prototype.includes=U(function(Y,L,K){return this.indexOf(Y,L,K)!==-1},"includes"),z.prototype.indexOf=U(function(Y,L,K){return E(this,Y,L,K,!0)},"indexOf"),z.prototype.lastIndexOf=U(function(Y,L,K){return E(this,Y,L,K,!1)},"lastIndexOf");function A(Y,L,K,v){K=Number(K)||0;let O=Y.length-K;v?(v=Number(v),v>O&&(v=O)):v=O;let x=L.length;v>x/2&&(v=x/2);let y;for(y=0;y<v;++y){let FW=parseInt(L.substr(y*2,2),16);if(I8(FW))return y;Y[K+y]=FW}return y}U(A,"hexWrite");function N(Y,L,K,v){return W8(B8(L,Y.length-K),Y,K,v)}U(N,"utf8Write");function b(Y,L,K,v){return W8(X9(L),Y,K,v)}U(b,"asciiWrite");function C(Y,L,K,v){return W8(B4(L),Y,K,v)}U(C,"base64Write");function u(Y,L,K,v){return W8(Y9(L,Y.length-K),Y,K,v)}U(u,"ucs2Write"),z.prototype.write=U(function(Y,L,K,v){if(L===void 0)v="utf8",K=this.length,L=0;else if(K===void 0&&typeof L=="string")v=L,K=this.length,L=0;else if(isFinite(L))L=L>>>0,isFinite(K)?(K=K>>>0,v===void 0&&(v="utf8")):(v=K,K=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let O=this.length-L;if((K===void 0||K>O)&&(K=O),Y.length>0&&(K<0||L<0)||L>this.length)throw RangeError("Attempt to write outside buffer bounds");v||(v="utf8");let x=!1;for(;;)switch(v){case"hex":return A(this,Y,L,K);case"utf8":case"utf-8":return N(this,Y,L,K);case"ascii":case"latin1":case"binary":return b(this,Y,L,K);case"base64":return C(this,Y,L,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return u(this,Y,L,K);default:if(x)throw TypeError("Unknown encoding: "+v);v=(""+v).toLowerCase(),x=!0}},"write"),z.prototype.toJSON=U(function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},"toJSON");function c(Y,L,K){return L===0&&K===Y.length?$.fromByteArray(Y):$.fromByteArray(Y.slice(L,K))}U(c,"base64Slice");function B(Y,L,K){K=Math.min(Y.length,K);let v=[],O=L;for(;O<K;){let x=Y[O],y=null,FW=x>239?4:x>223?3:x>191?2:1;if(O+FW<=K){let OW,DW,wW,EW;switch(FW){case 1:x<128&&(y=x);break;case 2:OW=Y[O+1],(OW&192)===128&&(EW=(x&31)<<6|OW&63,EW>127&&(y=EW));break;case 3:OW=Y[O+1],DW=Y[O+2],(OW&192)===128&&(DW&192)===128&&(EW=(x&15)<<12|(OW&63)<<6|DW&63,EW>2047&&(EW<55296||EW>57343)&&(y=EW));break;case 4:OW=Y[O+1],DW=Y[O+2],wW=Y[O+3],(OW&192)===128&&(DW&192)===128&&(wW&192)===128&&(EW=(x&15)<<18|(OW&63)<<12|(DW&63)<<6|wW&63,EW>65535&&EW<1114112&&(y=EW))}}y===null?(y=65533,FW=1):y>65535&&(y-=65536,v.push(y>>>10&1023|55296),y=56320|y&1023),v.push(y),O+=FW}return p(v)}U(B,"utf8Slice");var m=4096;function p(Y){let L=Y.length;if(L<=m)return String.fromCharCode.apply(String,Y);let K="",v=0;for(;v<L;)K+=String.fromCharCode.apply(String,Y.slice(v,v+=m));return K}U(p,"decodeCodePointsArray");function a(Y,L,K){let v="";K=Math.min(Y.length,K);for(let O=L;O<K;++O)v+=String.fromCharCode(Y[O]&127);return v}U(a,"asciiSlice");function JW(Y,L,K){let v="";K=Math.min(Y.length,K);for(let O=L;O<K;++O)v+=String.fromCharCode(Y[O]);return v}U(JW,"latin1Slice");function n(Y,L,K){let v=Y.length;(!L||L<0)&&(L=0),(!K||K<0||K>v)&&(K=v);let O="";for(let x=L;x<K;++x)O+=s7[Y[x]];return O}U(n,"hexSlice");function sW(Y,L,K){let v=Y.slice(L,K),O="";for(let x=0;x<v.length-1;x+=2)O+=String.fromCharCode(v[x]+v[x+1]*256);return O}U(sW,"utf16leSlice"),z.prototype.slice=U(function(Y,L){let K=this.length;Y=~~Y,L=L===void 0?K:~~L,Y<0?(Y+=K,Y<0&&(Y=0)):Y>K&&(Y=K),L<0?(L+=K,L<0&&(L=0)):L>K&&(L=K),L<Y&&(L=Y);let v=this.subarray(Y,L);return Object.setPrototypeOf(v,z.prototype),v},"slice");function RW(Y,L,K){if(Y%1!==0||Y<0)throw RangeError("offset is not uint");if(Y+L>K)throw RangeError("Trying to access beyond buffer length")}U(RW,"checkOffset"),z.prototype.readUintLE=z.prototype.readUIntLE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let v=this[Y],O=1,x=0;for(;++x<L&&(O*=256);)v+=this[Y+x]*O;return v},"readUIntLE"),z.prototype.readUintBE=z.prototype.readUIntBE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let v=this[Y+--L],O=1;for(;L>0&&(O*=256);)v+=this[Y+--L]*O;return v},"readUIntBE"),z.prototype.readUint8=z.prototype.readUInt8=U(function(Y,L){return Y=Y>>>0,L||RW(Y,1,this.length),this[Y]},"readUInt8"),z.prototype.readUint16LE=z.prototype.readUInt16LE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,2,this.length),this[Y]|this[Y+1]<<8},"readUInt16LE"),z.prototype.readUint16BE=z.prototype.readUInt16BE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,2,this.length),this[Y]<<8|this[Y+1]},"readUInt16BE"),z.prototype.readUint32LE=z.prototype.readUInt32LE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),(this[Y]|this[Y+1]<<8|this[Y+2]<<16)+this[Y+3]*16777216},"readUInt32LE"),z.prototype.readUint32BE=z.prototype.readUInt32BE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),this[Y]*16777216+(this[Y+1]<<16|this[Y+2]<<8|this[Y+3])},"readUInt32BE"),z.prototype.readBigUInt64LE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let v=L+this[++Y]*256+this[++Y]*65536+this[++Y]*16777216,O=this[++Y]+this[++Y]*256+this[++Y]*65536+K*16777216;return BigInt(v)+(BigInt(O)<<BigInt(32))},"readBigUInt64LE")),z.prototype.readBigUInt64BE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let v=L*16777216+this[++Y]*65536+this[++Y]*256+this[++Y],O=this[++Y]*16777216+this[++Y]*65536+this[++Y]*256+K;return(BigInt(v)<<BigInt(32))+BigInt(O)},"readBigUInt64BE")),z.prototype.readIntLE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let v=this[Y],O=1,x=0;for(;++x<L&&(O*=256);)v+=this[Y+x]*O;return O*=128,v>=O&&(v-=Math.pow(2,8*L)),v},"readIntLE"),z.prototype.readIntBE=U(function(Y,L,K){Y=Y>>>0,L=L>>>0,K||RW(Y,L,this.length);let v=L,O=1,x=this[Y+--v];for(;v>0&&(O*=256);)x+=this[Y+--v]*O;return O*=128,x>=O&&(x-=Math.pow(2,8*L)),x},"readIntBE"),z.prototype.readInt8=U(function(Y,L){return Y=Y>>>0,L||RW(Y,1,this.length),this[Y]&128?(255-this[Y]+1)*-1:this[Y]},"readInt8"),z.prototype.readInt16LE=U(function(Y,L){Y=Y>>>0,L||RW(Y,2,this.length);let K=this[Y]|this[Y+1]<<8;return K&32768?K|4294901760:K},"readInt16LE"),z.prototype.readInt16BE=U(function(Y,L){Y=Y>>>0,L||RW(Y,2,this.length);let K=this[Y+1]|this[Y]<<8;return K&32768?K|4294901760:K},"readInt16BE"),z.prototype.readInt32LE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),this[Y]|this[Y+1]<<8|this[Y+2]<<16|this[Y+3]<<24},"readInt32LE"),z.prototype.readInt32BE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),this[Y]<<24|this[Y+1]<<16|this[Y+2]<<8|this[Y+3]},"readInt32BE"),z.prototype.readBigInt64LE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let v=this[Y+4]+this[Y+5]*256+this[Y+6]*65536+(K<<24);return(BigInt(v)<<BigInt(32))+BigInt(L+this[++Y]*256+this[++Y]*65536+this[++Y]*16777216)},"readBigInt64LE")),z.prototype.readBigInt64BE=O1(U(function(Y){Y=Y>>>0,Z0(Y,"offset");let L=this[Y],K=this[Y+7];(L===void 0||K===void 0)&&_0(Y,this.length-8);let v=(L<<24)+this[++Y]*65536+this[++Y]*256+this[++Y];return(BigInt(v)<<BigInt(32))+BigInt(this[++Y]*16777216+this[++Y]*65536+this[++Y]*256+K)},"readBigInt64BE")),z.prototype.readFloatLE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),k.read(this,Y,!0,23,4)},"readFloatLE"),z.prototype.readFloatBE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,4,this.length),k.read(this,Y,!1,23,4)},"readFloatBE"),z.prototype.readDoubleLE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,8,this.length),k.read(this,Y,!0,52,8)},"readDoubleLE"),z.prototype.readDoubleBE=U(function(Y,L){return Y=Y>>>0,L||RW(Y,8,this.length),k.read(this,Y,!1,52,8)},"readDoubleBE");function SW(Y,L,K,v,O,x){if(!z.isBuffer(Y))throw TypeError('"buffer" argument must be a Buffer instance');if(L>O||L<x)throw RangeError('"value" argument is out of bounds');if(K+v>Y.length)throw RangeError("Index out of range")}U(SW,"checkInt"),z.prototype.writeUintLE=z.prototype.writeUIntLE=U(function(Y,L,K,v){if(Y=+Y,L=L>>>0,K=K>>>0,!v){let y=Math.pow(2,8*K)-1;SW(this,Y,L,K,y,0)}let O=1,x=0;for(this[L]=Y&255;++x<K&&(O*=256);)this[L+x]=Y/O&255;return L+K},"writeUIntLE"),z.prototype.writeUintBE=z.prototype.writeUIntBE=U(function(Y,L,K,v){if(Y=+Y,L=L>>>0,K=K>>>0,!v){let y=Math.pow(2,8*K)-1;SW(this,Y,L,K,y,0)}let O=K-1,x=1;for(this[L+O]=Y&255;--O>=0&&(x*=256);)this[L+O]=Y/x&255;return L+K},"writeUIntBE"),z.prototype.writeUint8=z.prototype.writeUInt8=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,1,255,0),this[L]=Y&255,L+1},"writeUInt8"),z.prototype.writeUint16LE=z.prototype.writeUInt16LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,65535,0),this[L]=Y&255,this[L+1]=Y>>>8,L+2},"writeUInt16LE"),z.prototype.writeUint16BE=z.prototype.writeUInt16BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,65535,0),this[L]=Y>>>8,this[L+1]=Y&255,L+2},"writeUInt16BE"),z.prototype.writeUint32LE=z.prototype.writeUInt32LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,4294967295,0),this[L+3]=Y>>>24,this[L+2]=Y>>>16,this[L+1]=Y>>>8,this[L]=Y&255,L+4},"writeUInt32LE"),z.prototype.writeUint32BE=z.prototype.writeUInt32BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,4294967295,0),this[L]=Y>>>24,this[L+1]=Y>>>16,this[L+2]=Y>>>8,this[L+3]=Y&255,L+4},"writeUInt32BE");function r0(Y,L,K,v,O){b4(L,v,O,Y,K,7);let x=Number(L&BigInt(4294967295));Y[K++]=x,x=x>>8,Y[K++]=x,x=x>>8,Y[K++]=x,x=x>>8,Y[K++]=x;let y=Number(L>>BigInt(32)&BigInt(4294967295));return Y[K++]=y,y=y>>8,Y[K++]=y,y=y>>8,Y[K++]=y,y=y>>8,Y[K++]=y,K}U(r0,"wrtBigUInt64LE");function e0(Y,L,K,v,O){b4(L,v,O,Y,K,7);let x=Number(L&BigInt(4294967295));Y[K+7]=x,x=x>>8,Y[K+6]=x,x=x>>8,Y[K+5]=x,x=x>>8,Y[K+4]=x;let y=Number(L>>BigInt(32)&BigInt(4294967295));return Y[K+3]=y,y=y>>8,Y[K+2]=y,y=y>>8,Y[K+1]=y,y=y>>8,Y[K]=y,K+8}U(e0,"wrtBigUInt64BE"),z.prototype.writeBigUInt64LE=O1(U(function(Y,L=0){return r0(this,Y,L,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64LE")),z.prototype.writeBigUInt64BE=O1(U(function(Y,L=0){return e0(this,Y,L,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64BE")),z.prototype.writeIntLE=U(function(Y,L,K,v){if(Y=+Y,L=L>>>0,!v){let FW=Math.pow(2,8*K-1);SW(this,Y,L,K,FW-1,-FW)}let O=0,x=1,y=0;for(this[L]=Y&255;++O<K&&(x*=256);)Y<0&&y===0&&this[L+O-1]!==0&&(y=1),this[L+O]=(Y/x>>0)-y&255;return L+K},"writeIntLE"),z.prototype.writeIntBE=U(function(Y,L,K,v){if(Y=+Y,L=L>>>0,!v){let FW=Math.pow(2,8*K-1);SW(this,Y,L,K,FW-1,-FW)}let O=K-1,x=1,y=0;for(this[L+O]=Y&255;--O>=0&&(x*=256);)Y<0&&y===0&&this[L+O+1]!==0&&(y=1),this[L+O]=(Y/x>>0)-y&255;return L+K},"writeIntBE"),z.prototype.writeInt8=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,1,127,-128),Y<0&&(Y=255+Y+1),this[L]=Y&255,L+1},"writeInt8"),z.prototype.writeInt16LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,32767,-32768),this[L]=Y&255,this[L+1]=Y>>>8,L+2},"writeInt16LE"),z.prototype.writeInt16BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,2,32767,-32768),this[L]=Y>>>8,this[L+1]=Y&255,L+2},"writeInt16BE"),z.prototype.writeInt32LE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,2147483647,-2147483648),this[L]=Y&255,this[L+1]=Y>>>8,this[L+2]=Y>>>16,this[L+3]=Y>>>24,L+4},"writeInt32LE"),z.prototype.writeInt32BE=U(function(Y,L,K){return Y=+Y,L=L>>>0,K||SW(this,Y,L,4,2147483647,-2147483648),Y<0&&(Y=4294967295+Y+1),this[L]=Y>>>24,this[L+1]=Y>>>16,this[L+2]=Y>>>8,this[L+3]=Y&255,L+4},"writeInt32BE"),z.prototype.writeBigInt64LE=O1(U(function(Y,L=0){return r0(this,Y,L,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64LE")),z.prototype.writeBigInt64BE=O1(U(function(Y,L=0){return e0(this,Y,L,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64BE"));function C4(Y,L,K,v,O,x){if(K+v>Y.length)throw RangeError("Index out of range");if(K<0)throw RangeError("Index out of range")}U(C4,"checkIEEE754");function Q4(Y,L,K,v,O){return L=+L,K=K>>>0,O||C4(Y,L,K,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),k.write(Y,L,K,v,23,4),K+4}U(Q4,"writeFloat"),z.prototype.writeFloatLE=U(function(Y,L,K){return Q4(this,Y,L,!0,K)},"writeFloatLE"),z.prototype.writeFloatBE=U(function(Y,L,K){return Q4(this,Y,L,!1,K)},"writeFloatBE");function x4(Y,L,K,v,O){return L=+L,K=K>>>0,O||C4(Y,L,K,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),k.write(Y,L,K,v,52,8),K+8}U(x4,"writeDouble"),z.prototype.writeDoubleLE=U(function(Y,L,K){return x4(this,Y,L,!0,K)},"writeDoubleLE"),z.prototype.writeDoubleBE=U(function(Y,L,K){return x4(this,Y,L,!1,K)},"writeDoubleBE"),z.prototype.copy=U(function(Y,L,K,v){if(!z.isBuffer(Y))throw TypeError("argument should be a Buffer");if(K||(K=0),!v&&v!==0&&(v=this.length),L>=Y.length&&(L=Y.length),L||(L=0),v>0&&v<K&&(v=K),v===K||Y.length===0||this.length===0)return 0;if(L<0)throw RangeError("targetStart out of bounds");if(K<0||K>=this.length)throw RangeError("Index out of range");if(v<0)throw RangeError("sourceEnd out of bounds");v>this.length&&(v=this.length),Y.length-L<v-K&&(v=Y.length-L+K);let O=v-K;return this===Y&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(L,K,v):Uint8Array.prototype.set.call(Y,this.subarray(K,v),L),O},"copy"),z.prototype.fill=U(function(Y,L,K,v){if(typeof Y=="string"){if(typeof L=="string"?(v=L,L=0,K=this.length):typeof K=="string"&&(v=K,K=this.length),v!==void 0&&typeof v!="string")throw TypeError("encoding must be a string");if(typeof v=="string"&&!z.isEncoding(v))throw TypeError("Unknown encoding: "+v);if(Y.length===1){let x=Y.charCodeAt(0);(v==="utf8"&&x<128||v==="latin1")&&(Y=x)}}else typeof Y=="number"?Y=Y&255:typeof Y=="boolean"&&(Y=Number(Y));if(L<0||this.length<L||this.length<K)throw RangeError("Out of range index");if(K<=L)return this;L=L>>>0,K=K===void 0?this.length:K>>>0,Y||(Y=0);let O;if(typeof Y=="number")for(O=L;O<K;++O)this[O]=Y;else{let x=z.isBuffer(Y)?Y:z.from(Y,v),y=x.length;if(y===0)throw TypeError('The value "'+Y+'" is invalid for argument "value"');for(O=0;O<K-L;++O)this[O+L]=x[O%y]}return this},"fill");var w0={};function b8(Y,L,K){var v;w0[Y]=(v=class extends K{constructor(){super(),Object.defineProperty(this,"message",{value:L.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${Y}]`,this.stack,delete this.name}get code(){return Y}set code(O){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:O,writable:!0})}toString(){return`${this.name} [${Y}]: ${this.message}`}},U(v,"NodeError"),v)}U(b8,"E"),b8("ERR_BUFFER_OUT_OF_BOUNDS",function(Y){return Y?`${Y} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),b8("ERR_INVALID_ARG_TYPE",function(Y,L){return`The "${Y}" argument must be of type number. Received type ${typeof L}`},TypeError),b8("ERR_OUT_OF_RANGE",function(Y,L,K){let v=`The value of "${Y}" is out of range.`,O=K;return Number.isInteger(K)&&Math.abs(K)>4294967296?O=q4(String(K)):typeof K=="bigint"&&(O=String(K),(K>BigInt(2)**BigInt(32)||K<-(BigInt(2)**BigInt(32)))&&(O=q4(O)),O+="n"),v+=` It must be ${L}. Received ${O}`,v},RangeError);function q4(Y){let L="",K=Y.length,v=Y[0]==="-"?1:0;for(;K>=v+4;K-=3)L=`_${Y.slice(K-3,K)}${L}`;return`${Y.slice(0,K)}${L}`}U(q4,"addNumericalSeparator");function J9(Y,L,K){Z0(L,"offset"),(Y[L]===void 0||Y[L+K]===void 0)&&_0(L,Y.length-(K+1))}U(J9,"checkBounds");function b4(Y,L,K,v,O,x){if(Y>K||Y<L){let y=typeof L=="bigint"?"n":"",FW;throw x>3?L===0||L===BigInt(0)?FW=`>= 0${y} and < 2${y} ** ${(x+1)*8}${y}`:FW=`>= -(2${y} ** ${(x+1)*8-1}${y}) and < 2 ** ${(x+1)*8-1}${y}`:FW=`>= ${L}${y} and <= ${K}${y}`,new w0.ERR_OUT_OF_RANGE("value",FW,Y)}J9(v,O,x)}U(b4,"checkIntBI");function Z0(Y,L){if(typeof Y!="number")throw new w0.ERR_INVALID_ARG_TYPE(L,"number",Y)}U(Z0,"validateNumber");function _0(Y,L,K){throw Math.floor(Y)!==Y?(Z0(Y,K),new w0.ERR_OUT_OF_RANGE(K||"offset","an integer",Y)):L<0?new w0.ERR_BUFFER_OUT_OF_BOUNDS:new w0.ERR_OUT_OF_RANGE(K||"offset",`>= ${K?1:0} and <= ${L}`,Y)}U(_0,"boundsError");var t7=/[^+/0-9A-Za-z-_]/g;function Z9(Y){if(Y=Y.split("=")[0],Y=Y.trim().replace(t7,""),Y.length<2)return"";for(;Y.length%4!==0;)Y=Y+"=";return Y}U(Z9,"base64clean");function B8(Y,L){L=L||1/0;let K,v=Y.length,O=null,x=[];for(let y=0;y<v;++y){if(K=Y.charCodeAt(y),K>55295&&K<57344){if(!O){if(K>56319){(L-=3)>-1&&x.push(239,191,189);continue}else if(y+1===v){(L-=3)>-1&&x.push(239,191,189);continue}O=K;continue}if(K<56320){(L-=3)>-1&&x.push(239,191,189),O=K;continue}K=(O-55296<<10|K-56320)+65536}else O&&(L-=3)>-1&&x.push(239,191,189);if(O=null,K<128){if((L-=1)<0)break;x.push(K)}else if(K<2048){if((L-=2)<0)break;x.push(K>>6|192,K&63|128)}else if(K<65536){if((L-=3)<0)break;x.push(K>>12|224,K>>6&63|128,K&63|128)}else if(K<1114112){if((L-=4)<0)break;x.push(K>>18|240,K>>12&63|128,K>>6&63|128,K&63|128)}else throw Error("Invalid code point")}return x}U(B8,"utf8ToBytes");function X9(Y){let L=[];for(let K=0;K<Y.length;++K)L.push(Y.charCodeAt(K)&255);return L}U(X9,"asciiToBytes");function Y9(Y,L){let K,v,O,x=[];for(let y=0;y<Y.length&&!((L-=2)<0);++y)K=Y.charCodeAt(y),v=K>>8,O=K%256,x.push(O),x.push(v);return x}U(Y9,"utf16leToBytes");function B4(Y){return $.toByteArray(Z9(Y))}U(B4,"base64ToBytes");function W8(Y,L,K,v){let O;for(O=0;O<v&&!(O+K>=L.length||O>=Y.length);++O)L[O+K]=Y[O];return O}U(W8,"blitBuffer");function Z1(Y,L){return Y instanceof L||Y!=null&&Y.constructor!=null&&Y.constructor.name!=null&&Y.constructor.name===L.name}U(Z1,"isInstance");function I8(Y){return Y!==Y}U(I8,"numberIsNaN");var s7=function(){let Y="0123456789abcdef",L=Array(256);for(let K=0;K<16;++K){let v=K*16;for(let O=0;O<16;++O)L[v+O]=Y[K]+Y[O]}return L}();function O1(Y){return typeof BigInt>"u"?H9:Y}U(O1,"defineBigIntMethod");function H9(){throw Error("BigInt not supported")}U(H9,"BufferBigIntNotDefined")}),D4,t6,Ik,t,o,l=tW(()=>{D4=globalThis,t6=globalThis.setImmediate??((W)=>setTimeout(W,0)),Ik=globalThis.clearImmediate??((W)=>clearTimeout(W)),t=typeof globalThis.Buffer=="function"&&typeof globalThis.Buffer.allocUnsafe=="function"?globalThis.Buffer:Bk().Buffer,o=globalThis.process??{},o.env??(o.env={});try{o.nextTick(()=>{})}catch{let W=Promise.resolve();o.nextTick=W.then.bind(W)}}),F0=r((W,$)=>{l();var k=typeof Reflect=="object"?Reflect:null,J=k&&typeof k.apply=="function"?k.apply:U(function(E,j,A){return Function.prototype.apply.call(E,j,A)},"ReflectApply"),Z;k&&typeof k.ownKeys=="function"?Z=k.ownKeys:Object.getOwnPropertySymbols?Z=U(function(E){return Object.getOwnPropertyNames(E).concat(Object.getOwnPropertySymbols(E))},"ReflectOwnKeys"):Z=U(function(E){return Object.getOwnPropertyNames(E)},"ReflectOwnKeys");function X(E){console&&console.warn&&console.warn(E)}U(X,"ProcessEmitWarning");var G=Number.isNaN||U(function(E){return E!==E},"NumberIsNaN");function z(){z.init.call(this)}U(z,"EventEmitter"),$.exports=z,$.exports.once=S,z.EventEmitter=z,z.prototype._events=void 0,z.prototype._eventsCount=0,z.prototype._maxListeners=void 0;var V=10;function w(E){if(typeof E!="function")throw TypeError('The "listener" argument must be of type Function. Received type '+typeof E)}U(w,"checkListener"),Object.defineProperty(z,"defaultMaxListeners",{enumerable:!0,get:U(function(){return V},"get"),set:U(function(E){if(typeof E!="number"||E<0||G(E))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+E+".");V=E},"set")}),z.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},z.prototype.setMaxListeners=U(function(E){if(typeof E!="number"||E<0||G(E))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+E+".");return this._maxListeners=E,this},"setMaxListeners");function R(E){return E._maxListeners===void 0?z.defaultMaxListeners:E._maxListeners}U(R,"_getMaxListeners"),z.prototype.getMaxListeners=U(function(){return R(this)},"getMaxListeners"),z.prototype.emit=U(function(E){for(var j=[],A=1;A<arguments.length;A++)j.push(arguments[A]);var N=E==="error",b=this._events;if(b!==void 0)N=N&&b.error===void 0;else if(!N)return!1;if(N){var C;if(j.length>0&&(C=j[0]),C instanceof Error)throw C;var u=Error("Unhandled error."+(C?" ("+C.message+")":""));throw u.context=C,u}var c=b[E];if(c===void 0)return!1;if(typeof c=="function")J(c,this,j);else for(var B=c.length,m=P(c,B),A=0;A<B;++A)J(m[A],this,j);return!0},"emit");function h(E,j,A,N){var b,C,u;if(w(A),C=E._events,C===void 0?(C=E._events=Object.create(null),E._eventsCount=0):(C.newListener!==void 0&&(E.emit("newListener",j,A.listener?A.listener:A),C=E._events),u=C[j]),u===void 0)u=C[j]=A,++E._eventsCount;else if(typeof u=="function"?u=C[j]=N?[A,u]:[u,A]:N?u.unshift(A):u.push(A),b=R(E),b>0&&u.length>b&&!u.warned){u.warned=!0;var c=Error("Possible EventEmitter memory leak detected. "+u.length+" "+String(j)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=E,c.type=j,c.count=u.length,X(c)}return E}U(h,"_addListener"),z.prototype.addListener=U(function(E,j){return h(this,E,j,!1)},"addListener"),z.prototype.on=z.prototype.addListener,z.prototype.prependListener=U(function(E,j){return h(this,E,j,!0)},"prependListener");function _(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}U(_,"onceWrapper");function D(E,j,A){var N={fired:!1,wrapFn:void 0,target:E,type:j,listener:A},b=_.bind(N);return b.listener=A,N.wrapFn=b,b}U(D,"_onceWrap"),z.prototype.once=U(function(E,j){return w(j),this.on(E,D(this,E,j)),this},"once"),z.prototype.prependOnceListener=U(function(E,j){return w(j),this.prependListener(E,D(this,E,j)),this},"prependOnceListener"),z.prototype.removeListener=U(function(E,j){var A,N,b,C,u;if(w(j),N=this._events,N===void 0)return this;if(A=N[E],A===void 0)return this;if(A===j||A.listener===j)--this._eventsCount===0?this._events=Object.create(null):(delete N[E],N.removeListener&&this.emit("removeListener",E,A.listener||j));else if(typeof A!="function"){for(b=-1,C=A.length-1;C>=0;C--)if(A[C]===j||A[C].listener===j){u=A[C].listener,b=C;break}if(b<0)return this;b===0?A.shift():f(A,b),A.length===1&&(N[E]=A[0]),N.removeListener!==void 0&&this.emit("removeListener",E,u||j)}return this},"removeListener"),z.prototype.off=z.prototype.removeListener,z.prototype.removeAllListeners=U(function(E){var j,A,N;if(A=this._events,A===void 0)return this;if(A.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):A[E]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete A[E]),this;if(arguments.length===0){var b=Object.keys(A),C;for(N=0;N<b.length;++N)C=b[N],C!=="removeListener"&&this.removeAllListeners(C);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(j=A[E],typeof j=="function")this.removeListener(E,j);else if(j!==void 0)for(N=j.length-1;N>=0;N--)this.removeListener(E,j[N]);return this},"removeAllListeners");function F(E,j,A){var N=E._events;if(N===void 0)return[];var b=N[j];return b===void 0?[]:typeof b=="function"?A?[b.listener||b]:[b]:A?T(b):P(b,b.length)}U(F,"_listeners"),z.prototype.listeners=U(function(E){return F(this,E,!0)},"listeners"),z.prototype.rawListeners=U(function(E){return F(this,E,!1)},"rawListeners"),z.listenerCount=function(E,j){return typeof E.listenerCount=="function"?E.listenerCount(j):M.call(E,j)},z.prototype.listenerCount=M;function M(E){var j=this._events;if(j!==void 0){var A=j[E];if(typeof A=="function")return 1;if(A!==void 0)return A.length}return 0}U(M,"listenerCount"),z.prototype.eventNames=U(function(){return this._eventsCount>0?Z(this._events):[]},"eventNames");function P(E,j){for(var A=Array(j),N=0;N<j;++N)A[N]=E[N];return A}U(P,"arrayClone");function f(E,j){for(;j+1<E.length;j++)E[j]=E[j+1];E.pop()}U(f,"spliceOne");function T(E){for(var j=Array(E.length),A=0;A<j.length;++A)j[A]=E[A].listener||E[A];return j}U(T,"unwrapListeners");function S(E,j){return new Promise(function(A,N){function b(u){E.removeListener(j,C),N(u)}U(b,"errorListener");function C(){typeof E.removeListener=="function"&&E.removeListener("error",b),A([].slice.call(arguments))}U(C,"resolver"),Q(E,j,C,{once:!0}),j!=="error"&&q(E,b,{once:!0})})}U(S,"once");function q(E,j,A){typeof E.on=="function"&&Q(E,"error",j,A)}U(q,"addErrorHandlerIfEventEmitter");function Q(E,j,A,N){if(typeof E.on=="function")N.once?E.once(j,A):E.on(j,A);else if(typeof E.addEventListener=="function")E.addEventListener(j,U(function b(C){N.once&&E.removeEventListener(j,b),A(C)},"wrapListener"));else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof E)}U(Q,"eventTargetAgnosticAddListener")}),u5={};_1(u5,{Socket:()=>V0,isIP:()=>l5});function l5(W){return 0}var b5,c6,A8,V0,Q8=tW(()=>{l(),b5=R0(F0(),1),U(l5,"isIP"),c6=/^[^.]+\./,A8=class W extends b5.EventEmitter{constructor(){super(...arguments);s(this,"opts",{}),s(this,"connecting",!1),s(this,"pending",!0),s(this,"writable",!0),s(this,"encrypted",!1),s(this,"authorized",!1),s(this,"destroyed",!1),s(this,"ws",null),s(this,"writeBuffer"),s(this,"tlsState",0),s(this,"tlsRead"),s(this,"tlsWrite")}static get poolQueryViaFetch(){return W.opts.poolQueryViaFetch??W.defaults.poolQueryViaFetch}static set poolQueryViaFetch($){W.opts.poolQueryViaFetch=$}static get fetchEndpoint(){return W.opts.fetchEndpoint??W.defaults.fetchEndpoint}static set fetchEndpoint($){W.opts.fetchEndpoint=$}static get fetchConnectionCache(){return!0}static set fetchConnectionCache($){console.warn("The `fetchConnectionCache` option is deprecated (now always `true`)")}static get fetchFunction(){return W.opts.fetchFunction??W.defaults.fetchFunction}static set fetchFunction($){W.opts.fetchFunction=$}static get webSocketConstructor(){return W.opts.webSocketConstructor??W.defaults.webSocketConstructor}static set webSocketConstructor($){W.opts.webSocketConstructor=$}get webSocketConstructor(){return this.opts.webSocketConstructor??W.webSocketConstructor}set webSocketConstructor($){this.opts.webSocketConstructor=$}static get wsProxy(){return W.opts.wsProxy??W.defaults.wsProxy}static set wsProxy($){W.opts.wsProxy=$}get wsProxy(){return this.opts.wsProxy??W.wsProxy}set wsProxy($){this.opts.wsProxy=$}static get coalesceWrites(){return W.opts.coalesceWrites??W.defaults.coalesceWrites}static set coalesceWrites($){W.opts.coalesceWrites=$}get coalesceWrites(){return this.opts.coalesceWrites??W.coalesceWrites}set coalesceWrites($){this.opts.coalesceWrites=$}static get useSecureWebSocket(){return W.opts.useSecureWebSocket??W.defaults.useSecureWebSocket}static set useSecureWebSocket($){W.opts.useSecureWebSocket=$}get useSecureWebSocket(){return this.opts.useSecureWebSocket??W.useSecureWebSocket}set useSecureWebSocket($){this.opts.useSecureWebSocket=$}static get forceDisablePgSSL(){return W.opts.forceDisablePgSSL??W.defaults.forceDisablePgSSL}static set forceDisablePgSSL($){W.opts.forceDisablePgSSL=$}get forceDisablePgSSL(){return this.opts.forceDisablePgSSL??W.forceDisablePgSSL}set forceDisablePgSSL($){this.opts.forceDisablePgSSL=$}static get disableSNI(){return W.opts.disableSNI??W.defaults.disableSNI}static set disableSNI($){W.opts.disableSNI=$}get disableSNI(){return this.opts.disableSNI??W.disableSNI}set disableSNI($){this.opts.disableSNI=$}static get disableWarningInBrowsers(){return W.opts.disableWarningInBrowsers??W.defaults.disableWarningInBrowsers}static set disableWarningInBrowsers($){W.opts.disableWarningInBrowsers=$}get disableWarningInBrowsers(){return this.opts.disableWarningInBrowsers??W.disableWarningInBrowsers}set disableWarningInBrowsers($){this.opts.disableWarningInBrowsers=$}static get pipelineConnect(){return W.opts.pipelineConnect??W.defaults.pipelineConnect}static set pipelineConnect($){W.opts.pipelineConnect=$}get pipelineConnect(){return this.opts.pipelineConnect??W.pipelineConnect}set pipelineConnect($){this.opts.pipelineConnect=$}static get subtls(){return W.opts.subtls??W.defaults.subtls}static set subtls($){W.opts.subtls=$}get subtls(){return this.opts.subtls??W.subtls}set subtls($){this.opts.subtls=$}static get pipelineTLS(){return W.opts.pipelineTLS??W.defaults.pipelineTLS}static set pipelineTLS($){W.opts.pipelineTLS=$}get pipelineTLS(){return this.opts.pipelineTLS??W.pipelineTLS}set pipelineTLS($){this.opts.pipelineTLS=$}static get rootCerts(){return W.opts.rootCerts??W.defaults.rootCerts}static set rootCerts($){W.opts.rootCerts=$}get rootCerts(){return this.opts.rootCerts??W.rootCerts}set rootCerts($){this.opts.rootCerts=$}wsProxyAddrForHost($,k){let J=this.wsProxy;if(J===void 0)throw Error("No WebSocket proxy is configured. Please see https://github.com/neondatabase/serverless/blob/main/CONFIG.md#wsproxy-string--host-string-port-number--string--string");return typeof J=="function"?J($,k):`${J}?address=${$}:${k}`}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}connect($,k,J){this.connecting=!0,J&&this.once("connect",J);let Z=U(()=>{this.connecting=!1,this.pending=!1,this.emit("connect"),this.emit("ready")},"handleWebSocketOpen"),X=U((z,V=!1)=>{z.binaryType="arraybuffer",z.addEventListener("error",(w)=>{this.emit("error",w),this.emit("close")}),z.addEventListener("message",(w)=>{if(this.tlsState===0){let R=t.from(w.data);this.emit("data",R)}}),z.addEventListener("close",()=>{this.emit("close")}),V?Z():z.addEventListener("open",Z)},"configureWebSocket"),G;try{G=this.wsProxyAddrForHost(k,typeof $=="string"?parseInt($,10):$)}catch(z){this.emit("error",z),this.emit("close");return}try{let z=(this.useSecureWebSocket?"wss:":"ws:")+"//"+G;if(this.webSocketConstructor!==void 0)this.ws=new this.webSocketConstructor(z),X(this.ws);else try{this.ws=new WebSocket(z),X(this.ws)}catch{this.ws=new __unstable_WebSocket(z),X(this.ws)}}catch(z){let V=(this.useSecureWebSocket?"https:":"http:")+"//"+G;fetch(V,{headers:{Upgrade:"websocket"}}).then((w)=>{if(this.ws=w.webSocket,this.ws==null)throw z;this.ws.accept(),X(this.ws,!0)}).catch((w)=>{this.emit("error",Error(`All attempts to open a WebSocket to connect to the database failed. Please refer to https://github.com/neondatabase/serverless/blob/main/CONFIG.md#websocketconstructor-typeof-websocket--undefined. Details: ${w}`)),this.emit("close")})}}async startTls($){if(this.subtls===void 0)throw Error("For Postgres SSL connections, you must set `neonConfig.subtls` to the subtls library. See https://github.com/neondatabase/serverless/blob/main/CONFIG.md for more information.");this.tlsState=1;let k=await this.subtls.TrustedCert.databaseFromPEM(this.rootCerts),J=new this.subtls.WebSocketReadQueue(this.ws),Z=J.read.bind(J),X=this.rawWrite.bind(this),{read:G,write:z}=await this.subtls.startTls($,k,Z,X,{useSNI:!this.disableSNI,expectPreData:this.pipelineTLS?new Uint8Array([83]):void 0});this.tlsRead=G,this.tlsWrite=z,this.tlsState=2,this.encrypted=!0,this.authorized=!0,this.emit("secureConnection",this),this.tlsReadLoop()}async tlsReadLoop(){for(;;){let $=await this.tlsRead();if($===void 0)break;{let k=t.from($);this.emit("data",k)}}}rawWrite($){if(!this.coalesceWrites){this.ws&&this.ws.send($);return}if(this.writeBuffer===void 0)this.writeBuffer=$,setTimeout(()=>{this.ws&&this.ws.send(this.writeBuffer),this.writeBuffer=void 0},0);else{let k=new Uint8Array(this.writeBuffer.length+$.length);k.set(this.writeBuffer),k.set($,this.writeBuffer.length),this.writeBuffer=k}}write($,k="utf8",J=(Z)=>{}){return $.length===0?(J(),!0):(typeof $=="string"&&($=t.from($,k)),this.tlsState===0?(this.rawWrite($),J()):this.tlsState===1?this.once("secureConnection",()=>{this.write($,k,J)}):(this.tlsWrite($),J()),!0)}end($=t.alloc(0),k="utf8",J=()=>{}){return this.write($,k,()=>{this.ws.close(),J()}),this}destroy(){return this.destroyed=!0,this.end()}},U(A8,"Socket"),s(A8,"defaults",{poolQueryViaFetch:!1,fetchEndpoint:U((W,$,k)=>{let J;return k?.jwtAuth?J=W.replace(c6,"apiauth."):J=W.replace(c6,"api."),"https://"+J+"/sql"},"fetchEndpoint"),fetchConnectionCache:!0,fetchFunction:void 0,webSocketConstructor:void 0,wsProxy:U((W)=>W+"/v2","wsProxy"),useSecureWebSocket:!0,forceDisablePgSSL:!0,coalesceWrites:!0,pipelineConnect:"password",subtls:void 0,rootCerts:"",pipelineTLS:!1,disableSNI:!1,disableWarningInBrowsers:!1}),s(A8,"opts",{}),V0=A8}),i5={};_1(i5,{parse:()=>s6});function s6(W,$=!1){let{protocol:k}=new URL(W),J="http:"+W.substring(k.length),{username:Z,password:X,host:G,hostname:z,port:V,pathname:w,search:R,searchParams:h,hash:_}=new URL(J);X=decodeURIComponent(X),Z=decodeURIComponent(Z),w=decodeURIComponent(w);let D=Z+":"+X,F=$?Object.fromEntries(h.entries()):R;return{href:W,protocol:k,auth:D,username:Z,password:X,host:G,hostname:z,port:V,pathname:w,search:R,query:F,hash:_}}var p5=tW(()=>{l(),U(s6,"parse")}),t5=r((W)=>{l(),W.parse=function(Z,X){return new k(Z,X).parse()};var $=class Z{constructor(X,G){this.source=X,this.transform=G||J,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var X=this.source[this.position++];return X==="\\"?{value:this.source[this.position++],escaped:!0}:{value:X,escaped:!1}}record(X){this.recorded.push(X)}newEntry(X){var G;(this.recorded.length>0||X)&&(G=this.recorded.join(""),G==="NULL"&&!X&&(G=null),G!==null&&(G=this.transform(G)),this.entries.push(G),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var X=this.nextCharacter();if(X.value==="=")break}}parse(X){var G,z,V;for(this.consumeDimensions();!this.isEof();)if(G=this.nextCharacter(),G.value==="{"&&!V)this.dimension++,this.dimension>1&&(z=new Z(this.source.substr(this.position-1),this.transform),this.entries.push(z.parse(!0)),this.position+=z.position-2);else if(G.value==="}"&&!V){if(this.dimension--,!this.dimension&&(this.newEntry(),X))return this.entries}else G.value==='"'&&!G.escaped?(V&&this.newEntry(!0),V=!V):G.value===","&&!V?this.newEntry():this.record(G.value);if(this.dimension!==0)throw Error("array dimension not balanced");return this.entries}};U($,"ArrayParser");var k=$;function J(Z){return Z}U(J,"identity")}),s5=r((W,$)=>{l();var k=t5();$.exports={create:U(function(J,Z){return{parse:U(function(){return k.parse(J,Z)},"parse")}},"create")}}),yk=r((W,$)=>{l();var k=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,J=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,Z=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,X=/^-?infinity$/;$.exports=U(function(R){if(X.test(R))return Number(R.replace("i","I"));var h=k.exec(R);if(!h)return G(R)||null;var _=!!h[8],D=parseInt(h[1],10);_&&(D=V(D));var F=parseInt(h[2],10)-1,M=h[3],P=parseInt(h[4],10),f=parseInt(h[5],10),T=parseInt(h[6],10),S=h[7];S=S?1000*parseFloat(S):0;var q,Q=z(R);return Q!=null?(q=new Date(Date.UTC(D,F,M,P,f,T,S)),w(D)&&q.setUTCFullYear(D),Q!==0&&q.setTime(q.getTime()-Q)):(q=new Date(D,F,M,P,f,T,S),w(D)&&q.setFullYear(D)),q},"parseDate");function G(R){var h=J.exec(R);if(h){var _=parseInt(h[1],10),D=!!h[4];D&&(_=V(_));var F=parseInt(h[2],10)-1,M=h[3],P=new Date(_,F,M);return w(_)&&P.setFullYear(_),P}}U(G,"getDate");function z(R){if(R.endsWith("+00"))return 0;var h=Z.exec(R.split(" ")[1]);if(h){var _=h[1];if(_==="Z")return 0;var D=_==="-"?-1:1,F=parseInt(h[2],10)*3600+parseInt(h[3]||0,10)*60+parseInt(h[4]||0,10);return F*D*1000}}U(z,"timeZoneOffset");function V(R){return-(R-1)}U(V,"bcYearToNegativeYear");function w(R){return R>=0&&R<100}U(w,"is0To99")}),gk=r((W,$)=>{l(),$.exports=J;var k=Object.prototype.hasOwnProperty;function J(Z){for(var X=1;X<arguments.length;X++){var G=arguments[X];for(var z in G)k.call(G,z)&&(Z[z]=G[z])}return Z}U(J,"extend")}),mk=r((W,$)=>{l();var k=gk();$.exports=J;function J(T){if(!(this instanceof J))return new J(T);k(this,f(T))}U(J,"PostgresInterval");var Z=["seconds","minutes","hours","days","months","years"];J.prototype.toPostgres=function(){var T=Z.filter(this.hasOwnProperty,this);return this.milliseconds&&T.indexOf("seconds")<0&&T.push("seconds"),T.length===0?"0":T.map(function(S){var q=this[S]||0;return S==="seconds"&&this.milliseconds&&(q=(q+this.milliseconds/1000).toFixed(6).replace(/\.?0+$/,"")),q+" "+S},this).join(" ")};var X={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},G=["years","months","days"],z=["hours","minutes","seconds"];J.prototype.toISOString=J.prototype.toISO=function(){var T=G.map(q,this).join(""),S=z.map(q,this).join("");return"P"+T+"T"+S;function q(Q){var E=this[Q]||0;return Q==="seconds"&&this.milliseconds&&(E=(E+this.milliseconds/1000).toFixed(6).replace(/0+$/,"")),E+X[Q]}};var V="([+-]?\\d+)",w=V+"\\s+years?",R=V+"\\s+mons?",h=V+"\\s+days?",_="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",D=new RegExp([w,R,h,_].map(function(T){return"("+T+")?"}).join("\\s*")),F={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},M=["hours","minutes","seconds","milliseconds"];function P(T){var S=T+"000000".slice(T.length);return parseInt(S,10)/1000}U(P,"parseMilliseconds");function f(T){if(!T)return{};var S=D.exec(T),q=S[8]==="-";return Object.keys(F).reduce(function(Q,E){var j=F[E],A=S[j];return!A||(A=E==="milliseconds"?P(A):parseInt(A,10),!A)||(q&&~M.indexOf(E)&&(A*=-1),Q[E]=A),Q},{})}U(f,"parse")}),ck=r((W,$)=>{l(),$.exports=U(function(k){if(/^\\x/.test(k))return new t(k.substr(2),"hex");for(var J="",Z=0;Z<k.length;)if(k[Z]!=="\\")J+=k[Z],++Z;else if(/[0-7]{3}/.test(k.substr(Z+1,3)))J+=String.fromCharCode(parseInt(k.substr(Z+1,3),8)),Z+=4;else{for(var X=1;Z+X<k.length&&k[Z+X]==="\\";)X++;for(var G=0;G<Math.floor(X/2);++G)J+="\\";Z+=Math.floor(X/2)*2}return new t(J,"binary")},"parseBytea")}),uk=r((W,$)=>{l();var k=t5(),J=s5(),Z=yk(),X=mk(),G=ck();function z(N){return U(function(b){return b===null?b:N(b)},"nullAllowed")}U(z,"allowNull");function V(N){return N===null?N:N==="TRUE"||N==="t"||N==="true"||N==="y"||N==="yes"||N==="on"||N==="1"}U(V,"parseBool");function w(N){return N?k.parse(N,V):null}U(w,"parseBoolArray");function R(N){return parseInt(N,10)}U(R,"parseBaseTenInt");function h(N){return N?k.parse(N,z(R)):null}U(h,"parseIntegerArray");function _(N){return N?k.parse(N,z(function(b){return q(b).trim()})):null}U(_,"parseBigIntegerArray");var D=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=E(C)),C});return b.parse()},"parsePointArray"),F=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=parseFloat(C)),C});return b.parse()},"parseFloatArray"),M=U(function(N){if(!N)return null;var b=J.create(N);return b.parse()},"parseStringArray"),P=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=Z(C)),C});return b.parse()},"parseDateArray"),f=U(function(N){if(!N)return null;var b=J.create(N,function(C){return C!==null&&(C=X(C)),C});return b.parse()},"parseIntervalArray"),T=U(function(N){return N?k.parse(N,z(G)):null},"parseByteAArray"),S=U(function(N){return parseInt(N,10)},"parseInteger"),q=U(function(N){var b=String(N);return/^\d+$/.test(b)?b:N},"parseBigInteger"),Q=U(function(N){return N?k.parse(N,z(JSON.parse)):null},"parseJsonArray"),E=U(function(N){return N[0]!=="("?null:(N=N.substring(1,N.length-1).split(","),{x:parseFloat(N[0]),y:parseFloat(N[1])})},"parsePoint"),j=U(function(N){if(N[0]!=="<"&&N[1]!=="(")return null;for(var b="(",C="",u=!1,c=2;c<N.length-1;c++){if(u||(b+=N[c]),N[c]===")"){u=!0;continue}else if(!u)continue;N[c]!==","&&(C+=N[c])}var B=E(b);return B.radius=parseFloat(C),B},"parseCircle"),A=U(function(N){N(20,q),N(21,S),N(23,S),N(26,S),N(700,parseFloat),N(701,parseFloat),N(16,V),N(1082,Z),N(1114,Z),N(1184,Z),N(600,E),N(651,M),N(718,j),N(1000,w),N(1001,T),N(1005,h),N(1007,h),N(1028,h),N(1016,_),N(1017,D),N(1021,F),N(1022,F),N(1231,F),N(1014,M),N(1015,M),N(1008,M),N(1009,M),N(1040,M),N(1041,M),N(1115,P),N(1182,P),N(1185,P),N(1186,X),N(1187,f),N(17,G),N(114,JSON.parse.bind(JSON)),N(3802,JSON.parse.bind(JSON)),N(199,Q),N(3807,Q),N(3907,M),N(2951,M),N(791,M),N(1183,M),N(1270,M)},"init");$.exports={init:A}}),lk=r((W,$)=>{l();var k=1e6;function J(Z){var X=Z.readInt32BE(0),G=Z.readUInt32BE(4),z="";X<0&&(X=~X+(G===0),G=~G+1>>>0,z="-");var V="",w,R,h,_,D,F;{if(w=X%k,X=X/k>>>0,R=4294967296*w+G,G=R/k>>>0,h=""+(R-k*G),G===0&&X===0)return z+h+V;for(_="",D=6-h.length,F=0;F<D;F++)_+="0";V=_+h+V}{if(w=X%k,X=X/k>>>0,R=4294967296*w+G,G=R/k>>>0,h=""+(R-k*G),G===0&&X===0)return z+h+V;for(_="",D=6-h.length,F=0;F<D;F++)_+="0";V=_+h+V}{if(w=X%k,X=X/k>>>0,R=4294967296*w+G,G=R/k>>>0,h=""+(R-k*G),G===0&&X===0)return z+h+V;for(_="",D=6-h.length,F=0;F<D;F++)_+="0";V=_+h+V}return w=X%k,R=4294967296*w+G,h=""+R%k,z+h+V}U(J,"readInt8"),$.exports=J}),ik=r((W,$)=>{l();var k=lk(),J=U(function(M,P,f,T,S){f=f||0,T=T||!1,S=S||function(u,c,B){return u*Math.pow(2,B)+c};var q=f>>3,Q=U(function(u){return T?~u&255:u},"inv"),E=255,j=8-f%8;P<j&&(E=255<<8-P&255,j=P),f&&(E=E>>f%8);var A=0;f%8+P>=8&&(A=S(0,Q(M[q])&E,j));for(var N=P+f>>3,b=q+1;b<N;b++)A=S(A,Q(M[b]),8);var C=(P+f)%8;return C>0&&(A=S(A,Q(M[N])>>8-C,C)),A},"parseBits"),Z=U(function(M,P,f){var T=Math.pow(2,f-1)-1,S=J(M,1),q=J(M,f,1);if(q===0)return 0;var Q=1,E=U(function(A,N,b){A===0&&(A=1);for(var C=1;C<=b;C++)Q/=2,(N&1<<b-C)>0&&(A+=Q);return A},"parsePrecisionBits"),j=J(M,P,f+1,!1,E);return q==Math.pow(2,f+1)-1?j===0?S===0?1/0:-1/0:NaN:(S===0?1:-1)*Math.pow(2,q-T)*j},"parseFloatFromBits"),X=U(function(M){return J(M,1)==1?-1*(J(M,15,1,!0)+1):J(M,15,1)},"parseInt16"),G=U(function(M){return J(M,1)==1?-1*(J(M,31,1,!0)+1):J(M,31,1)},"parseInt32"),z=U(function(M){return Z(M,23,8)},"parseFloat32"),V=U(function(M){return Z(M,52,11)},"parseFloat64"),w=U(function(M){var P=J(M,16,32);if(P==49152)return NaN;for(var f=Math.pow(1e4,J(M,16,16)),T=0,S=[],q=J(M,16),Q=0;Q<q;Q++)T+=J(M,16,64+16*Q)*f,f/=1e4;var E=Math.pow(10,J(M,16,48));return(P===0?1:-1)*Math.round(T*E)/E},"parseNumeric"),R=U(function(M,P){var f=J(P,1),T=J(P,63,1),S=new Date((f===0?1:-1)*T/1000+946684800000);return M||S.setTime(S.getTime()+S.getTimezoneOffset()*60000),S.usec=T%1000,S.getMicroSeconds=function(){return this.usec},S.setMicroSeconds=function(q){this.usec=q},S.getUTCMicroSeconds=function(){return this.usec},S},"parseDate"),h=U(function(M){for(var P=J(M,32),f=J(M,32,32),T=J(M,32,64),S=96,q=[],Q=0;Q<P;Q++)q[Q]=J(M,32,S),S+=32,S+=32;var E=U(function(A){var N=J(M,32,S);if(S+=32,N==4294967295)return null;var b;if(A==23||A==20)return b=J(M,N*8,S),S+=N*8,b;if(A==25)return b=M.toString(this.encoding,S>>3,(S+=N<<3)>>3),b;console.log("ERROR: ElementType not implemented: "+A)},"parseElement"),j=U(function(A,N){var b=[],C;if(A.length>1){var u=A.shift();for(C=0;C<u;C++)b[C]=j(A,N);A.unshift(u)}else for(C=0;C<A[0];C++)b[C]=E(N);return b},"parse");return j(q,T)},"parseArray"),_=U(function(M){return M.toString("utf8")},"parseText"),D=U(function(M){return M===null?null:J(M,8)>0},"parseBool"),F=U(function(M){M(20,k),M(21,X),M(23,G),M(26,G),M(1700,w),M(700,z),M(701,V),M(16,D),M(1114,R.bind(null,!1)),M(1184,R.bind(null,!0)),M(1000,h),M(1007,h),M(1016,h),M(1008,h),M(1009,h),M(25,_)},"init");$.exports={init:F}}),pk=r((W,$)=>{l(),$.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}}),f4=r((W)=>{l();var $=uk(),k=ik(),J=s5(),Z=pk();W.getTypeParser=z,W.setTypeParser=V,W.arrayParser=J,W.builtins=Z;var X={text:{},binary:{}};function G(w){return String(w)}U(G,"noParse");function z(w,R){return R=R||"text",X[R]&&X[R][w]||G}U(z,"getTypeParser");function V(w,R,h){typeof R=="function"&&(h=R,R="text"),X[R][w]=h}U(V,"setTypeParser"),$.init(function(w,R){X.text[w]=R}),k.init(function(w,R){X.binary[w]=R})}),a6=r((W,$)=>{l();var k=f4();function J(Z){this._types=Z||k,this.text={},this.binary={}}U(J,"TypeOverrides"),J.prototype.getOverrides=function(Z){switch(Z){case"text":return this.text;case"binary":return this.binary;default:return{}}},J.prototype.setTypeParser=function(Z,X,G){typeof X=="function"&&(G=X,X="text"),this.getOverrides(X)[Z]=G},J.prototype.getTypeParser=function(Z,X){return X=X||"text",this.getOverrides(X)[Z]||this._types.getTypeParser(Z,X)},$.exports=J});function C8(W){let $=1779033703,k=3144134277,J=1013904242,Z=2773480762,X=1359893119,G=2600822924,z=528734635,V=1541459225,w=0,R=0,h=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],_=U((T,S)=>T>>>S|T<<32-S,"rrot"),D=new Uint32Array(64),F=new Uint8Array(64),M=U(()=>{for(let b=0,C=0;b<16;b++,C+=4)D[b]=F[C]<<24|F[C+1]<<16|F[C+2]<<8|F[C+3];for(let b=16;b<64;b++){let C=_(D[b-15],7)^_(D[b-15],18)^D[b-15]>>>3,u=_(D[b-2],17)^_(D[b-2],19)^D[b-2]>>>10;D[b]=D[b-16]+C+D[b-7]+u|0}let T=$,S=k,q=J,Q=Z,E=X,j=G,A=z,N=V;for(let b=0;b<64;b++){let C=_(E,6)^_(E,11)^_(E,25),u=E&j^~E&A,c=N+C+u+h[b]+D[b]|0,B=_(T,2)^_(T,13)^_(T,22),m=T&S^T&q^S&q,p=B+m|0;N=A,A=j,j=E,E=Q+c|0,Q=q,q=S,S=T,T=c+p|0}$=$+T|0,k=k+S|0,J=J+q|0,Z=Z+Q|0,X=X+E|0,G=G+j|0,z=z+A|0,V=V+N|0,R=0},"process"),P=U((T)=>{typeof T=="string"&&(T=new TextEncoder().encode(T));for(let S=0;S<T.length;S++)F[R++]=T[S],R===64&&M();w+=T.length},"add"),f=U(()=>{if(F[R++]=128,R==64&&M(),R+8>64){for(;R<64;)F[R++]=0;M()}for(;R<58;)F[R++]=0;let T=w*8;F[R++]=T/1099511627776&255,F[R++]=T/4294967296&255,F[R++]=T>>>24,F[R++]=T>>>16&255,F[R++]=T>>>8&255,F[R++]=T&255,M();let S=new Uint8Array(32);return S[0]=$>>>24,S[1]=$>>>16&255,S[2]=$>>>8&255,S[3]=$&255,S[4]=k>>>24,S[5]=k>>>16&255,S[6]=k>>>8&255,S[7]=k&255,S[8]=J>>>24,S[9]=J>>>16&255,S[10]=J>>>8&255,S[11]=J&255,S[12]=Z>>>24,S[13]=Z>>>16&255,S[14]=Z>>>8&255,S[15]=Z&255,S[16]=X>>>24,S[17]=X>>>16&255,S[18]=X>>>8&255,S[19]=X&255,S[20]=G>>>24,S[21]=G>>>16&255,S[22]=G>>>8&255,S[23]=G&255,S[24]=z>>>24,S[25]=z>>>16&255,S[26]=z>>>8&255,S[27]=z&255,S[28]=V>>>24,S[29]=V>>>16&255,S[30]=V>>>8&255,S[31]=V&255,S},"digest");return W===void 0?{add:P,digest:f}:(P(W),f())}var tk=tW(()=>{l(),U(C8,"sha256")}),c1,l6,sk=tW(()=>{l(),c1=class W{constructor(){s(this,"_dataLength",0),s(this,"_bufferLength",0),s(this,"_state",new Int32Array(4)),s(this,"_buffer",new ArrayBuffer(68)),s(this,"_buffer8"),s(this,"_buffer32"),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashByteArray($,k=!1){return this.onePassHasher.start().appendByteArray($).end(k)}static hashStr($,k=!1){return this.onePassHasher.start().appendStr($).end(k)}static hashAsciiStr($,k=!1){return this.onePassHasher.start().appendAsciiStr($).end(k)}static _hex($){let{hexChars:k,hexOut:J}=W,Z,X,G,z;for(z=0;z<4;z+=1)for(X=z*8,Z=$[z],G=0;G<8;G+=2)J[X+1+G]=k.charAt(Z&15),Z>>>=4,J[X+0+G]=k.charAt(Z&15),Z>>>=4;return J.join("")}static _md5cycle($,k){let J=$[0],Z=$[1],X=$[2],G=$[3];J+=(Z&X|~Z&G)+k[0]-680876936|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[1]-389564586|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[2]+606105819|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[3]-1044525330|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&X|~Z&G)+k[4]-176418897|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[5]+1200080426|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[6]-1473231341|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[7]-45705983|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&X|~Z&G)+k[8]+1770035416|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[9]-1958414417|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[10]-42063|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[11]-1990404162|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&X|~Z&G)+k[12]+1804603682|0,J=(J<<7|J>>>25)+Z|0,G+=(J&Z|~J&X)+k[13]-40341101|0,G=(G<<12|G>>>20)+J|0,X+=(G&J|~G&Z)+k[14]-1502002290|0,X=(X<<17|X>>>15)+G|0,Z+=(X&G|~X&J)+k[15]+1236535329|0,Z=(Z<<22|Z>>>10)+X|0,J+=(Z&G|X&~G)+k[1]-165796510|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[6]-1069501632|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[11]+643717713|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[0]-373897302|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z&G|X&~G)+k[5]-701558691|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[10]+38016083|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[15]-660478335|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[4]-405537848|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z&G|X&~G)+k[9]+568446438|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[14]-1019803690|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[3]-187363961|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[8]+1163531501|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z&G|X&~G)+k[13]-1444681467|0,J=(J<<5|J>>>27)+Z|0,G+=(J&X|Z&~X)+k[2]-51403784|0,G=(G<<9|G>>>23)+J|0,X+=(G&Z|J&~Z)+k[7]+1735328473|0,X=(X<<14|X>>>18)+G|0,Z+=(X&J|G&~J)+k[12]-1926607734|0,Z=(Z<<20|Z>>>12)+X|0,J+=(Z^X^G)+k[5]-378558|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[8]-2022574463|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[11]+1839030562|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[14]-35309556|0,Z=(Z<<23|Z>>>9)+X|0,J+=(Z^X^G)+k[1]-1530992060|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[4]+1272893353|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[7]-155497632|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[10]-1094730640|0,Z=(Z<<23|Z>>>9)+X|0,J+=(Z^X^G)+k[13]+681279174|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[0]-358537222|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[3]-722521979|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[6]+76029189|0,Z=(Z<<23|Z>>>9)+X|0,J+=(Z^X^G)+k[9]-640364487|0,J=(J<<4|J>>>28)+Z|0,G+=(J^Z^X)+k[12]-421815835|0,G=(G<<11|G>>>21)+J|0,X+=(G^J^Z)+k[15]+530742520|0,X=(X<<16|X>>>16)+G|0,Z+=(X^G^J)+k[2]-995338651|0,Z=(Z<<23|Z>>>9)+X|0,J+=(X^(Z|~G))+k[0]-198630844|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[7]+1126891415|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[14]-1416354905|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[5]-57434055|0,Z=(Z<<21|Z>>>11)+X|0,J+=(X^(Z|~G))+k[12]+1700485571|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[3]-1894986606|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[10]-1051523|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[1]-2054922799|0,Z=(Z<<21|Z>>>11)+X|0,J+=(X^(Z|~G))+k[8]+1873313359|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[15]-30611744|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[6]-1560198380|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[13]+1309151649|0,Z=(Z<<21|Z>>>11)+X|0,J+=(X^(Z|~G))+k[4]-145523070|0,J=(J<<6|J>>>26)+Z|0,G+=(Z^(J|~X))+k[11]-1120210379|0,G=(G<<10|G>>>22)+J|0,X+=(J^(G|~Z))+k[2]+718787259|0,X=(X<<15|X>>>17)+G|0,Z+=(G^(X|~J))+k[9]-343485551|0,Z=(Z<<21|Z>>>11)+X|0,$[0]=J+$[0]|0,$[1]=Z+$[1]|0,$[2]=X+$[2]|0,$[3]=G+$[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(W.stateIdentity),this}appendStr($){let k=this._buffer8,J=this._buffer32,Z=this._bufferLength,X,G;for(G=0;G<$.length;G+=1){if(X=$.charCodeAt(G),X<128)k[Z++]=X;else if(X<2048)k[Z++]=(X>>>6)+192,k[Z++]=X&63|128;else if(X<55296||X>56319)k[Z++]=(X>>>12)+224,k[Z++]=X>>>6&63|128,k[Z++]=X&63|128;else{if(X=(X-55296)*1024+($.charCodeAt(++G)-56320)+65536,X>1114111)throw Error("Unicode standard supports code points up to U+10FFFF");k[Z++]=(X>>>18)+240,k[Z++]=X>>>12&63|128,k[Z++]=X>>>6&63|128,k[Z++]=X&63|128}Z>=64&&(this._dataLength+=64,W._md5cycle(this._state,J),Z-=64,J[0]=J[16])}return this._bufferLength=Z,this}appendAsciiStr($){let k=this._buffer8,J=this._buffer32,Z=this._bufferLength,X,G=0;for(;;){for(X=Math.min($.length-G,64-Z);X--;)k[Z++]=$.charCodeAt(G++);if(Z<64)break;this._dataLength+=64,W._md5cycle(this._state,J),Z=0}return this._bufferLength=Z,this}appendByteArray($){let k=this._buffer8,J=this._buffer32,Z=this._bufferLength,X,G=0;for(;;){for(X=Math.min($.length-G,64-Z);X--;)k[Z++]=$[G++];if(Z<64)break;this._dataLength+=64,W._md5cycle(this._state,J),Z=0}return this._bufferLength=Z,this}getState(){let $=this._state;return{buffer:String.fromCharCode.apply(null,Array.from(this._buffer8)),buflen:this._bufferLength,length:this._dataLength,state:[$[0],$[1],$[2],$[3]]}}setState($){let{buffer:k,state:J}=$,Z=this._state,X;for(this._dataLength=$.length,this._bufferLength=$.buflen,Z[0]=J[0],Z[1]=J[1],Z[2]=J[2],Z[3]=J[3],X=0;X<k.length;X+=1)this._buffer8[X]=k.charCodeAt(X)}end($=!1){let k=this._bufferLength,J=this._buffer8,Z=this._buffer32,X=(k>>2)+1;this._dataLength+=k;let G=this._dataLength*8;if(J[k]=128,J[k+1]=J[k+2]=J[k+3]=0,Z.set(W.buffer32Identity.subarray(X),X),k>55&&(W._md5cycle(this._state,Z),Z.set(W.buffer32Identity)),G<=4294967295)Z[14]=G;else{let z=G.toString(16).match(/(.*?)(.{0,8})$/);if(z===null)return;let V=parseInt(z[2],16),w=parseInt(z[1],16)||0;Z[14]=V,Z[15]=w}return W._md5cycle(this._state,Z),$?this._state:W._hex(this._state)}},U(c1,"Md5"),s(c1,"stateIdentity",new Int32Array([1732584193,-271733879,-1732584194,271733878])),s(c1,"buffer32Identity",new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])),s(c1,"hexChars","0123456789abcdef"),s(c1,"hexOut",[]),s(c1,"onePassHasher",new c1),l6=c1}),d6={};_1(d6,{createHash:()=>d5,createHmac:()=>n5,randomBytes:()=>a5});function a5(W){return crypto.getRandomValues(t.alloc(W))}function d5(W){if(W==="sha256")return{update:U(function($){return{digest:U(function(){return t.from(C8($))},"digest")}},"update")};if(W==="md5")return{update:U(function($){return{digest:U(function(){return typeof $=="string"?l6.hashStr($):l6.hashByteArray($)},"digest")}},"update")};throw Error(`Hash type '${W}' not supported`)}function n5(W,$){if(W!=="sha256")throw Error(`Only sha256 is supported (requested: '${W}')`);return{update:U(function(k){return{digest:U(function(){typeof $=="string"&&($=new TextEncoder().encode($)),typeof k=="string"&&(k=new TextEncoder().encode(k));let J=$.length;if(J>64)$=C8($);else if(J<64){let V=new Uint8Array(64);V.set($),$=V}let Z=new Uint8Array(64),X=new Uint8Array(64);for(let V=0;V<64;V++)Z[V]=54^$[V],X[V]=92^$[V];let G=new Uint8Array(k.length+64);G.set(Z,0),G.set(k,64);let z=new Uint8Array(96);return z.set(X,0),z.set(C8(G),64),t.from(C8(z))},"digest")}},"update")}}var o5=tW(()=>{l(),tk(),sk(),U(a5,"randomBytes"),U(d5,"createHash"),U(n5,"createHmac")}),T4=r((W,$)=>{l(),$.exports={host:"localhost",user:o.platform==="win32"?o.env.USERNAME:o.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:30000,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var k=f4(),J=k.getTypeParser(20,"text"),Z=k.getTypeParser(1016,"text");$.exports.__defineSetter__("parseInt8",function(X){k.setTypeParser(20,"text",X?k.getTypeParser(23,"text"):J),k.setTypeParser(1016,"text",X?k.getTypeParser(1007,"text"):Z)})}),E4=r((W,$)=>{l();var k=(o5(),QW(d6)),J=T4();function Z(F){var M=F.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");return'"'+M+'"'}U(Z,"escapeElement");function X(F){for(var M="{",P=0;P<F.length;P++)P>0&&(M=M+","),F[P]===null||typeof F[P]>"u"?M=M+"NULL":Array.isArray(F[P])?M=M+X(F[P]):F[P]instanceof t?M+="\\\\x"+F[P].toString("hex"):M+=Z(G(F[P]));return M=M+"}",M}U(X,"arrayString");var G=U(function(F,M){if(F==null)return null;if(F instanceof t)return F;if(ArrayBuffer.isView(F)){var P=t.from(F.buffer,F.byteOffset,F.byteLength);return P.length===F.byteLength?P:P.slice(F.byteOffset,F.byteOffset+F.byteLength)}return F instanceof Date?J.parseInputDatesAsUTC?R(F):w(F):Array.isArray(F)?X(F):typeof F=="object"?z(F,M):F.toString()},"prepareValue");function z(F,M){if(F&&typeof F.toPostgres=="function"){if(M=M||[],M.indexOf(F)!==-1)throw Error('circular reference detected while preparing "'+F+'" for query');return M.push(F),G(F.toPostgres(G),M)}return JSON.stringify(F)}U(z,"prepareObject");function V(F,M){for(F=""+F;F.length<M;)F="0"+F;return F}U(V,"pad");function w(F){var M=-F.getTimezoneOffset(),P=F.getFullYear(),f=P<1;f&&(P=Math.abs(P)+1);var T=V(P,4)+"-"+V(F.getMonth()+1,2)+"-"+V(F.getDate(),2)+"T"+V(F.getHours(),2)+":"+V(F.getMinutes(),2)+":"+V(F.getSeconds(),2)+"."+V(F.getMilliseconds(),3);return M<0?(T+="-",M*=-1):T+="+",T+=V(Math.floor(M/60),2)+":"+V(M%60,2),f&&(T+=" BC"),T}U(w,"dateToString");function R(F){var M=F.getUTCFullYear(),P=M<1;P&&(M=Math.abs(M)+1);var f=V(M,4)+"-"+V(F.getUTCMonth()+1,2)+"-"+V(F.getUTCDate(),2)+"T"+V(F.getUTCHours(),2)+":"+V(F.getUTCMinutes(),2)+":"+V(F.getUTCSeconds(),2)+"."+V(F.getUTCMilliseconds(),3);return f+="+00:00",P&&(f+=" BC"),f}U(R,"dateToStringUTC");function h(F,M,P){return F=typeof F=="string"?{text:F}:F,M&&(typeof M=="function"?F.callback=M:F.values=M),P&&(F.callback=P),F}U(h,"normalizeQueryConfig");var _=U(function(F){return k.createHash("md5").update(F,"utf-8").digest("hex")},"md5"),D=U(function(F,M,P){var f=_(M+F),T=_(t.concat([t.from(f),P]));return"md5"+T},"postgresMd5PasswordHash");$.exports={prepareValue:U(function(F){return G(F)},"prepareValueWrapper"),normalizeQueryConfig:h,postgresMd5PasswordHash:D,md5:_}}),x8={};_1(x8,{default:()=>r5});var r5,v4=tW(()=>{l(),r5={}}),ak=r((W,$)=>{l();var k=(o5(),QW(d6));function J(M){if(M.indexOf("SCRAM-SHA-256")===-1)throw Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let P=k.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:P,response:"n,,n=*,r="+P,message:"SASLInitialResponse"}}U(J,"startSession");function Z(M,P,f){if(M.message!=="SASLInitialResponse")throw Error("SASL: Last message was not SASLInitialResponse");if(typeof P!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(typeof f!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let T=w(f);if(T.nonce.startsWith(M.clientNonce)){if(T.nonce.length===M.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var S=t.from(T.salt,"base64"),q=F(P,S,T.iteration),Q=D(q,"Client Key"),E=_(Q),j="n=*,r="+M.clientNonce,A="r="+T.nonce+",s="+T.salt+",i="+T.iteration,N="c=biws,r="+T.nonce,b=j+","+A+","+N,C=D(E,b),u=h(Q,C),c=u.toString("base64"),B=D(q,"Server Key"),m=D(B,b);M.message="SASLResponse",M.serverSignature=m.toString("base64"),M.response=N+",p="+c}U(Z,"continueSession");function X(M,P){if(M.message!=="SASLResponse")throw Error("SASL: Last message was not SASLResponse");if(typeof P!="string")throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:f}=R(P);if(f!==M.serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}U(X,"finalizeSession");function G(M){if(typeof M!="string")throw TypeError("SASL: text must be a string");return M.split("").map((P,f)=>M.charCodeAt(f)).every((P)=>P>=33&&P<=43||P>=45&&P<=126)}U(G,"isPrintableChars");function z(M){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(M)}U(z,"isBase64");function V(M){if(typeof M!="string")throw TypeError("SASL: attribute pairs text must be a string");return new Map(M.split(",").map((P)=>{if(!/^.=/.test(P))throw Error("SASL: Invalid attribute pair entry");let f=P[0],T=P.substring(2);return[f,T]}))}U(V,"parseAttributePairs");function w(M){let P=V(M),f=P.get("r");if(f){if(!G(f))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let T=P.get("s");if(T){if(!z(T))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let S=P.get("i");if(S){if(!/^[1-9][0-9]*$/.test(S))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let q=parseInt(S,10);return{nonce:f,salt:T,iteration:q}}U(w,"parseServerFirstMessage");function R(M){let P=V(M).get("v");if(P){if(!z(P))throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:P}}U(R,"parseServerFinalMessage");function h(M,P){if(!t.isBuffer(M))throw TypeError("first argument must be a Buffer");if(!t.isBuffer(P))throw TypeError("second argument must be a Buffer");if(M.length!==P.length)throw Error("Buffer lengths must match");if(M.length===0)throw Error("Buffers cannot be empty");return t.from(M.map((f,T)=>M[T]^P[T]))}U(h,"xorBuffers");function _(M){return k.createHash("sha256").update(M).digest()}U(_,"sha256");function D(M,P){return k.createHmac("sha256",M).update(P).digest()}U(D,"hmacSha256");function F(M,P,f){for(var T=D(M,t.concat([P,t.from([0,0,0,1])])),S=T,q=0;q<f-1;q++)T=D(M,T),S=h(S,T);return S}U(F,"Hi"),$.exports={startSession:J,continueSession:Z,finalizeSession:X}}),n6={};_1(n6,{join:()=>e5});function e5(...W){return W.join("/")}var W7=tW(()=>{l(),U(e5,"join")}),o6={};_1(o6,{stat:()=>$7});function $7(W,$){$(Error("No filesystem"))}var k7=tW(()=>{l(),U($7,"stat")}),r6={};_1(r6,{default:()=>J7});var J7,Z7=tW(()=>{l(),J7={}}),X7={};_1(X7,{StringDecoder:()=>Y7});var u6,Y7,dk=tW(()=>{l(),u6=class{constructor($){s(this,"td"),this.td=new TextDecoder($)}write($){return this.td.decode($,{stream:!0})}end($){return this.td.decode($)}},U(u6,"StringDecoder"),Y7=u6}),nk=r((W,$)=>{l();var{Transform:k}=(Z7(),QW(r6)),{StringDecoder:J}=(dk(),QW(X7)),Z=Symbol("last"),X=Symbol("decoder");function G(h,_,D){let F;if(this.overflow){if(F=this[X].write(h).split(this.matcher),F.length===1)return D();F.shift(),this.overflow=!1}else this[Z]+=this[X].write(h),F=this[Z].split(this.matcher);this[Z]=F.pop();for(let M=0;M<F.length;M++)try{V(this,this.mapper(F[M]))}catch(P){return D(P)}if(this.overflow=this[Z].length>this.maxLength,this.overflow&&!this.skipOverflow){D(Error("maximum buffer reached"));return}D()}U(G,"transform");function z(h){if(this[Z]+=this[X].end(),this[Z])try{V(this,this.mapper(this[Z]))}catch(_){return h(_)}h()}U(z,"flush");function V(h,_){_!==void 0&&h.push(_)}U(V,"push");function w(h){return h}U(w,"noop");function R(h,_,D){switch(h=h||/\r?\n/,_=_||w,D=D||{},arguments.length){case 1:typeof h=="function"?(_=h,h=/\r?\n/):typeof h=="object"&&!(h instanceof RegExp)&&!h[Symbol.split]&&(D=h,h=/\r?\n/);break;case 2:typeof h=="function"?(D=_,_=h,h=/\r?\n/):typeof _=="object"&&(D=_,_=w)}D=Object.assign({},D),D.autoDestroy=!0,D.transform=G,D.flush=z,D.readableObjectMode=!0;let F=new k(D);return F[Z]="",F[X]=new J("utf8"),F.matcher=h,F.mapper=_,F.maxLength=D.maxLength,F.skipOverflow=D.skipOverflow||!1,F.overflow=!1,F._destroy=function(M,P){this._writableState.errorEmitted=!1,P(M)},F}U(R,"split"),$.exports=R}),ok=r((W,$)=>{l();var k=(W7(),QW(n6)),J=(Z7(),QW(r6)).Stream,Z=nk(),X=(v4(),QW(x8)),G=5432,z=o.platform==="win32",V=o.stderr,w=56,R=7,h=61440,_=32768;function D(Q){return(Q&h)==_}U(D,"isRegFile");var F=["host","port","database","user","password"],M=F.length,P=F[M-1];function f(){var Q=V instanceof J&&V.writable===!0;if(Q){var E=Array.prototype.slice.call(arguments).concat(`
28
- `);V.write(X.format.apply(X,E))}}U(f,"warn"),Object.defineProperty($.exports,"isWin",{get:U(function(){return z},"get"),set:U(function(Q){z=Q},"set")}),$.exports.warnTo=function(Q){var E=V;return V=Q,E},$.exports.getFileName=function(Q){var E=Q||o.env,j=E.PGPASSFILE||(z?k.join(E.APPDATA||"./","postgresql","pgpass.conf"):k.join(E.HOME||"./",".pgpass"));return j},$.exports.usePgPass=function(Q,E){return Object.prototype.hasOwnProperty.call(o.env,"PGPASSWORD")?!1:z?!0:(E=E||"<unkn>",D(Q.mode)?Q.mode&(w|R)?(f('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',E),!1):!0:(f('WARNING: password file "%s" is not a plain file',E),!1))};var T=$.exports.match=function(Q,E){return F.slice(0,-1).reduce(function(j,A,N){return N==1&&Number(Q[A]||G)===Number(E[A])?j&&!0:j&&(E[A]==="*"||E[A]===Q[A])},!0)};$.exports.getPassword=function(Q,E,j){var A,N=E.pipe(Z());function b(c){var B=S(c);B&&q(B)&&T(Q,B)&&(A=B[P],N.end())}U(b,"onLine");var C=U(function(){E.destroy(),j(A)},"onEnd"),u=U(function(c){E.destroy(),f("WARNING: error on reading file: %s",c),j(void 0)},"onErr");E.on("error",u),N.on("data",b).on("end",C).on("error",u)};var S=$.exports.parseLine=function(Q){if(Q.length<11||Q.match(/^\s+#/))return null;for(var E="",j="",A=0,N=0,b=0,C={},u=!1,c=U(function(m,p,a){var JW=Q.substring(p,a);Object.hasOwnProperty.call(o.env,"PGPASS_NO_DEESCAPE")||(JW=JW.replace(/\\([:\\])/g,"$1")),C[F[m]]=JW},"addToObj"),B=0;B<Q.length-1;B+=1){if(E=Q.charAt(B+1),j=Q.charAt(B),u=A==M-1,u){c(A,N);break}B>=0&&E==":"&&j!=="\\"&&(c(A,N,B+1),N=B+2,A+=1)}return C=Object.keys(C).length===M?C:null,C},q=$.exports.isValidEntry=function(Q){for(var E={0:function(C){return C.length>0},1:function(C){return C==="*"?!0:(C=Number(C),isFinite(C)&&C>0&&C<9007199254740992&&Math.floor(C)===C)},2:function(C){return C.length>0},3:function(C){return C.length>0},4:function(C){return C.length>0}},j=0;j<F.length;j+=1){var A=E[j],N=Q[F[j]]||"",b=A(N);if(!b)return!1}return!0}}),rk=r((W,$)=>{l();var k=(W7(),QW(n6)),J=(k7(),QW(o6)),Z=ok();$.exports=function(X,G){var z=Z.getFileName();J.stat(z,function(V,w){if(V||!Z.usePgPass(w,z))return G(void 0);var R=J.createReadStream(z);Z.getPassword(X,R,G)})},$.exports.warnTo=Z.warnTo}),H7={};_1(H7,{default:()=>z7});var z7,ek=tW(()=>{l(),z7={}}),W2=r((W,$)=>{l();var k=(p5(),QW(i5)),J=(k7(),QW(o6));function Z(X){if(X.charAt(0)==="/"){var z=X.split(" ");return{host:z[0],database:z[1]}}var G=k.parse(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(X)?encodeURI(X).replace(/\%25(\d\d)/g,"%$1"):X,!0),z=G.query;for(var V in z)Array.isArray(z[V])&&(z[V]=z[V][z[V].length-1]);var w=(G.auth||":").split(":");if(z.user=w[0],z.password=w.splice(1).join(":"),z.port=G.port,G.protocol=="socket:")return z.host=decodeURI(G.pathname),z.database=G.query.db,z.client_encoding=G.query.encoding,z;z.host||(z.host=G.hostname);var R=G.pathname;if(!z.host&&R&&/^%2f/i.test(R)){var h=R.split("/");z.host=decodeURIComponent(h[0]),R=h.splice(1).join("/")}switch(R&&R.charAt(0)==="/"&&(R=R.slice(1)||null),z.database=R&&decodeURI(R),(z.ssl==="true"||z.ssl==="1")&&(z.ssl=!0),z.ssl==="0"&&(z.ssl=!1),(z.sslcert||z.sslkey||z.sslrootcert||z.sslmode)&&(z.ssl={}),z.sslcert&&(z.ssl.cert=J.readFileSync(z.sslcert).toString()),z.sslkey&&(z.ssl.key=J.readFileSync(z.sslkey).toString()),z.sslrootcert&&(z.ssl.ca=J.readFileSync(z.sslrootcert).toString()),z.sslmode){case"disable":{z.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{z.ssl.rejectUnauthorized=!1;break}}return z}U(Z,"parse"),$.exports=Z,Z.parse=Z}),e6=r((W,$)=>{l();var k=(ek(),QW(H7)),J=T4(),Z=W2().parse,X=U(function(h,_,D){return D===void 0?D=o.env["PG"+h.toUpperCase()]:D===!1||(D=o.env[D]),_[h]||D||J[h]},"val"),G=U(function(){switch(o.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return J.ssl},"readSSLConfigFromEnvironment"),z=U(function(h){return"'"+(""+h).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),V=U(function(h,_,D){var F=_[D];F!=null&&h.push(D+"="+z(F))},"add"),w=class{constructor(_){_=typeof _=="string"?Z(_):_||{},_.connectionString&&(_=Object.assign({},_,Z(_.connectionString))),this.user=X("user",_),this.database=X("database",_),this.database===void 0&&(this.database=this.user),this.port=parseInt(X("port",_),10),this.host=X("host",_),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:X("password",_)}),this.binary=X("binary",_),this.options=X("options",_),this.ssl=typeof _.ssl>"u"?G():_.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=X("client_encoding",_),this.replication=X("replication",_),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=X("application_name",_,"PGAPPNAME"),this.fallback_application_name=X("fallback_application_name",_,!1),this.statement_timeout=X("statement_timeout",_,!1),this.lock_timeout=X("lock_timeout",_,!1),this.idle_in_transaction_session_timeout=X("idle_in_transaction_session_timeout",_,!1),this.query_timeout=X("query_timeout",_,!1),_.connectionTimeoutMillis===void 0?this.connect_timeout=o.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(_.connectionTimeoutMillis/1000),_.keepAlive===!1?this.keepalives=0:_.keepAlive===!0&&(this.keepalives=1),typeof _.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(_.keepAliveInitialDelayMillis/1000))}getLibpqConnectionString(_){var D=[];V(D,this,"user"),V(D,this,"password"),V(D,this,"port"),V(D,this,"application_name"),V(D,this,"fallback_application_name"),V(D,this,"connect_timeout"),V(D,this,"options");var F=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(V(D,F,"sslmode"),V(D,F,"sslca"),V(D,F,"sslkey"),V(D,F,"sslcert"),V(D,F,"sslrootcert"),this.database&&D.push("dbname="+z(this.database)),this.replication&&D.push("replication="+z(this.replication)),this.host&&D.push("host="+z(this.host)),this.isDomainSocket)return _(null,D.join(" "));this.client_encoding&&D.push("client_encoding="+z(this.client_encoding)),k.lookup(this.host,function(M,P){return M?_(M,null):(D.push("hostaddr="+z(P)),_(null,D.join(" ")))})}};U(w,"ConnectionParameters");var R=w;$.exports=R}),$2=r((W,$)=>{l();var k=f4(),J=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,Z=class{constructor(z,V){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=V,this.RowCtor=null,this.rowAsArray=z==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray)}addCommandComplete(z){var V;z.text?V=J.exec(z.text):V=J.exec(z.command),V&&(this.command=V[1],V[3]?(this.oid=parseInt(V[2],10),this.rowCount=parseInt(V[3],10)):V[2]&&(this.rowCount=parseInt(V[2],10)))}_parseRowAsArray(z){for(var V=Array(z.length),w=0,R=z.length;w<R;w++){var h=z[w];h!==null?V[w]=this._parsers[w](h):V[w]=null}return V}parseRow(z){for(var V={},w=0,R=z.length;w<R;w++){var h=z[w],_=this.fields[w].name;h!==null?V[_]=this._parsers[w](h):V[_]=null}return V}addRow(z){this.rows.push(z)}addFields(z){this.fields=z,this.fields.length&&(this._parsers=Array(z.length));for(var V=0;V<z.length;V++){var w=z[V];this._types?this._parsers[V]=this._types.getTypeParser(w.dataTypeID,w.format||"text"):this._parsers[V]=k.getTypeParser(w.dataTypeID,w.format||"text")}}};U(Z,"Result");var X=Z;$.exports=X}),k2=r((W,$)=>{l();var{EventEmitter:k}=F0(),J=$2(),Z=E4(),X=class extends k{constructor(V,w,R){super(),V=Z.normalizeQueryConfig(V,w,R),this.text=V.text,this.values=V.values,this.rows=V.rows,this.types=V.types,this.name=V.name,this.binary=V.binary,this.portal=V.portal||"",this.callback=V.callback,this._rowMode=V.rowMode,o.domain&&V.callback&&(this.callback=o.domain.bind(V.callback)),this._result=new J(this._rowMode,this.types),this._results=this._result,this.isPreparedStatement=!1,this._canceledDueToError=!1,this._promise=null}requiresPreparation(){return this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new J(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(V){this._checkForMultirow(),this._result.addFields(V.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(V){let w;if(!this._canceledDueToError){try{w=this._result.parseRow(V.fields)}catch(R){this._canceledDueToError=R;return}this.emit("row",w,this._result),this._accumulateRows&&this._result.addRow(w)}}handleCommandComplete(V,w){this._checkForMultirow(),this._result.addCommandComplete(V),this.rows&&w.sync()}handleEmptyQuery(V){this.rows&&V.sync()}handleError(V,w){if(this._canceledDueToError&&(V=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(V);this.emit("error",V)}handleReadyForQuery(V){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,V);if(this.callback)try{this.callback(null,this._results)}catch(w){o.nextTick(()=>{throw w})}this.emit("end",this._results)}submit(V){if(typeof this.text!="string"&&typeof this.name!="string")return Error("A query must have either text or a name. Supplying neither is unsupported.");let w=V.parsedStatements[this.name];return this.text&&w&&this.text!==w?Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`):this.values&&!Array.isArray(this.values)?Error("Query values must be an array"):(this.requiresPreparation()?this.prepare(V):V.query(this.text),null)}hasBeenParsed(V){return this.name&&V.parsedStatements[this.name]}handlePortalSuspended(V){this._getRows(V,this.rows)}_getRows(V,w){V.execute({portal:this.portal,rows:w}),w?V.flush():V.sync()}prepare(V){this.isPreparedStatement=!0,this.hasBeenParsed(V)||V.parse({text:this.text,name:this.name,types:this.types});try{V.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:Z.prepareValue})}catch(w){this.handleError(w,V);return}V.describe({type:"P",name:this.portal||""}),this._getRows(V,this.rows)}handleCopyInResponse(V){V.sendCopyFail("No source stream defined")}handleCopyData(V,w){}};U(X,"Query");var G=X;$.exports=G}),G7=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.NoticeMessage=W.DataRowMessage=W.CommandCompleteMessage=W.ReadyForQueryMessage=W.NotificationResponseMessage=W.BackendKeyDataMessage=W.AuthenticationMD5Password=W.ParameterStatusMessage=W.ParameterDescriptionMessage=W.RowDescriptionMessage=W.Field=W.CopyResponse=W.CopyDataMessage=W.DatabaseError=W.copyDone=W.emptyQuery=W.replicationStart=W.portalSuspended=W.noData=W.closeComplete=W.bindComplete=W.parseComplete=void 0,W.parseComplete={name:"parseComplete",length:5},W.bindComplete={name:"bindComplete",length:5},W.closeComplete={name:"closeComplete",length:5},W.noData={name:"noData",length:5},W.portalSuspended={name:"portalSuspended",length:5},W.replicationStart={name:"replicationStart",length:4},W.emptyQuery={name:"emptyQuery",length:4},W.copyDone={name:"copyDone",length:4};var $=class extends Error{constructor(B,m,p){super(B),this.length=m,this.name=p}};U($,"DatabaseError");var k=$;W.DatabaseError=k;var J=class{constructor(B,m){this.length=B,this.chunk=m,this.name="copyData"}};U(J,"CopyDataMessage");var Z=J;W.CopyDataMessage=Z;var X=class{constructor(B,m,p,a){this.length=B,this.name=m,this.binary=p,this.columnTypes=Array(a)}};U(X,"CopyResponse");var G=X;W.CopyResponse=G;var z=class{constructor(B,m,p,a,JW,n,sW){this.name=B,this.tableID=m,this.columnID=p,this.dataTypeID=a,this.dataTypeSize=JW,this.dataTypeModifier=n,this.format=sW}};U(z,"Field");var V=z;W.Field=V;var w=class{constructor(B,m){this.length=B,this.fieldCount=m,this.name="rowDescription",this.fields=Array(this.fieldCount)}};U(w,"RowDescriptionMessage");var R=w;W.RowDescriptionMessage=R;var h=class{constructor(B,m){this.length=B,this.parameterCount=m,this.name="parameterDescription",this.dataTypeIDs=Array(this.parameterCount)}};U(h,"ParameterDescriptionMessage");var _=h;W.ParameterDescriptionMessage=_;var D=class{constructor(B,m,p){this.length=B,this.parameterName=m,this.parameterValue=p,this.name="parameterStatus"}};U(D,"ParameterStatusMessage");var F=D;W.ParameterStatusMessage=F;var M=class{constructor(B,m){this.length=B,this.salt=m,this.name="authenticationMD5Password"}};U(M,"AuthenticationMD5Password");var P=M;W.AuthenticationMD5Password=P;var f=class{constructor(B,m,p){this.length=B,this.processID=m,this.secretKey=p,this.name="backendKeyData"}};U(f,"BackendKeyDataMessage");var T=f;W.BackendKeyDataMessage=T;var S=class{constructor(B,m,p,a){this.length=B,this.processId=m,this.channel=p,this.payload=a,this.name="notification"}};U(S,"NotificationResponseMessage");var q=S;W.NotificationResponseMessage=q;var Q=class{constructor(B,m){this.length=B,this.status=m,this.name="readyForQuery"}};U(Q,"ReadyForQueryMessage");var E=Q;W.ReadyForQueryMessage=E;var j=class{constructor(B,m){this.length=B,this.text=m,this.name="commandComplete"}};U(j,"CommandCompleteMessage");var A=j;W.CommandCompleteMessage=A;var N=class{constructor(B,m){this.length=B,this.fields=m,this.name="dataRow",this.fieldCount=m.length}};U(N,"DataRowMessage");var b=N;W.DataRowMessage=b;var C=class{constructor(B,m){this.length=B,this.message=m,this.name="notice"}};U(C,"NoticeMessage");var u=C;W.NoticeMessage=u}),J2=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.Writer=void 0;var $=class{constructor(Z=256){this.size=Z,this.offset=5,this.headerPosition=0,this.buffer=t.allocUnsafe(Z)}ensure(Z){if(this.buffer.length-this.offset<Z){let X=this.buffer,G=X.length+(X.length>>1)+Z;this.buffer=t.allocUnsafe(G),X.copy(this.buffer)}}addInt32(Z){return this.ensure(4),this.buffer[this.offset++]=Z>>>24&255,this.buffer[this.offset++]=Z>>>16&255,this.buffer[this.offset++]=Z>>>8&255,this.buffer[this.offset++]=Z>>>0&255,this}addInt16(Z){return this.ensure(2),this.buffer[this.offset++]=Z>>>8&255,this.buffer[this.offset++]=Z>>>0&255,this}addCString(Z){if(!Z)this.ensure(1);else{let X=t.byteLength(Z);this.ensure(X+1),this.buffer.write(Z,this.offset,"utf-8"),this.offset+=X}return this.buffer[this.offset++]=0,this}addString(Z=""){let X=t.byteLength(Z);return this.ensure(X),this.buffer.write(Z,this.offset),this.offset+=X,this}add(Z){return this.ensure(Z.length),Z.copy(this.buffer,this.offset),this.offset+=Z.length,this}join(Z){if(Z){this.buffer[this.headerPosition]=Z;let X=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(X,this.headerPosition+1)}return this.buffer.slice(Z?0:5,this.offset)}flush(Z){let X=this.join(Z);return this.offset=5,this.headerPosition=0,this.buffer=t.allocUnsafe(this.size),X}};U($,"Writer");var k=$;W.Writer=k}),Z2=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.serialize=void 0;var $=J2(),k=new $.Writer,J=U((B)=>{k.addInt16(3).addInt16(0);for(let a of Object.keys(B))k.addCString(a).addCString(B[a]);k.addCString("client_encoding").addCString("UTF8");let m=k.addCString("").flush(),p=m.length+4;return new $.Writer().addInt32(p).add(m).flush()},"startup"),Z=U(()=>{let B=t.allocUnsafe(8);return B.writeInt32BE(8,0),B.writeInt32BE(80877103,4),B},"requestSsl"),X=U((B)=>k.addCString(B).flush(112),"password"),G=U(function(B,m){return k.addCString(B).addInt32(t.byteLength(m)).addString(m),k.flush(112)},"sendSASLInitialResponseMessage"),z=U(function(B){return k.addString(B).flush(112)},"sendSCRAMClientFinalMessage"),V=U((B)=>k.addCString(B).flush(81),"query"),w=[],R=U((B)=>{let m=B.name||"";m.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",m,m.length),console.error("This can cause conflicts and silent errors executing queries"));let p=B.types||w,a=p.length,JW=k.addCString(m).addCString(B.text).addInt16(a);for(let n=0;n<a;n++)JW.addInt32(p[n]);return k.flush(80)},"parse"),h=new $.Writer,_=U(function(B,m){for(let p=0;p<B.length;p++){let a=m?m(B[p],p):B[p];a==null?(k.addInt16(0),h.addInt32(-1)):a instanceof t?(k.addInt16(1),h.addInt32(a.length),h.add(a)):(k.addInt16(0),h.addInt32(t.byteLength(a)),h.addString(a))}},"writeValues"),D=U((B={})=>{let m=B.portal||"",p=B.statement||"",a=B.binary||!1,JW=B.values||w,n=JW.length;return k.addCString(m).addCString(p),k.addInt16(n),_(JW,B.valueMapper),k.addInt16(n),k.add(h.flush()),k.addInt16(a?1:0),k.flush(66)},"bind"),F=t.from([69,0,0,0,9,0,0,0,0,0]),M=U((B)=>{if(!B||!B.portal&&!B.rows)return F;let m=B.portal||"",p=B.rows||0,a=t.byteLength(m),JW=4+a+1+4,n=t.allocUnsafe(1+JW);return n[0]=69,n.writeInt32BE(JW,1),n.write(m,5,"utf-8"),n[a+5]=0,n.writeUInt32BE(p,n.length-4),n},"execute"),P=U((B,m)=>{let p=t.allocUnsafe(16);return p.writeInt32BE(16,0),p.writeInt16BE(1234,4),p.writeInt16BE(5678,6),p.writeInt32BE(B,8),p.writeInt32BE(m,12),p},"cancel"),f=U((B,m)=>{let p=4+t.byteLength(m)+1,a=t.allocUnsafe(1+p);return a[0]=B,a.writeInt32BE(p,1),a.write(m,5,"utf-8"),a[p]=0,a},"cstringMessage"),T=k.addCString("P").flush(68),S=k.addCString("S").flush(68),q=U((B)=>B.name?f(68,`${B.type}${B.name||""}`):B.type==="P"?T:S,"describe"),Q=U((B)=>{let m=`${B.type}${B.name||""}`;return f(67,m)},"close"),E=U((B)=>k.add(B).flush(100),"copyData"),j=U((B)=>f(102,B),"copyFail"),A=U((B)=>t.from([B,0,0,0,4]),"codeOnlyBuffer"),N=A(72),b=A(83),C=A(88),u=A(99),c={startup:J,password:X,requestSsl:Z,sendSASLInitialResponseMessage:G,sendSCRAMClientFinalMessage:z,query:V,parse:R,bind:D,execute:M,describe:q,close:Q,flush:U(()=>N,"flush"),sync:U(()=>b,"sync"),end:U(()=>C,"end"),copyData:E,copyDone:U(()=>u,"copyDone"),copyFail:j,cancel:P};W.serialize=c}),X2=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.BufferReader=void 0;var $=t.allocUnsafe(0),k=class{constructor(X=0){this.offset=X,this.buffer=$,this.encoding="utf-8"}setBuffer(X,G){this.offset=X,this.buffer=G}int16(){let X=this.buffer.readInt16BE(this.offset);return this.offset+=2,X}byte(){let X=this.buffer[this.offset];return this.offset++,X}int32(){let X=this.buffer.readInt32BE(this.offset);return this.offset+=4,X}uint32(){let X=this.buffer.readUInt32BE(this.offset);return this.offset+=4,X}string(X){let G=this.buffer.toString(this.encoding,this.offset,this.offset+X);return this.offset+=X,G}cstring(){let X=this.offset,G=X;for(;this.buffer[G++]!==0;);return this.offset=G,this.buffer.toString(this.encoding,X,G-1)}bytes(X){let G=this.buffer.slice(this.offset,this.offset+X);return this.offset+=X,G}};U(k,"BufferReader");var J=k;W.BufferReader=J}),Y2=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.Parser=void 0;var $=G7(),k=X2(),J=1,Z=4,X=J+Z,G=t.allocUnsafe(0),z=class{constructor(R){if(this.buffer=G,this.bufferLength=0,this.bufferOffset=0,this.reader=new k.BufferReader,R?.mode==="binary")throw Error("Binary mode not supported yet");this.mode=R?.mode||"text"}parse(R,h){this.mergeBuffer(R);let _=this.bufferOffset+this.bufferLength,D=this.bufferOffset;for(;D+X<=_;){let F=this.buffer[D],M=this.buffer.readUInt32BE(D+J),P=J+M;if(P+D<=_){let f=this.handlePacket(D+X,F,M,this.buffer);h(f),D+=P}else break}D===_?(this.buffer=G,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=_-D,this.bufferOffset=D)}mergeBuffer(R){if(this.bufferLength>0){let h=this.bufferLength+R.byteLength;if(h+this.bufferOffset>this.buffer.byteLength){let _;if(h<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)_=this.buffer;else{let D=this.buffer.byteLength*2;for(;h>=D;)D*=2;_=t.allocUnsafe(D)}this.buffer.copy(_,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=_,this.bufferOffset=0}R.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=h}else this.buffer=R,this.bufferOffset=0,this.bufferLength=R.byteLength}handlePacket(R,h,_,D){switch(h){case 50:return $.bindComplete;case 49:return $.parseComplete;case 51:return $.closeComplete;case 110:return $.noData;case 115:return $.portalSuspended;case 99:return $.copyDone;case 87:return $.replicationStart;case 73:return $.emptyQuery;case 68:return this.parseDataRowMessage(R,_,D);case 67:return this.parseCommandCompleteMessage(R,_,D);case 90:return this.parseReadyForQueryMessage(R,_,D);case 65:return this.parseNotificationMessage(R,_,D);case 82:return this.parseAuthenticationResponse(R,_,D);case 83:return this.parseParameterStatusMessage(R,_,D);case 75:return this.parseBackendKeyData(R,_,D);case 69:return this.parseErrorMessage(R,_,D,"error");case 78:return this.parseErrorMessage(R,_,D,"notice");case 84:return this.parseRowDescriptionMessage(R,_,D);case 116:return this.parseParameterDescriptionMessage(R,_,D);case 71:return this.parseCopyInMessage(R,_,D);case 72:return this.parseCopyOutMessage(R,_,D);case 100:return this.parseCopyData(R,_,D);default:return new $.DatabaseError("received invalid response: "+h.toString(16),_,"error")}}parseReadyForQueryMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.string(1);return new $.ReadyForQueryMessage(h,D)}parseCommandCompleteMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.cstring();return new $.CommandCompleteMessage(h,D)}parseCopyData(R,h,_){let D=_.slice(R,R+(h-4));return new $.CopyDataMessage(h,D)}parseCopyInMessage(R,h,_){return this.parseCopyMessage(R,h,_,"copyInResponse")}parseCopyOutMessage(R,h,_){return this.parseCopyMessage(R,h,_,"copyOutResponse")}parseCopyMessage(R,h,_,D){this.reader.setBuffer(R,_);let F=this.reader.byte()!==0,M=this.reader.int16(),P=new $.CopyResponse(h,D,F,M);for(let f=0;f<M;f++)P.columnTypes[f]=this.reader.int16();return P}parseNotificationMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int32(),F=this.reader.cstring(),M=this.reader.cstring();return new $.NotificationResponseMessage(h,D,F,M)}parseRowDescriptionMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int16(),F=new $.RowDescriptionMessage(h,D);for(let M=0;M<D;M++)F.fields[M]=this.parseField();return F}parseField(){let R=this.reader.cstring(),h=this.reader.uint32(),_=this.reader.int16(),D=this.reader.uint32(),F=this.reader.int16(),M=this.reader.int32(),P=this.reader.int16()===0?"text":"binary";return new $.Field(R,h,_,D,F,M,P)}parseParameterDescriptionMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int16(),F=new $.ParameterDescriptionMessage(h,D);for(let M=0;M<D;M++)F.dataTypeIDs[M]=this.reader.int32();return F}parseDataRowMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int16(),F=Array(D);for(let M=0;M<D;M++){let P=this.reader.int32();F[M]=P===-1?null:this.reader.string(P)}return new $.DataRowMessage(h,F)}parseParameterStatusMessage(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.cstring(),F=this.reader.cstring();return new $.ParameterStatusMessage(h,D,F)}parseBackendKeyData(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int32(),F=this.reader.int32();return new $.BackendKeyDataMessage(h,D,F)}parseAuthenticationResponse(R,h,_){this.reader.setBuffer(R,_);let D=this.reader.int32(),F={name:"authenticationOk",length:h};switch(D){case 0:break;case 3:F.length===8&&(F.name="authenticationCleartextPassword");break;case 5:if(F.length===12){F.name="authenticationMD5Password";let M=this.reader.bytes(4);return new $.AuthenticationMD5Password(h,M)}break;case 10:{F.name="authenticationSASL",F.mechanisms=[];let M;do M=this.reader.cstring(),M&&F.mechanisms.push(M);while(M)}break;case 11:F.name="authenticationSASLContinue",F.data=this.reader.string(h-8);break;case 12:F.name="authenticationSASLFinal",F.data=this.reader.string(h-8);break;default:throw Error("Unknown authenticationOk message type "+D)}return F}parseErrorMessage(R,h,_,D){this.reader.setBuffer(R,_);let F={},M=this.reader.string(1);for(;M!=="\x00";)F[M]=this.reader.cstring(),M=this.reader.string(1);let P=F.M,f=D==="notice"?new $.NoticeMessage(h,P):new $.DatabaseError(P,h,D);return f.severity=F.S,f.code=F.C,f.detail=F.D,f.hint=F.H,f.position=F.P,f.internalPosition=F.p,f.internalQuery=F.q,f.where=F.W,f.schema=F.s,f.table=F.t,f.column=F.c,f.dataType=F.d,f.constraint=F.n,f.file=F.F,f.line=F.L,f.routine=F.R,f}};U(z,"Parser");var V=z;W.Parser=V}),M7=r((W)=>{l(),Object.defineProperty(W,"__esModule",{value:!0}),W.DatabaseError=W.serialize=W.parse=void 0;var $=G7();Object.defineProperty(W,"DatabaseError",{enumerable:!0,get:U(function(){return $.DatabaseError},"get")});var k=Z2();Object.defineProperty(W,"serialize",{enumerable:!0,get:U(function(){return k.serialize},"get")});var J=Y2();function Z(X,G){let z=new J.Parser;return X.on("data",(V)=>z.parse(V,G)),new Promise((V)=>X.on("end",()=>V()))}U(Z,"parse"),W.parse=Z}),L7={};_1(L7,{connect:()=>K7});function K7({socket:W,servername:$}){return W.startTls($),W}var H2=tW(()=>{l(),U(K7,"connect")}),U7=r((W,$)=>{l();var k=(Q8(),QW(u5)),J=F0().EventEmitter,{parse:Z,serialize:X}=M7(),G=X.flush(),z=X.sync(),V=X.end(),w=class extends J{constructor(_){super(),_=_||{},this.stream=_.stream||new k.Socket,this._keepAlive=_.keepAlive,this._keepAliveInitialDelayMillis=_.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=_.ssl||!1,this._ending=!1,this._emitMessage=!1;var D=this;this.on("newListener",function(F){F==="message"&&(D._emitMessage=!0)})}connect(_,D){var F=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(_,D),this.stream.once("connect",function(){F._keepAlive&&F.stream.setKeepAlive(!0,F._keepAliveInitialDelayMillis),F.emit("connect")});let M=U(function(P){F._ending&&(P.code==="ECONNRESET"||P.code==="EPIPE")||F.emit("error",P)},"reportStreamError");if(this.stream.on("error",M),this.stream.on("close",function(){F.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(P){var f=P.toString("utf8");switch(f){case"S":break;case"N":return F.stream.end(),F.emit("error",Error("The server does not support SSL connections"));default:return F.stream.end(),F.emit("error",Error("There was an error establishing an SSL connection"))}var T=(H2(),QW(L7));let S={socket:F.stream};F.ssl!==!0&&(Object.assign(S,F.ssl),("key"in F.ssl)&&(S.key=F.ssl.key)),k.isIP(D)===0&&(S.servername=D);try{F.stream=T.connect(S)}catch(q){return F.emit("error",q)}F.attachListeners(F.stream),F.stream.on("error",M),F.emit("sslconnect")})}attachListeners(_){_.on("end",()=>{this.emit("end")}),Z(_,(D)=>{var F=D.name==="error"?"errorMessage":D.name;this._emitMessage&&this.emit("message",D),this.emit(F,D)})}requestSsl(){this.stream.write(X.requestSsl())}startup(_){this.stream.write(X.startup(_))}cancel(_,D){this._send(X.cancel(_,D))}password(_){this._send(X.password(_))}sendSASLInitialResponseMessage(_,D){this._send(X.sendSASLInitialResponseMessage(_,D))}sendSCRAMClientFinalMessage(_){this._send(X.sendSCRAMClientFinalMessage(_))}_send(_){return this.stream.writable?this.stream.write(_):!1}query(_){this._send(X.query(_))}parse(_){this._send(X.parse(_))}bind(_){this._send(X.bind(_))}execute(_){this._send(X.execute(_))}flush(){this.stream.writable&&this.stream.write(G)}sync(){this._ending=!0,this._send(G),this._send(z)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(V,()=>{this.stream.end()})}close(_){this._send(X.close(_))}describe(_){this._send(X.describe(_))}sendCopyFromChunk(_){this._send(X.copyData(_))}endCopyFrom(){this._send(X.copyDone())}sendCopyFail(_){this._send(X.copyFail(_))}};U(w,"Connection");var R=w;$.exports=R}),z2=r((W,$)=>{l();var k=F0().EventEmitter,J=(v4(),QW(x8)),Z=E4(),X=ak(),G=rk(),z=a6(),V=e6(),w=k2(),R=T4(),h=U7(),_=class extends k{constructor(M){super(),this.connectionParameters=new V(M),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var P=M||{};this._Promise=P.Promise||D4.Promise,this._types=new z(P.types),this._ending=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=P.connection||new h({stream:P.stream,ssl:this.connectionParameters.ssl,keepAlive:P.keepAlive||!1,keepAliveInitialDelayMillis:P.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=P.binary||R.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=P.connectionTimeoutMillis||0}_errorAllQueries(M){let P=U((f)=>{o.nextTick(()=>{f.handleError(M,this.connection)})},"enqueueError");this.activeQuery&&(P(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(P),this.queryQueue.length=0}_connect(M){var P=this,f=this.connection;if(this._connectionCallback=M,this._connecting||this._connected){let T=Error("Client has already been connected. You cannot reuse a client.");o.nextTick(()=>{M(T)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{f._ending=!0,f.stream.destroy(Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?f.connect(this.host+"/.s.PGSQL."+this.port):f.connect(this.port,this.host),f.on("connect",function(){P.ssl?f.requestSsl():f.startup(P.getStartupConf())}),f.on("sslconnect",function(){f.startup(P.getStartupConf())}),this._attachListeners(f),f.once("end",()=>{let T=this._ending?Error("Connection terminated"):Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(T),this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(T):this._handleErrorEvent(T):this._connectionError||this._handleErrorEvent(T)),o.nextTick(()=>{this.emit("end")})})}connect(M){if(M){this._connect(M);return}return new this._Promise((P,f)=>{this._connect((T)=>{T?f(T):P()})})}_attachListeners(M){M.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),M.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),M.on("authenticationSASL",this._handleAuthSASL.bind(this)),M.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),M.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),M.on("backendKeyData",this._handleBackendKeyData.bind(this)),M.on("error",this._handleErrorEvent.bind(this)),M.on("errorMessage",this._handleErrorMessage.bind(this)),M.on("readyForQuery",this._handleReadyForQuery.bind(this)),M.on("notice",this._handleNotice.bind(this)),M.on("rowDescription",this._handleRowDescription.bind(this)),M.on("dataRow",this._handleDataRow.bind(this)),M.on("portalSuspended",this._handlePortalSuspended.bind(this)),M.on("emptyQuery",this._handleEmptyQuery.bind(this)),M.on("commandComplete",this._handleCommandComplete.bind(this)),M.on("parseComplete",this._handleParseComplete.bind(this)),M.on("copyInResponse",this._handleCopyInResponse.bind(this)),M.on("copyData",this._handleCopyData.bind(this)),M.on("notification",this._handleNotification.bind(this))}_checkPgPass(M){let P=this.connection;typeof this.password=="function"?this._Promise.resolve().then(()=>this.password()).then((f)=>{if(f!==void 0){if(typeof f!="string"){P.emit("error",TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=f}else this.connectionParameters.password=this.password=null;M()}).catch((f)=>{P.emit("error",f)}):this.password!==null?M():G(this.connectionParameters,(f)=>{f!==void 0&&(this.connectionParameters.password=this.password=f),M()})}_handleAuthCleartextPassword(M){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(M){this._checkPgPass(()=>{let P=Z.postgresMd5PasswordHash(this.user,this.password,M.salt);this.connection.password(P)})}_handleAuthSASL(M){this._checkPgPass(()=>{this.saslSession=X.startSession(M.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)})}_handleAuthSASLContinue(M){X.continueSession(this.saslSession,this.password,M.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}_handleAuthSASLFinal(M){X.finalizeSession(this.saslSession,M.data),this.saslSession=null}_handleBackendKeyData(M){this.processID=M.processID,this.secretKey=M.secretKey}_handleReadyForQuery(M){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:P}=this;this.activeQuery=null,this.readyForQuery=!0,P&&P.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(M){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(M);this.emit("error",M)}}_handleErrorEvent(M){if(this._connecting)return this._handleErrorWhileConnecting(M);this._queryable=!1,this._errorAllQueries(M),this.emit("error",M)}_handleErrorMessage(M){if(this._connecting)return this._handleErrorWhileConnecting(M);let P=this.activeQuery;if(!P){this._handleErrorEvent(M);return}this.activeQuery=null,P.handleError(M,this.connection)}_handleRowDescription(M){this.activeQuery.handleRowDescription(M)}_handleDataRow(M){this.activeQuery.handleDataRow(M)}_handlePortalSuspended(M){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(M){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(M){this.activeQuery.handleCommandComplete(M,this.connection)}_handleParseComplete(M){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(M){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(M){this.activeQuery.handleCopyData(M,this.connection)}_handleNotification(M){this.emit("notification",M)}_handleNotice(M){this.emit("notice",M)}getStartupConf(){var M=this.connectionParameters,P={user:M.user,database:M.database},f=M.application_name||M.fallback_application_name;return f&&(P.application_name=f),M.replication&&(P.replication=""+M.replication),M.statement_timeout&&(P.statement_timeout=String(parseInt(M.statement_timeout,10))),M.lock_timeout&&(P.lock_timeout=String(parseInt(M.lock_timeout,10))),M.idle_in_transaction_session_timeout&&(P.idle_in_transaction_session_timeout=String(parseInt(M.idle_in_transaction_session_timeout,10))),M.options&&(P.options=M.options),P}cancel(M,P){if(M.activeQuery===P){var f=this.connection;this.host&&this.host.indexOf("/")===0?f.connect(this.host+"/.s.PGSQL."+this.port):f.connect(this.port,this.host),f.on("connect",function(){f.cancel(M.processID,M.secretKey)})}else M.queryQueue.indexOf(P)!==-1&&M.queryQueue.splice(M.queryQueue.indexOf(P),1)}setTypeParser(M,P,f){return this._types.setTypeParser(M,P,f)}getTypeParser(M,P){return this._types.getTypeParser(M,P)}escapeIdentifier(M){return'"'+M.replace(/"/g,'""')+'"'}escapeLiteral(M){for(var P=!1,f="'",T=0;T<M.length;T++){var S=M[T];S==="'"?f+=S+S:S==="\\"?(f+=S+S,P=!0):f+=S}return f+="'",P===!0&&(f=" E"+f),f}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let M=this.activeQuery.submit(this.connection);M&&o.nextTick(()=>{this.activeQuery.handleError(M,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(M,P,f){var T,S,q,Q,E;if(M==null)throw TypeError("Client was passed a null or undefined query");return typeof M.submit=="function"?(q=M.query_timeout||this.connectionParameters.query_timeout,S=T=M,typeof P=="function"&&(T.callback=T.callback||P)):(q=this.connectionParameters.query_timeout,T=new w(M,P,f),T.callback||(S=new this._Promise((j,A)=>{T.callback=(N,b)=>N?A(N):j(b)}))),q&&(E=T.callback,Q=setTimeout(()=>{var j=Error("Query read timeout");o.nextTick(()=>{T.handleError(j,this.connection)}),E(j),T.callback=()=>{};var A=this.queryQueue.indexOf(T);A>-1&&this.queryQueue.splice(A,1),this._pulseQueryQueue()},q),T.callback=(j,A)=>{clearTimeout(Q),E(j,A)}),this.binary&&!T.binary&&(T.binary=!0),T._result&&!T._result._types&&(T._result._types=this._types),this._queryable?this._ending?(o.nextTick(()=>{T.handleError(Error("Client was closed and is not queryable"),this.connection)}),S):(this.queryQueue.push(T),this._pulseQueryQueue(),S):(o.nextTick(()=>{T.handleError(Error("Client has encountered a connection error and is not queryable"),this.connection)}),S)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(M){if(this._ending=!0,!this.connection._connecting)if(M)M();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),M)this.connection.once("end",M);else return new this._Promise((P)=>{this.connection.once("end",P)})}};U(_,"Client");var D=_;D.Query=w,$.exports=D}),G2=r((W,$)=>{l();var k=F0().EventEmitter,J=U(function(){},"NOOP"),Z=U((F,M)=>{let P=F.findIndex(M);return P===-1?void 0:F.splice(P,1)[0]},"removeWhere"),X=class{constructor(M,P,f){this.client=M,this.idleListener=P,this.timeoutId=f}};U(X,"IdleItem");var G=X,z=class{constructor(M){this.callback=M}};U(z,"PendingItem");var V=z;function w(){throw Error("Release called on client which has already been released to the pool.")}U(w,"throwOnDoubleRelease");function R(F,M){if(M)return{callback:M,result:void 0};let P,f,T=U(function(q,Q){q?P(q):f(Q)},"cb"),S=new F(function(q,Q){f=q,P=Q}).catch((q)=>{throw Error.captureStackTrace(q),q});return{callback:T,result:S}}U(R,"promisify");function h(F,M){return U(function P(f){f.client=M,M.removeListener("error",P),M.on("error",()=>{F.log("additional client error after disconnection due to error",f)}),F._remove(M),F.emit("error",f,M)},"idleListener")}U(h,"makeIdleListener");var _=class extends k{constructor(M,P){super(),this.options=Object.assign({},M),M!=null&&"password"in M&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:M.password}),M!=null&&M.ssl&&M.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||P||S4().Client,this.Promise=this.options.Promise||D4.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map((P)=>{this._remove(P.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let M=this._pendingQueue.shift();if(this._idle.length){let P=this._idle.pop();clearTimeout(P.timeoutId);let f=P.client;f.ref&&f.ref();let T=P.idleListener;return this._acquireClient(f,M,T,!1)}if(!this._isFull())return this.newClient(M);throw Error("unexpected condition")}_remove(M){let P=Z(this._idle,(f)=>f.client===M);P!==void 0&&clearTimeout(P.timeoutId),this._clients=this._clients.filter((f)=>f!==M),M.end(),this.emit("remove",M)}connect(M){if(this.ending){let T=Error("Cannot use a pool after calling end on the pool");return M?M(T):this.Promise.reject(T)}let P=R(this.Promise,M),f=P.result;if(this._isFull()||this._idle.length){if(this._idle.length&&o.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new V(P.callback)),f;let T=U((Q,E,j)=>{clearTimeout(q),P.callback(Q,E,j)},"queueCallback"),S=new V(T),q=setTimeout(()=>{Z(this._pendingQueue,(Q)=>Q.callback===T),S.timedOut=!0,P.callback(Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return q.unref&&q.unref(),this._pendingQueue.push(S),f}return this.newClient(new V(P.callback)),f}newClient(M){let P=new this.Client(this.options);this._clients.push(P);let f=h(this,P);this.log("checking client timeout");let T,S=!1;this.options.connectionTimeoutMillis&&(T=setTimeout(()=>{this.log("ending client due to timeout"),S=!0,P.connection?P.connection.stream.destroy():P.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),P.connect((q)=>{if(T&&clearTimeout(T),P.on("error",f),q)this.log("client failed to connect",q),this._clients=this._clients.filter((Q)=>Q!==P),S&&(q=Error("Connection terminated due to connection timeout",{cause:q})),this._pulseQueue(),M.timedOut||M.callback(q,void 0,J);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let Q=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(P),this._idle.findIndex((E)=>E.client===P)!==-1&&this._acquireClient(P,new V((E,j,A)=>A()),f,!1)},this.options.maxLifetimeSeconds*1000);Q.unref(),P.once("end",()=>clearTimeout(Q))}return this._acquireClient(P,M,f,!0)}})}_acquireClient(M,P,f,T){T&&this.emit("connect",M),this.emit("acquire",M),M.release=this._releaseOnce(M,f),M.removeListener("error",f),P.timedOut?T&&this.options.verify?this.options.verify(M,M.release):M.release():T&&this.options.verify?this.options.verify(M,(S)=>{if(S)return M.release(S),P.callback(S,void 0,J);P.callback(void 0,M,M.release)}):P.callback(void 0,M,M.release)}_releaseOnce(M,P){let f=!1;return(T)=>{f&&w(),f=!0,this._release(M,P,T)}}_release(M,P,f){if(M.on("error",P),M._poolUseCount=(M._poolUseCount||0)+1,this.emit("release",f,M),f||this.ending||!M._queryable||M._ending||M._poolUseCount>=this.options.maxUses){M._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(M),this._pulseQueue();return}if(this._expired.has(M)){this.log("remove expired client"),this._expired.delete(M),this._remove(M),this._pulseQueue();return}let T;this.options.idleTimeoutMillis&&this._isAboveMin()&&(T=setTimeout(()=>{this.log("remove idle client"),this._remove(M)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&T.unref()),this.options.allowExitOnIdle&&M.unref(),this._idle.push(new G(M,P,T)),this._pulseQueue()}query(M,P,f){if(typeof M=="function"){let S=R(this.Promise,M);return t6(function(){return S.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),S.result}typeof P=="function"&&(f=P,P=void 0);let T=R(this.Promise,f);return f=T.callback,this.connect((S,q)=>{if(S)return f(S);let Q=!1,E=U((j)=>{Q||(Q=!0,q.release(j),f(j))},"onError");q.once("error",E),this.log("dispatching query");try{q.query(M,P,(j,A)=>{if(this.log("query dispatched"),q.removeListener("error",E),!Q)return Q=!0,q.release(j),j?f(j):f(void 0,A)})}catch(j){return q.release(j),f(j)}}),T.result}end(M){if(this.log("ending"),this.ending){let f=Error("Called end on pool more than once");return M?M(f):this.Promise.reject(f)}this.ending=!0;let P=R(this.Promise,M);return this._endCallback=P.callback,this._pulseQueue(),P.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((M,P)=>M+(this._expired.has(P)?1:0),0)}get totalCount(){return this._clients.length}};U(_,"Pool");var D=_;$.exports=D}),V7={};_1(V7,{default:()=>R7});var R7,M2=tW(()=>{l(),R7={}}),L2=r((W,$)=>{$.exports={name:"pg",version:"8.8.0",description:"PostgreSQL client - pure javascript & libpq with the same API",keywords:["database","libpq","pg","postgre","postgres","postgresql","rdbms"],homepage:"https://github.com/brianc/node-postgres",repository:{type:"git",url:"git://github.com/brianc/node-postgres.git",directory:"packages/pg"},author:"Brian Carlson <brian.m.carlson@gmail.com>",main:"./lib",dependencies:{"buffer-writer":"2.0.0","packet-reader":"1.0.0","pg-connection-string":"^2.5.0","pg-pool":"^3.5.2","pg-protocol":"^1.5.0","pg-types":"^2.1.0",pgpass:"1.x"},devDependencies:{async:"2.6.4",bluebird:"3.5.2",co:"4.6.0","pg-copy-streams":"0.3.0"},peerDependencies:{"pg-native":">=3.0.1"},peerDependenciesMeta:{"pg-native":{optional:!0}},scripts:{test:"make test-all"},files:["lib","SPONSORS.md"],license:"MIT",engines:{node:">= 8.0.0"},gitHead:"c99fb2c127ddf8d712500db2c7b9a5491a178655"}}),K2=r((W,$)=>{l();var k=F0().EventEmitter,J=(v4(),QW(x8)),Z=E4(),X=$.exports=function(z,V,w){k.call(this),z=Z.normalizeQueryConfig(z,V,w),this.text=z.text,this.values=z.values,this.name=z.name,this.callback=z.callback,this.state="new",this._arrayMode=z.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(R){R==="row"&&(this._emitRowEvents=!0)}.bind(this))};J.inherits(X,k);var G={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};X.prototype.handleError=function(z){var V=this.native.pq.resultErrorFields();if(V)for(var w in V){var R=G[w]||w;z[R]=V[w]}this.callback?this.callback(z):this.emit("error",z),this.state="error"},X.prototype.then=function(z,V){return this._getPromise().then(z,V)},X.prototype.catch=function(z){return this._getPromise().catch(z)},X.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(z,V){this._once("end",z),this._once("error",V)}.bind(this)),this._promise)},X.prototype.submit=function(z){this.state="running";var V=this;this.native=z.native,z.native.arrayMode=this._arrayMode;var w=U(function(_,D,F){if(z.native.arrayMode=!1,t6(function(){V.emit("_done")}),_)return V.handleError(_);V._emitRowEvents&&(F.length>1?D.forEach((M,P)=>{M.forEach((f)=>{V.emit("row",f,F[P])})}):D.forEach(function(M){V.emit("row",M,F)})),V.state="end",V.emit("end",F),V.callback&&V.callback(null,F)},"after");if(o.domain&&(w=o.domain.bind(w)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var R=(this.values||[]).map(Z.prepareValue);if(z.namedQueries[this.name]){if(this.text&&z.namedQueries[this.name]!==this.text){let _=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return w(_)}return z.native.execute(this.name,R,w)}return z.native.prepare(this.name,this.text,R.length,function(_){return _?w(_):(z.namedQueries[V.name]=V.text,V.native.execute(V.name,R,w))})}else if(this.values){if(!Array.isArray(this.values)){let _=Error("Query values must be an array");return w(_)}var h=this.values.map(Z.prepareValue);z.native.query(this.text,h,w)}else z.native.query(this.text,w)}}),U2=r((W,$)=>{l();var k=(M2(),QW(V7)),J=a6(),Z=L2(),X=F0().EventEmitter,G=(v4(),QW(x8)),z=e6(),V=K2(),w=$.exports=function(R){X.call(this),R=R||{},this._Promise=R.Promise||D4.Promise,this._types=new J(R.types),this.native=new k({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var h=this.connectionParameters=new z(R);this.user=h.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:h.password}),this.database=h.database,this.host=h.host,this.port=h.port,this.namedQueries={}};w.Query=V,G.inherits(w,X),w.prototype._errorAllQueries=function(R){let h=U((_)=>{o.nextTick(()=>{_.native=this.native,_.handleError(R)})},"enqueueError");this._hasActiveQuery()&&(h(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(h),this._queryQueue.length=0},w.prototype._connect=function(R){var h=this;if(this._connecting){o.nextTick(()=>R(Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(_,D){if(_)return R(_);h.native.connect(D,function(F){if(F)return h.native.end(),R(F);h._connected=!0,h.native.on("error",function(M){h._queryable=!1,h._errorAllQueries(M),h.emit("error",M)}),h.native.on("notification",function(M){h.emit("notification",{channel:M.relname,payload:M.extra})}),h.emit("connect"),h._pulseQueryQueue(!0),R()})})},w.prototype.connect=function(R){if(R){this._connect(R);return}return new this._Promise((h,_)=>{this._connect((D)=>{D?_(D):h()})})},w.prototype.query=function(R,h,_){var D,F,M,P,f;if(R==null)throw TypeError("Client was passed a null or undefined query");if(typeof R.submit=="function")M=R.query_timeout||this.connectionParameters.query_timeout,F=D=R,typeof h=="function"&&(R.callback=h);else if(M=this.connectionParameters.query_timeout,D=new V(R,h,_),!D.callback){let T,S;F=new this._Promise((q,Q)=>{T=q,S=Q}),D.callback=(q,Q)=>q?S(q):T(Q)}return M&&(f=D.callback,P=setTimeout(()=>{var T=Error("Query read timeout");o.nextTick(()=>{D.handleError(T,this.connection)}),f(T),D.callback=()=>{};var S=this._queryQueue.indexOf(D);S>-1&&this._queryQueue.splice(S,1),this._pulseQueryQueue()},M),D.callback=(T,S)=>{clearTimeout(P),f(T,S)}),this._queryable?this._ending?(D.native=this.native,o.nextTick(()=>{D.handleError(Error("Client was closed and is not queryable"))}),F):(this._queryQueue.push(D),this._pulseQueryQueue(),F):(D.native=this.native,o.nextTick(()=>{D.handleError(Error("Client has encountered a connection error and is not queryable"))}),F)},w.prototype.end=function(R){var h=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,R));var _;return R||(_=new this._Promise(function(D,F){R=U((M)=>M?F(M):D(),"cb")})),this.native.end(function(){h._errorAllQueries(Error("Connection terminated")),o.nextTick(()=>{h.emit("end"),R&&R()})}),_},w.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"},w.prototype._pulseQueryQueue=function(R){if(this._connected&&!this._hasActiveQuery()){var h=this._queryQueue.shift();if(!h){R||this.emit("drain");return}this._activeQuery=h,h.submit(this);var _=this;h.once("_done",function(){_._pulseQueryQueue()})}},w.prototype.cancel=function(R){this._activeQuery===R?this.native.cancel(function(){}):this._queryQueue.indexOf(R)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(R),1)},w.prototype.ref=function(){},w.prototype.unref=function(){},w.prototype.setTypeParser=function(R,h,_){return this._types.setTypeParser(R,h,_)},w.prototype.getTypeParser=function(R,h){return this._types.getTypeParser(R,h)}}),B5=r((W,$)=>{l(),$.exports=U2()}),S4=r((W,$)=>{l();var k=z2(),J=T4(),Z=U7(),X=G2(),{DatabaseError:G}=M7(),z=U((w)=>{var R;return R=class extends X{constructor(h){super(h,w)}},U(R,"BoundPool"),R},"poolFactory"),V=U(function(w){this.defaults=J,this.Client=w,this.Query=this.Client.Query,this.Pool=z(this.Client),this._pools=[],this.Connection=Z,this.types=f4(),this.DatabaseError=G},"PG");typeof o.env.NODE_PG_FORCE_NATIVE<"u"?$.exports=new V(B5()):($.exports=new V(k),Object.defineProperty($.exports,"native",{configurable:!0,enumerable:!1,get(){var w=null;try{w=new V(B5())}catch(R){if(R.code!=="MODULE_NOT_FOUND")throw R}return Object.defineProperty($.exports,"native",{value:w}),w}}))});l();l();Q8();p5();l();var{defineProperty:V2,defineProperties:R2,getOwnPropertyDescriptors:F2,getOwnPropertySymbols:I5}=Object,w2=Object.prototype.hasOwnProperty,_2=Object.prototype.propertyIsEnumerable,y5=U((W,$,k)=>($ in W)?V2(W,$,{enumerable:!0,configurable:!0,writable:!0,value:k}):W[$]=k,"__defNormalProp"),h2=U((W,$)=>{for(var k in $||($={}))w2.call($,k)&&y5(W,k,$[k]);if(I5)for(var k of I5($))_2.call($,k)&&y5(W,k,$[k]);return W},"__spreadValues"),P2=U((W,$)=>R2(W,F2($)),"__spreadProps"),D2=1008000,g5=new Uint8Array(new Uint16Array([258]).buffer)[0]===2,f2=new TextDecoder,W9=new TextEncoder,w4=W9.encode("0123456789abcdef"),_4=W9.encode("0123456789ABCDEF"),T2=W9.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),F7=T2.slice();F7[62]=45;F7[63]=95;var j8,h4;function w7(W,{alphabet:$,scratchArr:k}={}){if(!j8)if(j8=new Uint16Array(256),h4=new Uint16Array(256),g5)for(let D=0;D<256;D++)j8[D]=w4[D&15]<<8|w4[D>>>4],h4[D]=_4[D&15]<<8|_4[D>>>4];else for(let D=0;D<256;D++)j8[D]=w4[D&15]|w4[D>>>4]<<8,h4[D]=_4[D&15]|_4[D>>>4]<<8;W.byteOffset%4!==0&&(W=new Uint8Array(W));let J=W.length,Z=J>>>1,X=J>>>2,G=k||new Uint16Array(J),z=new Uint32Array(W.buffer,W.byteOffset,X),V=new Uint32Array(G.buffer,G.byteOffset,Z),w=$==="upper"?h4:j8,R=0,h=0,_;if(g5)for(;R<X;)_=z[R++],V[h++]=w[_>>>8&255]<<16|w[_&255],V[h++]=w[_>>>24]<<16|w[_>>>16&255];else for(;R<X;)_=z[R++],V[h++]=w[_>>>24]<<16|w[_>>>16&255],V[h++]=w[_>>>8&255]<<16|w[_&255];for(R<<=2;R<J;)G[R]=w[W[R++]];return f2.decode(G.subarray(0,J))}U(w7,"_toHex");function _7(W,$={}){let k="",J=W.length,Z=D2>>>1,X=Math.ceil(J/Z),G=new Uint16Array(X>1?Z:J);for(let z=0;z<X;z++){let V=z*Z,w=V+Z;k+=w7(W.subarray(V,w),P2(h2({},$),{scratchArr:G}))}return k}U(_7,"_toHexChunked");function h7(W,$={}){return $.alphabet!=="upper"&&typeof W.toHex=="function"?W.toHex():_7(W,$)}U(h7,"toHex");l();var P7=class W{constructor($,k){this.strings=$,this.values=k}toParameterizedQuery($={query:"",params:[]}){let{strings:k,values:J}=this;for(let Z=0,X=k.length;Z<X;Z++)if($.query+=k[Z],Z<J.length){let G=J[Z];if(G instanceof T7)$.query+=G.sql;else if(G instanceof P4)if(G.queryData instanceof W)G.queryData.toParameterizedQuery($);else{if(G.queryData.params?.length)throw Error("This query is not composable");$.query+=G.queryData.query}else{let{params:z}=$;z.push(G),$.query+="$"+z.length,(G instanceof t||ArrayBuffer.isView(G))&&($.query+="::bytea")}}return $}};U(P7,"SqlTemplate");var D7=P7,f7=class{constructor($){this.sql=$}};U(f7,"UnsafeRawSql");var T7=f7;l();function $9(){typeof window<"u"&&typeof document<"u"&&typeof console<"u"&&typeof console.warn=="function"&&console.warn(`
24
+ `),this.outputHelp({error:!0});let Z=$||{},J=Z.exitCode||1,X=Z.code||"commander.error";this._exit(J,X,W)}_parseOptionsEnv(){this.options.forEach((W)=>{if(W.envVar&&W.envVar in H1.env){let $=W.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(W.required||W.optional)this.emit(`optionEnv:${W.name()}`,H1.env[W.envVar]);else this.emit(`optionEnv:${W.name()}`)}})}_parseOptionsImplied(){let W=new G2(this.options),$=(Z)=>{return this.getOptionValue(Z)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(Z))};this.options.filter((Z)=>Z.implied!==void 0&&$(Z.attributeName())&&W.valueFromOption(this.getOptionValue(Z.attributeName()),Z)).forEach((Z)=>{Object.keys(Z.implied).filter((J)=>!$(J)).forEach((J)=>{this.setOptionValueWithSource(J,Z.implied[J],"implied")})})}missingArgument(W){let $=`error: missing required argument '${W}'`;this.error($,{code:"commander.missingArgument"})}optionMissingArgument(W){let $=`error: option '${W.flags}' argument missing`;this.error($,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(W){let $=`error: required option '${W.flags}' not specified`;this.error($,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(W,$){let Z=(Y)=>{let M=Y.attributeName(),G=this.getOptionValue(M),V=this.options.find((P)=>P.negate&&M===P.attributeName()),R=this.options.find((P)=>!P.negate&&M===P.attributeName());if(V&&(V.presetArg===void 0&&G===!1||V.presetArg!==void 0&&G===V.presetArg))return V;return R||Y},J=(Y)=>{let M=Z(Y),G=M.attributeName();if(this.getOptionValueSource(G)==="env")return`environment variable '${M.envVar}'`;return`option '${M.flags}'`},X=`error: ${J(W)} cannot be used with ${J($)}`;this.error(X,{code:"commander.conflictingOption"})}unknownOption(W){if(this._allowUnknownOption)return;let $="";if(W.startsWith("--")&&this._showSuggestionAfterError){let J=[],X=this;do{let Y=X.createHelp().visibleOptions(X).filter((M)=>M.long).map((M)=>M.long);J=J.concat(Y),X=X.parent}while(X&&!X._enablePositionalOptions);$=I9(W,J)}let Z=`error: unknown option '${W}'${$}`;this.error(Z,{code:"commander.unknownOption"})}_excessArguments(W){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,Z=$===1?"":"s",X=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${Z} but got ${W.length}.`;this.error(X,{code:"commander.excessArguments"})}unknownCommand(){let W=this.args[0],$="";if(this._showSuggestionAfterError){let J=[];this.createHelp().visibleCommands(this).forEach((X)=>{if(J.push(X.name()),X.alias())J.push(X.alias())}),$=I9(W,J)}let Z=`error: unknown command '${W}'${$}`;this.error(Z,{code:"commander.unknownCommand"})}version(W,$,Z){if(W===void 0)return this._version;this._version=W,$=$||"-V, --version",Z=Z||"output the version number";let J=this.createOption($,Z);return this._versionOptionName=J.attributeName(),this._registerOption(J),this.on("option:"+J.name(),()=>{this._outputConfiguration.writeOut(`${W}
25
+ `),this._exit(0,"commander.version",W)}),this}description(W,$){if(W===void 0&&$===void 0)return this._description;if(this._description=W,$)this._argsDescription=$;return this}summary(W){if(W===void 0)return this._summary;return this._summary=W,this}alias(W){if(W===void 0)return this._aliases[0];let $=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)$=this.commands[this.commands.length-1];if(W===$._name)throw Error("Command alias can't be the same as its name");let Z=this.parent?._findCommand(W);if(Z){let J=[Z.name()].concat(Z.aliases()).join("|");throw Error(`cannot add alias '${W}' to command '${this.name()}' as already have command '${J}'`)}return $._aliases.push(W),this}aliases(W){if(W===void 0)return this._aliases;return W.forEach(($)=>this.alias($)),this}usage(W){if(W===void 0){if(this._usage)return this._usage;let $=this.registeredArguments.map((Z)=>{return Y2(Z)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?$:[]).join(" ")}return this._usage=W,this}name(W){if(W===void 0)return this._name;return this._name=W,this}helpGroup(W){if(W===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=W,this}commandsGroup(W){if(W===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=W,this}optionsGroup(W){if(W===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=W,this}_initOptionGroup(W){if(this._defaultOptionGroup&&!W.helpGroupHeading)W.helpGroup(this._defaultOptionGroup)}_initCommandGroup(W){if(this._defaultCommandGroup&&!W.helpGroup())W.helpGroup(this._defaultCommandGroup)}nameFromFilename(W){return this._name=x0.basename(W,x0.extname(W)),this}executableDir(W){if(W===void 0)return this._executableDir;return this._executableDir=W,this}helpInformation(W){let $=this.createHelp(),Z=this._getOutputContext(W);$.prepareContext({error:Z.error,helpWidth:Z.helpWidth,outputHasColors:Z.hasColors});let J=$.formatHelp(this,$);if(Z.hasColors)return J;return this._outputConfiguration.stripColor(J)}_getOutputContext(W){W=W||{};let $=!!W.error,Z,J,X;if($)Z=(M)=>this._outputConfiguration.writeErr(M),J=this._outputConfiguration.getErrHasColors(),X=this._outputConfiguration.getErrHelpWidth();else Z=(M)=>this._outputConfiguration.writeOut(M),J=this._outputConfiguration.getOutHasColors(),X=this._outputConfiguration.getOutHelpWidth();return{error:$,write:(M)=>{if(!J)M=this._outputConfiguration.stripColor(M);return Z(M)},hasColors:J,helpWidth:X}}outputHelp(W){let $;if(typeof W==="function")$=W,W=void 0;let Z=this._getOutputContext(W),J={error:Z.error,write:Z.write,command:this};this._getCommandAndAncestors().reverse().forEach((Y)=>Y.emit("beforeAllHelp",J)),this.emit("beforeHelp",J);let X=this.helpInformation({error:Z.error});if($){if(X=$(X),typeof X!=="string"&&!Buffer.isBuffer(X))throw Error("outputHelp callback must return a string or a Buffer")}if(Z.write(X),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",J),this._getCommandAndAncestors().forEach((Y)=>Y.emit("afterAllHelp",J))}helpOption(W,$){if(typeof W==="boolean"){if(W){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(W??"-h, --help",$??"display help for command"),W||$)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(W){return this._helpOption=W,this._initOptionGroup(W),this}help(W){this.outputHelp(W);let $=Number(H1.exitCode??0);if($===0&&W&&typeof W!=="function"&&W.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(W,$){let Z=["beforeAll","before","after","afterAll"];if(!Z.includes(W))throw Error(`Unexpected value for position to addHelpText.
26
+ Expecting one of '${Z.join("', '")}'`);let J=`${W}Help`;return this.on(J,(X)=>{let Y;if(typeof $==="function")Y=$({error:X.error,command:X.command});else Y=$;if(Y)X.write(`${Y}
27
+ `)}),this}_outputHelpIfRequested(W){let $=this._getHelpOption();if($&&W.find((J)=>$.is(J)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function y9(W){return W.map(($)=>{if(!$.startsWith("--inspect"))return $;let Z,J="127.0.0.1",X="9229",Y;if((Y=$.match(/^(--inspect(-brk)?)$/))!==null)Z=Y[1];else if((Y=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Z=Y[1],/^\d+$/.test(Y[3]))X=Y[3];else J=Y[3];else if((Y=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Z=Y[1],J=Y[3],X=Y[4];if(Z&&X!=="0")return`${Z}=${J}:${parseInt(X)+1}`;return $})}function J6(){if(H1.env.NO_COLOR||H1.env.FORCE_COLOR==="0"||H1.env.FORCE_COLOR==="false")return!1;if(H1.env.FORCE_COLOR||H1.env.CLICOLOR_FORCE!==void 0)return!0;return}M2.Command=X6;M2.useColor=J6});var l9=L8((V2)=>{var{Argument:m9}=oW(),{Command:Y6}=g9(),{CommanderError:z2,InvalidArgumentError:c9}=KW(),{Help:U2}=e4(),{Option:u9}=W6();V2.program=new Y6;V2.createCommand=(W)=>new Y6(W);V2.createOption=(W,$)=>new u9(W,$);V2.createArgument=(W,$)=>new m9(W,$);V2.Command=Y6;V2.Option=u9;V2.Argument=m9;V2.Help=U2;V2.CommanderError=z2;V2.InvalidArgumentError=c9;V2.InvalidOptionArgumentError=c9});var p9=x$(l9(),1),{program:mJ,createCommand:cJ,createArgument:uJ,createOption:lJ,CommanderError:pJ,InvalidArgumentError:iJ,InvalidOptionArgumentError:tJ,Command:i9,Argument:aJ,Option:dJ,Help:sJ}=p9.default;import i4 from"path";import{fileURLToPath as TJ}from"url";import{createRequire as fJ}from"module";import{execSync as jJ,spawn as AJ}from"child_process";function n1(W){return typeof W>"u"||W===void 0}function a(W){return typeof W==="string"}function d0(W){return typeof W==="number"}function K8(W){return typeof W==="boolean"}function E8(W){return W===null}function t9(W){return W instanceof Date}function h8(W){return typeof W==="bigint"}function R1(W){return typeof W==="function"}function Q1(W){return typeof W==="object"&&W!==null}function a9(W){return W[W.length-1]}function k(W){return Object.freeze(W)}function zW(W){if(y1(W))return W;else return[W]}function y1(W){return Array.isArray(W)}function N1(W){return W}function d9(W){return W instanceof Error?W.message:String(W)}var $1=k({is(W){return W.kind==="AlterTableNode"},create(W){return k({kind:"AlterTableNode",table:W})},cloneWithTableProps(W,$){return k({...W,...$})},cloneWithColumnAlteration(W,$){return k({...W,columnAlterations:W.columnAlterations?[...W.columnAlterations,$]:[$]})}});var l=k({is(W){return W.kind==="IdentifierNode"},create(W){return k({kind:"IdentifierNode",name:W})}});var H0=k({is(W){return W.kind==="CreateIndexNode"},create(W){return k({kind:"CreateIndexNode",name:l.create(W)})},cloneWith(W,$){return k({...W,...$})},cloneWithColumns(W,$){return k({...W,columns:[...W.columns||[],...$]})}});var W4=k({is(W){return W.kind==="CreateSchemaNode"},create(W,$){return k({kind:"CreateSchemaNode",schema:l.create(W),...$})},cloneWith(W,$){return k({...W,...$})}});var s9=["preserve rows","delete rows","drop"],C1=k({is(W){return W.kind==="CreateTableNode"},create(W){return k({kind:"CreateTableNode",table:W,columns:k([])})},cloneWithColumn(W,$){return k({...W,columns:k([...W.columns,$])})},cloneWithConstraint(W,$){return k({...W,constraints:W.constraints?k([...W.constraints,$]):k([$])})},cloneWithIndex(W,$){return k({...W,indexes:W.indexes?k([...W.indexes,$]):k([$])})},cloneWithFrontModifier(W,$){return k({...W,frontModifiers:W.frontModifiers?k([...W.frontModifiers,$]):k([$])})},cloneWithEndModifier(W,$){return k({...W,endModifiers:W.endModifiers?k([...W.endModifiers,$]):k([$])})},cloneWith(W,$){return k({...W,...$})}});var g1=k({is(W){return W.kind==="SchemableIdentifierNode"},create(W){return k({kind:"SchemableIdentifierNode",identifier:l.create(W)})},createWithSchema(W,$){return k({kind:"SchemableIdentifierNode",schema:l.create(W),identifier:l.create($)})}});var s0=k({is(W){return W.kind==="DropIndexNode"},create(W,$){return k({kind:"DropIndexNode",name:g1.create(W),...$})},cloneWith(W,$){return k({...W,...$})}});var UW=k({is(W){return W.kind==="DropSchemaNode"},create(W,$){return k({kind:"DropSchemaNode",schema:l.create(W),...$})},cloneWith(W,$){return k({...W,...$})}});var T8=k({is(W){return W.kind==="DropTableNode"},create(W,$){return k({kind:"DropTableNode",table:W,...$})},cloneWith(W,$){return k({...W,...$})}});var q1=k({is(W){return W.kind==="AliasNode"},create(W,$){return k({kind:"AliasNode",node:W,alias:$})}});var u1=k({is(W){return W.kind==="TableNode"},create(W){return k({kind:"TableNode",table:g1.create(W)})},createWithSchema(W,$){return k({kind:"TableNode",table:g1.createWithSchema(W,$)})}});function G1(W){return Q1(W)&&R1(W.toOperationNode)}function $4(W){return Q1(W)&&"expressionType"in W&&G1(W)}function n9(W){return Q1(W)&&"expression"in W&&a(W.alias)&&G1(W)}var _0=k({is(W){return W.kind==="SelectModifierNode"},create(W,$){return k({kind:"SelectModifierNode",modifier:W,of:$})},createWithExpression(W){return k({kind:"SelectModifierNode",rawModifier:W})}});var l1=k({is(W){return W.kind==="AndNode"},create(W,$){return k({kind:"AndNode",left:W,right:$})}});var k0=k({is(W){return W.kind==="OrNode"},create(W,$){return k({kind:"OrNode",left:W,right:$})}});var Z4=k({is(W){return W.kind==="OnNode"},create(W){return k({kind:"OnNode",on:W})},cloneWithOperation(W,$,Z){return k({...W,on:$==="And"?l1.create(W.on,Z):k0.create(W.on,Z)})}});var G0=k({is(W){return W.kind==="JoinNode"},create(W,$){return k({kind:"JoinNode",joinType:W,table:$,on:void 0})},createWithOn(W,$,Z){return k({kind:"JoinNode",joinType:W,table:$,on:Z4.create(Z)})},cloneWithOn(W,$){return k({...W,on:W.on?Z4.cloneWithOperation(W.on,"And",$):Z4.create($)})}});var n0=k({is(W){return W.kind==="BinaryOperationNode"},create(W,$,Z){return k({kind:"BinaryOperationNode",leftOperand:W,operator:$,rightOperand:Z})}});var r9=k({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0}),a3=Object.keys(r9),o9=k({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0}),d3=Object.keys(o9),e9=k({"->":!0,"->>":!0}),T2=Object.keys(e9),W5=k({...r9,...o9,"||":!0}),f2=Object.keys(W5),$5=k({exists:!0,"not exists":!0}),s3=Object.keys($5),Z5=k({...$5,"-":!0,not:!0}),j2=Object.keys(Z5),n3=[...f2,...T2,...j2,"between","between symmetric"],r1=k({is(W){return W.kind==="OperatorNode"},create(W){return k({kind:"OperatorNode",operator:W})}});function J5(W){return a(W)&&W5[W]}function X5(W){return a(W)&&e9[W]}function Y5(W){return a(W)&&Z5[W]}var e=k({is(W){return W.kind==="ColumnNode"},create(W){return k({kind:"ColumnNode",column:l.create(W)})}});var f8=k({is(W){return W.kind==="SelectAllNode"},create(){return k({kind:"SelectAllNode"})}});var j8=k({is(W){return W.kind==="ReferenceNode"},create(W,$){return k({kind:"ReferenceNode",table:$,column:W})},createSelectAll(W){return k({kind:"ReferenceNode",table:W,column:f8.create()})}});class H6{#W;get dynamicReference(){return this.#W}get refType(){return}constructor(W){this.#W=W}toOperationNode(){return k6(this.#W)}}function J4(W){return Q1(W)&&G1(W)&&a(W.dynamicReference)}var M0=k({is(W){return W.kind==="OrderByItemNode"},create(W,$){return k({kind:"OrderByItemNode",orderBy:W,direction:$})},cloneWith(W,$){return k({...W,...$})}});var X1=k({is(W){return W.kind==="RawNode"},create(W,$){return k({kind:"RawNode",sqlFragments:k(W),parameters:k($)})},createWithSql(W){return X1.create([W],[])},createWithChild(W){return X1.create(["",""],[W])},createWithChildren(W){return X1.create(Array(W.length+1).fill(""),W)}});var H5=k({is(W){return W.kind==="CollateNode"},create(W){return k({kind:"CollateNode",collation:l.create(W)})}});class r0{#W;constructor(W){this.#W=k(W)}desc(){return new r0({node:M0.cloneWith(this.#W.node,{direction:X1.createWithSql("desc")})})}asc(){return new r0({node:M0.cloneWith(this.#W.node,{direction:X1.createWithSql("asc")})})}nullsLast(){return new r0({node:M0.cloneWith(this.#W.node,{nulls:"last"})})}nullsFirst(){return new r0({node:M0.cloneWith(this.#W.node,{nulls:"first"})})}collate(W){return new r0({node:M0.cloneWith(this.#W.node,{collation:H5.create(W)})})}toOperationNode(){return this.#W.node}}var k5=new Set;function A8(W){if(k5.has(W))return;k5.add(W),console.log(W)}function M6(W){return W==="asc"||W==="desc"}function o1(W){if(W.length===2)return[G6(W[0],W[1])];if(W.length===1){let[$]=W;if(Array.isArray($))return A8("orderBy(array) is deprecated, use multiple orderBy calls instead."),$.map((Z)=>G6(Z));return[G6($)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${W.length}`)}function G6(W,$){let Z=A2(W);if(M0.is(Z)){if($)throw Error("Cannot specify direction twice!");return Z}return G5(Z,$)}function A2(W){if(B0(W))return O1(W);if(J4(W))return W.toOperationNode();let[$,Z]=W.split(" ");if(Z)return A8("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),G5(p1($),Z);return p1(W)}function G5(W,$){if(typeof $==="string"){if(!M6($))throw Error(`Invalid order by direction: ${$}`);return M0.create(W,X1.createWithSql($))}if($4($))return A8("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),M0.create(W,$.toOperationNode());let Z=M0.create(W);if(!$)return Z;return $(new r0({node:Z})).toOperationNode()}var N8=k({is(W){return W.kind==="JSONReferenceNode"},create(W,$){return k({kind:"JSONReferenceNode",reference:W,traversal:$})},cloneWithTraversal(W,$){return k({...W,traversal:$})}});var X4=k({is(W){return W.kind==="JSONOperatorChainNode"},create(W){return k({kind:"JSONOperatorChainNode",operator:W,values:k([])})},cloneWithValue(W,$){return k({...W,values:k([...W.values,$])})}});var o0=k({is(W){return W.kind==="JSONPathNode"},create(W){return k({kind:"JSONPathNode",inOperator:W,pathLegs:k([])})},cloneWithLeg(W,$){return k({...W,pathLegs:k([...W.pathLegs,$])})}});function k6(W){if(a(W))return p1(W);return W.toOperationNode()}function b0(W){if(y1(W))return W.map(($)=>T1($));else return[T1(W)]}function T1(W){if(B0(W))return O1(W);return k6(W)}function M5(W,$){if(X5($))return N8.create(p1(W),X4.create(r1.create($)));if($==="->$"||$==="->>$")return N8.create(p1(W),o0.create(r1.create($.slice(0,-1))));throw Error(`Invalid JSON operator: ${$}`)}function p1(W){if(!W.includes("."))return j8.create(e.create(W));let Z=W.split(".").map(K6);if(Z.length===3)return N2(Z);if(Z.length===2)return C2(Z);throw Error(`invalid column reference ${W}`)}function L5(W){if(W.includes(" as ")){let[Z,J]=W.split(" as ").map(K6);return q1.create(p1(Z),l.create(J))}else return p1(W)}function L6(W){return e.create(W)}function C8(W){if(W.includes(" ")){let[Z,J]=W.split(" ").map(K6);if(!M6(J))throw Error(`invalid order direction "${J}" next to "${Z}"`);return o1([Z,J])[0]}else return L6(W)}function N2(W){let[$,Z,J]=W;return j8.create(e.create(J),u1.createWithSchema($,Z))}function C2(W){let[$,Z]=W;return j8.create(e.create(Z),u1.create($))}function K6(W){return W.trim()}var Y4=k({is(W){return W.kind==="PrimitiveValueListNode"},create(W){return k({kind:"PrimitiveValueListNode",values:k([...W])})}});var e0=k({is(W){return W.kind==="ValueListNode"},create(W){return k({kind:"ValueListNode",values:k(W)})}});var D1=k({is(W){return W.kind==="ValueNode"},create(W){return k({kind:"ValueNode",value:W})},createImmediate(W){return k({kind:"ValueNode",value:W,immediate:!0})}});function K5(W){if(y1(W))return q2(W);return M1(W)}function M1(W){if(B0(W))return O1(W);return D1.create(W)}function H4(W){return d0(W)||K8(W)||E8(W)}function VW(W){if(!H4(W))throw Error(`unsafe immediate value ${JSON.stringify(W)}`);return D1.createImmediate(W)}function q2(W){if(W.some(B0))return e0.create(W.map(($)=>M1($)));return Y4.create(W)}var e1=k({is(W){return W.kind==="ParensNode"},create(W){return k({kind:"ParensNode",node:W})}});function K1(W){if(W.length===3)return k4(W[0],W[1],W[2]);else if(W.length===1)return M1(W[0]);throw Error(`invalid arguments: ${JSON.stringify(W)}`)}function k4(W,$,Z){if(O2($)&&U5(Z))return n0.create(T1(W),z6($),D1.createImmediate(Z));return n0.create(T1(W),z6($),K5(Z))}function E1(W,$,Z){return n0.create(T1(W),z6($),T1(Z))}function U6(W,$){return q8(Object.entries(W).filter(([,Z])=>!n1(Z)).map(([Z,J])=>k4(Z,U5(J)?"is":"=",J)),$)}function q8(W,$,Z=!0){let J=$==="and"?l1.create:k0.create;if(W.length===0)return n0.create(D1.createImmediate(1),r1.create("="),D1.createImmediate($==="and"?1:0));let X=z5(W[0]);for(let Y=1;Y<W.length;++Y)X=J(X,z5(W[Y]));if(W.length>1&&Z)return e1.create(X);return X}function O2(W){return W==="is"||W==="is not"}function U5(W){return E8(W)||K8(W)}function z6(W){if(J5(W))return r1.create(W);if(G1(W))return W.toOperationNode();throw Error(`invalid operator ${JSON.stringify(W)}`)}function z5(W){return G1(W)?W.toOperationNode():W}var I0=k({is(W){return W.kind==="OrderByNode"},create(W){return k({kind:"OrderByNode",items:k([...W])})},cloneWithItems(W,$){return k({...W,items:k([...W.items,...$])})}});var V6=k({is(W){return W.kind==="PartitionByNode"},create(W){return k({kind:"PartitionByNode",items:k(W)})},cloneWithItems(W,$){return k({...W,items:k([...W.items,...$])})}});var PW=k({is(W){return W.kind==="OverNode"},create(){return k({kind:"OverNode"})},cloneWithOrderByItems(W,$){return k({...W,orderBy:W.orderBy?I0.cloneWithItems(W.orderBy,$):I0.create($)})},cloneWithPartitionByItems(W,$){return k({...W,partitionBy:W.partitionBy?V6.cloneWithItems(W.partitionBy,$):V6.create($)})}});var z8=k({is(W){return W.kind==="FromNode"},create(W){return k({kind:"FromNode",froms:k(W)})},cloneWithFroms(W,$){return k({...W,froms:k([...W.froms,...$])})}});var P6=k({is(W){return W.kind==="GroupByNode"},create(W){return k({kind:"GroupByNode",items:k(W)})},cloneWithItems(W,$){return k({...W,items:k([...W.items,...$])})}});var F6=k({is(W){return W.kind==="HavingNode"},create(W){return k({kind:"HavingNode",having:W})},cloneWithOperation(W,$,Z){return k({...W,having:$==="And"?l1.create(W.having,Z):k0.create(W.having,Z)})}});var S1=k({is(W){return W.kind==="InsertQueryNode"},create(W,$,Z){return k({kind:"InsertQueryNode",into:W,...$&&{with:$},replace:Z})},createWithoutInto(){return k({kind:"InsertQueryNode"})},cloneWith(W,$){return k({...W,...$})}});var G4=k({is(W){return W.kind==="ListNode"},create(W){return k({kind:"ListNode",items:k(W)})}});var v0=k({is(W){return W.kind==="UpdateQueryNode"},create(W,$){return k({kind:"UpdateQueryNode",table:W.length===1?W[0]:G4.create(W),...$&&{with:$}})},createWithoutTable(){return k({kind:"UpdateQueryNode"})},cloneWithFromItems(W,$){return k({...W,from:W.from?z8.cloneWithFroms(W.from,$):z8.create($)})},cloneWithUpdates(W,$){return k({...W,updates:W.updates?k([...W.updates,...$]):$})},cloneWithLimit(W,$){return k({...W,limit:$})}});var FW=k({is(W){return W.kind==="UsingNode"},create(W){return k({kind:"UsingNode",tables:k(W)})},cloneWithTables(W,$){return k({...W,tables:k([...W.tables,...$])})}});var W8=k({is(W){return W.kind==="DeleteQueryNode"},create(W,$){return k({kind:"DeleteQueryNode",from:z8.create(W),...$&&{with:$}})},cloneWithOrderByItems:(W,$)=>y.cloneWithOrderByItems(W,$),cloneWithoutOrderBy:(W)=>y.cloneWithoutOrderBy(W),cloneWithLimit(W,$){return k({...W,limit:$})},cloneWithoutLimit(W){return k({...W,limit:void 0})},cloneWithUsing(W,$){return k({...W,using:W.using!==void 0?FW.cloneWithTables(W.using,$):FW.create($)})}});var b1=k({is(W){return W.kind==="WhereNode"},create(W){return k({kind:"WhereNode",where:W})},cloneWithOperation(W,$,Z){return k({...W,where:$==="And"?l1.create(W.where,Z):k0.create(W.where,Z)})}});var R6=k({is(W){return W.kind==="ReturningNode"},create(W){return k({kind:"ReturningNode",selections:k(W)})},cloneWithSelections(W,$){return k({...W,selections:W.selections?k([...W.selections,...$]):k($)})}});var V5=k({is(W){return W.kind==="ExplainNode"},create(W,$){return k({kind:"ExplainNode",format:W,options:$})}});var i1=k({is(W){return W.kind==="WhenNode"},create(W){return k({kind:"WhenNode",condition:W})},cloneWithResult(W,$){return k({...W,result:$})}});var W0=k({is(W){return W.kind==="MergeQueryNode"},create(W,$){return k({kind:"MergeQueryNode",into:W,...$&&{with:$}})},cloneWithUsing(W,$){return k({...W,using:$})},cloneWithWhen(W,$){return k({...W,whens:W.whens?k([...W.whens,$]):k([$])})},cloneWithThen(W,$){return k({...W,whens:W.whens?k([...W.whens.slice(0,-1),i1.cloneWithResult(W.whens[W.whens.length-1],$)]):void 0})}});var D6=k({is(W){return W.kind==="OutputNode"},create(W){return k({kind:"OutputNode",selections:k(W)})},cloneWithSelections(W,$){return k({...W,selections:W.selections?k([...W.selections,...$]):k($)})}});var y=k({is(W){return k1.is(W)||S1.is(W)||v0.is(W)||W8.is(W)||W0.is(W)},cloneWithEndModifier(W,$){return k({...W,endModifiers:W.endModifiers?k([...W.endModifiers,$]):k([$])})},cloneWithWhere(W,$){return k({...W,where:W.where?b1.cloneWithOperation(W.where,"And",$):b1.create($)})},cloneWithJoin(W,$){return k({...W,joins:W.joins?k([...W.joins,$]):k([$])})},cloneWithReturning(W,$){return k({...W,returning:W.returning?R6.cloneWithSelections(W.returning,$):R6.create($)})},cloneWithoutReturning(W){return k({...W,returning:void 0})},cloneWithoutWhere(W){return k({...W,where:void 0})},cloneWithExplain(W,$,Z){return k({...W,explain:V5.create($,Z?.toOperationNode())})},cloneWithTop(W,$){return k({...W,top:$})},cloneWithOutput(W,$){return k({...W,output:W.output?D6.cloneWithSelections(W.output,$):D6.create($)})},cloneWithOrderByItems(W,$){return k({...W,orderBy:W.orderBy?I0.cloneWithItems(W.orderBy,$):I0.create($)})},cloneWithoutOrderBy(W){return k({...W,orderBy:void 0})}});var k1=k({is(W){return W.kind==="SelectQueryNode"},create(W){return k({kind:"SelectQueryNode",...W&&{with:W}})},createFrom(W,$){return k({kind:"SelectQueryNode",from:z8.create(W),...$&&{with:$}})},cloneWithSelections(W,$){return k({...W,selections:W.selections?k([...W.selections,...$]):k($)})},cloneWithDistinctOn(W,$){return k({...W,distinctOn:W.distinctOn?k([...W.distinctOn,...$]):k($)})},cloneWithFrontModifier(W,$){return k({...W,frontModifiers:W.frontModifiers?k([...W.frontModifiers,$]):k([$])})},cloneWithOrderByItems:(W,$)=>y.cloneWithOrderByItems(W,$),cloneWithGroupByItems(W,$){return k({...W,groupBy:W.groupBy?P6.cloneWithItems(W.groupBy,$):P6.create($)})},cloneWithLimit(W,$){return k({...W,limit:$})},cloneWithOffset(W,$){return k({...W,offset:$})},cloneWithFetch(W,$){return k({...W,fetch:$})},cloneWithHaving(W,$){return k({...W,having:W.having?F6.cloneWithOperation(W.having,"And",$):F6.create($)})},cloneWithSetOperations(W,$){return k({...W,setOperations:W.setOperations?k([...W.setOperations,...$]):k([...$])})},cloneWithoutSelections(W){return k({...W,selections:[]})},cloneWithoutLimit(W){return k({...W,limit:void 0})},cloneWithoutOffset(W){return k({...W,offset:void 0})},cloneWithoutOrderBy:(W)=>y.cloneWithoutOrderBy(W),cloneWithoutGroupBy(W){return k({...W,groupBy:void 0})}});class O8{#W;constructor(W){this.#W=k(W)}on(...W){return new O8({...this.#W,joinNode:G0.cloneWithOn(this.#W.joinNode,K1(W))})}onRef(W,$,Z){return new O8({...this.#W,joinNode:G0.cloneWithOn(this.#W.joinNode,E1(W,$,Z))})}onTrue(){return new O8({...this.#W,joinNode:G0.cloneWithOn(this.#W.joinNode,X1.createWithSql("true"))})}$call(W){return W(this)}toOperationNode(){return this.#W.joinNode}}var P5=k({is(W){return W.kind==="PartitionByItemNode"},create(W){return k({kind:"PartitionByItemNode",partitionBy:W})}});function F5(W){return b0(W).map(P5.create)}class x8{#W;constructor(W){this.#W=k(W)}orderBy(...W){return new x8({overNode:PW.cloneWithOrderByItems(this.#W.overNode,o1(W))})}clearOrderBy(){return new x8({overNode:y.cloneWithoutOrderBy(this.#W.overNode)})}partitionBy(W){return new x8({overNode:PW.cloneWithPartitionByItems(this.#W.overNode,F5(W))})}$call(W){return W(this)}toOperationNode(){return this.#W.overNode}}var B8=k({is(W){return W.kind==="SelectionNode"},create(W){return k({kind:"SelectionNode",selection:W})},createSelectAll(){return k({kind:"SelectionNode",selection:f8.create()})},createSelectAllFromTable(W){return k({kind:"SelectionNode",selection:j8.createSelectAll(W)})}});function j1(W){if(R1(W))return j1(W(L0()));else if(y1(W))return W.map(($)=>R5($));else return[R5(W)]}function R5(W){if(a(W))return B8.create(L5(W));else if(J4(W))return B8.create(W.toOperationNode());else return B8.create(M4(W))}function x1(W){if(!W)return[B8.createSelectAll()];else if(Array.isArray(W))return W.map(D5);else return[D5(W)]}function D5(W){if(a(W))return B8.createSelectAllFromTable(Z1(W));throw Error(`invalid value selectAll expression: ${JSON.stringify(W)}`)}var w5=k({is(W){return W.kind==="ValuesNode"},create(W){return k({kind:"ValuesNode",values:k(W)})}});var Q5=k({is(W){return W.kind==="DefaultInsertValueNode"},create(){return k({kind:"DefaultInsertValueNode"})}});function L4(W){let $=R1(W)?W(L0()):W,Z=y1($)?$:k([$]);return x2(Z)}function x2(W){let $=B2(W);return[k([...$.keys()].map(e.create)),w5.create(W.map((Z)=>b2(Z,$)))]}function B2(W){let $=new Map;for(let Z of W){let J=Object.keys(Z);for(let X of J)if(!$.has(X)&&Z[X]!==void 0)$.set(X,$.size)}return $}function b2(W,$){let Z=Object.keys(W),J=Array.from({length:$.size}),X=!1,Y=Z.length;for(let G of Z){let V=$.get(G);if(n1(V)){Y--;continue}let R=W[G];if(n1(R)||B0(R))X=!0;J[V]=R}if(Y<$.size||X){let G=Q5.create();return e0.create(J.map((V)=>n1(V)?G:M1(V)))}return Y4.create(J)}var w6=k({is(W){return W.kind==="ColumnUpdateNode"},create(W,$){return k({kind:"ColumnUpdateNode",column:W,value:$})}});function S5(...W){if(W.length===2)return[w6.create(T1(W[0]),M1(W[1]))];return RW(W[0])}function RW(W){let $=R1(W)?W(L0()):W;return Object.entries($).filter(([Z,J])=>J!==void 0).map(([Z,J])=>{return w6.create(e.create(Z),M1(J))})}var _5=k({is(W){return W.kind==="OnDuplicateKeyNode"},create(W){return k({kind:"OnDuplicateKeyNode",updates:W})}});class Q6{insertId;numInsertedOrUpdatedRows;constructor(W,$){this.insertId=W,this.numInsertedOrUpdatedRows=$}}class K0 extends Error{node;constructor(W){super("no result");this.node=W}}function E0(W){return Object.prototype.hasOwnProperty.call(W,"prototype")}var m1=k({is(W){return W.kind==="OnConflictNode"},create(){return k({kind:"OnConflictNode"})},cloneWith(W,$){return k({...W,...$})},cloneWithIndexWhere(W,$){return k({...W,indexWhere:W.indexWhere?b1.cloneWithOperation(W.indexWhere,"And",$):b1.create($)})},cloneWithIndexOrWhere(W,$){return k({...W,indexWhere:W.indexWhere?b1.cloneWithOperation(W.indexWhere,"Or",$):b1.create($)})},cloneWithUpdateWhere(W,$){return k({...W,updateWhere:W.updateWhere?b1.cloneWithOperation(W.updateWhere,"And",$):b1.create($)})},cloneWithUpdateOrWhere(W,$){return k({...W,updateWhere:W.updateWhere?b1.cloneWithOperation(W.updateWhere,"Or",$):b1.create($)})},cloneWithoutIndexWhere(W){return k({...W,indexWhere:void 0})},cloneWithoutUpdateWhere(W){return k({...W,updateWhere:void 0})}});class h0{#W;constructor(W){this.#W=k(W)}column(W){let $=e.create(W);return new h0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?k([...this.#W.onConflictNode.columns,$]):k([$])})})}columns(W){let $=W.map(e.create);return new h0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{columns:this.#W.onConflictNode.columns?k([...this.#W.onConflictNode.columns,...$]):k($)})})}constraint(W){return new h0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{constraint:l.create(W)})})}expression(W){return new h0({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{indexExpression:W.toOperationNode()})})}where(...W){return new h0({...this.#W,onConflictNode:m1.cloneWithIndexWhere(this.#W.onConflictNode,K1(W))})}whereRef(W,$,Z){return new h0({...this.#W,onConflictNode:m1.cloneWithIndexWhere(this.#W.onConflictNode,E1(W,$,Z))})}clearWhere(){return new h0({...this.#W,onConflictNode:m1.cloneWithoutIndexWhere(this.#W.onConflictNode)})}doNothing(){return new v5({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{doNothing:!0})})}doUpdateSet(W){return new DW({...this.#W,onConflictNode:m1.cloneWith(this.#W.onConflictNode,{updates:RW(W)})})}$call(W){return W(this)}}class v5{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.onConflictNode}}class DW{#W;constructor(W){this.#W=k(W)}where(...W){return new DW({...this.#W,onConflictNode:m1.cloneWithUpdateWhere(this.#W.onConflictNode,K1(W))})}whereRef(W,$,Z){return new DW({...this.#W,onConflictNode:m1.cloneWithUpdateWhere(this.#W.onConflictNode,E1(W,$,Z))})}clearWhere(){return new DW({...this.#W,onConflictNode:m1.cloneWithoutUpdateWhere(this.#W.onConflictNode)})}$call(W){return W(this)}toOperationNode(){return this.#W.onConflictNode}}var E5=k({is(W){return W.kind==="TopNode"},create(W,$){return k({kind:"TopNode",expression:W,modifiers:$})}});function z0(W,$){if(!d0(W)&&!h8(W))throw Error(`Invalid top expression: ${W}`);if(!n1($)&&!I2($))throw Error(`Invalid top modifiers: ${$}`);return E5.create(W,$)}function I2(W){return W==="percent"||W==="with ties"||W==="percent with ties"}var U8=k({is(W){return W.kind==="OrActionNode"},create(W){return k({kind:"OrActionNode",action:W})}});class L1{#W;constructor(W){this.#W=k(W)}values(W){let[$,Z]=L4(W);return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{columns:$,values:Z})})}columns(W){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{columns:k(W.map(e.create))})})}expression(W){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{values:O1(W)})})}defaultValues(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{defaultValues:!0})})}modifyEnd(W){return new L1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}ignore(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("ignore")})})}orIgnore(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("ignore")})})}orAbort(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("abort")})})}orFail(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("fail")})})}orReplace(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("replace")})})}orRollback(){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{orAction:U8.create("rollback")})})}top(W,$){return new L1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}onConflict(W){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{onConflict:W(new h0({onConflictNode:m1.create()})).toOperationNode()})})}onDuplicateKeyUpdate(W){return new L1({...this.#W,queryNode:S1.cloneWith(this.#W.queryNode,{onDuplicateKey:_5.create(RW(W))})})}returning(W){return new L1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(){return new L1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1())})}output(W){return new L1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new L1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}clearReturning(){return new L1({...this.#W,queryNode:y.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new L1({...this.#W})}$castTo(){return new L1(this.#W)}$narrowType(){return new L1(this.#W)}$assertType(){return new L1(this.#W)}withPlugin(W){return new L1({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new Q6(Z.insertId,Z.numAffectedRows??BigInt(0))]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??K0;throw E0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new L1({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}class S6{numDeletedRows;constructor(W){this.numDeletedRows=W}}var b8=k({is(W){return W.kind==="LimitNode"},create(W){return k({kind:"LimitNode",limit:W})}});var _1;class K4{#W;constructor(W){this.#W=k(W)}where(...W){return new _1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,K1(W))})}whereRef(W,$,Z){return new _1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,E1(W,$,Z))})}clearWhere(){return new _1({...this.#W,queryNode:y.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new _1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}using(W){return new _1({...this.#W,queryNode:W8.cloneWithUsing(this.#W.queryNode,U0(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}#$(W,$){return new _1({...this.#W,queryNode:y.cloneWithJoin(this.#W.queryNode,$8(W,$))})}returning(W){return new _1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new _1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new _1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new _1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}clearReturning(){return new _1({...this.#W,queryNode:y.cloneWithoutReturning(this.#W.queryNode)})}clearLimit(){return new _1({...this.#W,queryNode:W8.cloneWithoutLimit(this.#W.queryNode)})}orderBy(...W){return new _1({...this.#W,queryNode:y.cloneWithOrderByItems(this.#W.queryNode,o1(W))})}clearOrderBy(){return new _1({...this.#W,queryNode:y.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new _1({...this.#W,queryNode:W8.cloneWithLimit(this.#W.queryNode,b8.create(M1(W)))})}modifyEnd(W){return new _1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new _1({...this.#W})}$castTo(){return new _1(this.#W)}$narrowType(){return new _1(this.#W)}$assertType(){return new _1(this.#W)}withPlugin(W){return new _1({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new S6(Z.numAffectedRows??BigInt(0))]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??K0;throw E0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new _1({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}_1=K4;class _6{numUpdatedRows;numChangedRows;constructor(W,$){this.numUpdatedRows=W,this.numChangedRows=$}}var v1;class I8{#W;constructor(W){this.#W=k(W)}where(...W){return new v1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,K1(W))})}whereRef(W,$,Z){return new v1({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,E1(W,$,Z))})}clearWhere(){return new v1({...this.#W,queryNode:y.cloneWithoutWhere(this.#W.queryNode)})}top(W,$){return new v1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}from(W){return new v1({...this.#W,queryNode:v0.cloneWithFromItems(this.#W.queryNode,U0(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}#$(W,$){return new v1({...this.#W,queryNode:y.cloneWithJoin(this.#W.queryNode,$8(W,$))})}orderBy(...W){return new v1({...this.#W,queryNode:y.cloneWithOrderByItems(this.#W.queryNode,o1(W))})}clearOrderBy(){return new v1({...this.#W,queryNode:y.cloneWithoutOrderBy(this.#W.queryNode)})}limit(W){return new v1({...this.#W,queryNode:v0.cloneWithLimit(this.#W.queryNode,b8.create(M1(W)))})}set(...W){return new v1({...this.#W,queryNode:v0.cloneWithUpdates(this.#W.queryNode,S5(...W))})}returning(W){return new v1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new v1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new v1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new v1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}modifyEnd(W){return new v1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}clearReturning(){return new v1({...this.#W,queryNode:y.cloneWithoutReturning(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new v1({...this.#W})}$castTo(){return new v1(this.#W)}$narrowType(){return new v1(this.#W)}$assertType(){return new v1(this.#W)}withPlugin(W){return new v1({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new _6(Z.numAffectedRows??BigInt(0),Z.numChangedRows)]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??K0;throw E0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new v1({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}v1=I8;var v6=k({is(W){return W.kind==="CommonTableExpressionNameNode"},create(W,$){return k({kind:"CommonTableExpressionNameNode",table:u1.create(W),columns:$?k($.map(e.create)):void 0})}});var y8=k({is(W){return W.kind==="CommonTableExpressionNode"},create(W,$){return k({kind:"CommonTableExpressionNode",name:W,expression:$})},cloneWith(W,$){return k({...W,...$})}});class wW{#W;constructor(W){this.#W=k(W)}materialized(){return new wW({...this.#W,node:y8.cloneWith(this.#W.node,{materialized:!0})})}notMaterialized(){return new wW({...this.#W,node:y8.cloneWith(this.#W.node,{materialized:!1})})}toOperationNode(){return this.#W.node}}function E6(W,$){let Z=G1($)?$.toOperationNode():$(T5()).toOperationNode();if(R1(W))return W(y2(Z)).toOperationNode();return y8.create(h5(W),Z)}function y2(W){return($)=>{return new wW({node:y8.create(h5($),W)})}}function h5(W){if(W.includes("(")){let $=W.split(/[\(\)]/),Z=$[0],J=$[1].split(",").map((X)=>X.trim());return v6.create(Z,J)}else return v6.create(W)}var QW=k({is(W){return W.kind==="WithNode"},create(W,$){return k({kind:"WithNode",expressions:k([W]),...$})},cloneWithExpression(W,$){return k({...W,expressions:k([...W.expressions,$])})}});var f5=["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 j5(W){let $="";for(let Z=0;Z<W;++Z)$+=g2();return $}function g2(){return f5[~~(Math.random()*f5.length)]}function W1(){return new A5}class A5{#W;get queryId(){if(this.#W===void 0)this.#W=j5(8);return this.#W}}class SW{nodeStack=[];#W=k({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),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.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),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this),AlterTypeNode:this.transformAlterType.bind(this),AddValueNode:this.transformAddValue.bind(this),RenameValueNode:this.transformRenameValue.bind(this)});transformNode(W,$){if(!W)return W;this.nodeStack.push(W);let Z=this.transformNodeImpl(W,$);return this.nodeStack.pop(),k(Z)}transformNodeImpl(W,$){return this.#W[W.kind](W,$)}transformNodeList(W,$){if(!W)return W;return k(W.map((Z)=>this.transformNode(Z,$)))}transformSelectQuery(W,$){return{kind:"SelectQueryNode",from:this.transformNode(W.from,$),selections:this.transformNodeList(W.selections,$),distinctOn:this.transformNodeList(W.distinctOn,$),joins:this.transformNodeList(W.joins,$),groupBy:this.transformNode(W.groupBy,$),orderBy:this.transformNode(W.orderBy,$),where:this.transformNode(W.where,$),frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),limit:this.transformNode(W.limit,$),offset:this.transformNode(W.offset,$),with:this.transformNode(W.with,$),having:this.transformNode(W.having,$),explain:this.transformNode(W.explain,$),setOperations:this.transformNodeList(W.setOperations,$),fetch:this.transformNode(W.fetch,$),top:this.transformNode(W.top,$)}}transformSelection(W,$){return{kind:"SelectionNode",selection:this.transformNode(W.selection,$)}}transformColumn(W,$){return{kind:"ColumnNode",column:this.transformNode(W.column,$)}}transformAlias(W,$){return{kind:"AliasNode",node:this.transformNode(W.node,$),alias:this.transformNode(W.alias,$)}}transformTable(W,$){return{kind:"TableNode",table:this.transformNode(W.table,$)}}transformFrom(W,$){return{kind:"FromNode",froms:this.transformNodeList(W.froms,$)}}transformReference(W,$){return{kind:"ReferenceNode",column:this.transformNode(W.column,$),table:this.transformNode(W.table,$)}}transformAnd(W,$){return{kind:"AndNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)}}transformOr(W,$){return{kind:"OrNode",left:this.transformNode(W.left,$),right:this.transformNode(W.right,$)}}transformValueList(W,$){return{kind:"ValueListNode",values:this.transformNodeList(W.values,$)}}transformParens(W,$){return{kind:"ParensNode",node:this.transformNode(W.node,$)}}transformJoin(W,$){return{kind:"JoinNode",joinType:W.joinType,table:this.transformNode(W.table,$),on:this.transformNode(W.on,$)}}transformRaw(W,$){return{kind:"RawNode",sqlFragments:k([...W.sqlFragments]),parameters:this.transformNodeList(W.parameters,$)}}transformWhere(W,$){return{kind:"WhereNode",where:this.transformNode(W.where,$)}}transformInsertQuery(W,$){return{kind:"InsertQueryNode",into:this.transformNode(W.into,$),columns:this.transformNodeList(W.columns,$),values:this.transformNode(W.values,$),returning:this.transformNode(W.returning,$),onConflict:this.transformNode(W.onConflict,$),onDuplicateKey:this.transformNode(W.onDuplicateKey,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),orAction:this.transformNode(W.orAction,$),replace:W.replace,explain:this.transformNode(W.explain,$),defaultValues:W.defaultValues,top:this.transformNode(W.top,$),output:this.transformNode(W.output,$)}}transformValues(W,$){return{kind:"ValuesNode",values:this.transformNodeList(W.values,$)}}transformDeleteQuery(W,$){return{kind:"DeleteQueryNode",from:this.transformNode(W.from,$),using:this.transformNode(W.using,$),joins:this.transformNodeList(W.joins,$),where:this.transformNode(W.where,$),returning:this.transformNode(W.returning,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),orderBy:this.transformNode(W.orderBy,$),limit:this.transformNode(W.limit,$),explain:this.transformNode(W.explain,$),top:this.transformNode(W.top,$),output:this.transformNode(W.output,$)}}transformReturning(W,$){return{kind:"ReturningNode",selections:this.transformNodeList(W.selections,$)}}transformCreateTable(W,$){return{kind:"CreateTableNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),constraints:this.transformNodeList(W.constraints,$),indexes:this.transformNodeList(W.indexes,$),temporary:W.temporary,ifNotExists:W.ifNotExists,onCommit:W.onCommit,frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),selectQuery:this.transformNode(W.selectQuery,$)}}transformColumnDefinition(W,$){return{kind:"ColumnDefinitionNode",column:this.transformNode(W.column,$),dataType:this.transformNode(W.dataType,$),references:this.transformNode(W.references,$),primaryKey:W.primaryKey,autoIncrement:W.autoIncrement,unique:W.unique,notNull:W.notNull,unsigned:W.unsigned,defaultTo:this.transformNode(W.defaultTo,$),check:this.transformNode(W.check,$),generated:this.transformNode(W.generated,$),frontModifiers:this.transformNodeList(W.frontModifiers,$),endModifiers:this.transformNodeList(W.endModifiers,$),nullsNotDistinct:W.nullsNotDistinct,identity:W.identity,ifNotExists:W.ifNotExists}}transformAddColumn(W,$){return{kind:"AddColumnNode",column:this.transformNode(W.column,$)}}transformDropTable(W,$){return{kind:"DropTableNode",table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade,temporary:W.temporary}}transformOrderBy(W,$){return{kind:"OrderByNode",items:this.transformNodeList(W.items,$)}}transformOrderByItem(W,$){return{kind:"OrderByItemNode",orderBy:this.transformNode(W.orderBy,$),direction:this.transformNode(W.direction,$),collation:this.transformNode(W.collation,$),nulls:W.nulls}}transformGroupBy(W,$){return{kind:"GroupByNode",items:this.transformNodeList(W.items,$)}}transformGroupByItem(W,$){return{kind:"GroupByItemNode",groupBy:this.transformNode(W.groupBy,$)}}transformUpdateQuery(W,$){return{kind:"UpdateQueryNode",table:this.transformNode(W.table,$),from:this.transformNode(W.from,$),joins:this.transformNodeList(W.joins,$),where:this.transformNode(W.where,$),updates:this.transformNodeList(W.updates,$),returning:this.transformNode(W.returning,$),endModifiers:this.transformNodeList(W.endModifiers,$),with:this.transformNode(W.with,$),explain:this.transformNode(W.explain,$),limit:this.transformNode(W.limit,$),top:this.transformNode(W.top,$),output:this.transformNode(W.output,$),orderBy:this.transformNode(W.orderBy,$)}}transformColumnUpdate(W,$){return{kind:"ColumnUpdateNode",column:this.transformNode(W.column,$),value:this.transformNode(W.value,$)}}transformLimit(W,$){return{kind:"LimitNode",limit:this.transformNode(W.limit,$)}}transformOffset(W,$){return{kind:"OffsetNode",offset:this.transformNode(W.offset,$)}}transformOnConflict(W,$){return{kind:"OnConflictNode",columns:this.transformNodeList(W.columns,$),constraint:this.transformNode(W.constraint,$),indexExpression:this.transformNode(W.indexExpression,$),indexWhere:this.transformNode(W.indexWhere,$),updates:this.transformNodeList(W.updates,$),updateWhere:this.transformNode(W.updateWhere,$),doNothing:W.doNothing}}transformOnDuplicateKey(W,$){return{kind:"OnDuplicateKeyNode",updates:this.transformNodeList(W.updates,$)}}transformCreateIndex(W,$){return{kind:"CreateIndexNode",name:this.transformNode(W.name,$),table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),unique:W.unique,using:this.transformNode(W.using,$),ifNotExists:W.ifNotExists,where:this.transformNode(W.where,$),nullsNotDistinct:W.nullsNotDistinct}}transformList(W,$){return{kind:"ListNode",items:this.transformNodeList(W.items,$)}}transformDropIndex(W,$){return{kind:"DropIndexNode",name:this.transformNode(W.name,$),table:this.transformNode(W.table,$),ifExists:W.ifExists,cascade:W.cascade}}transformPrimaryKeyConstraint(W,$){return{kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred}}transformUniqueConstraint(W,$){return{kind:"UniqueConstraintNode",columns:this.transformNodeList(W.columns,$),name:this.transformNode(W.name,$),nullsNotDistinct:W.nullsNotDistinct,deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred}}transformForeignKeyConstraint(W,$){return{kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(W.columns,$),references:this.transformNode(W.references,$),name:this.transformNode(W.name,$),onDelete:W.onDelete,onUpdate:W.onUpdate,deferrable:W.deferrable,initiallyDeferred:W.initiallyDeferred}}transformSetOperation(W,$){return{kind:"SetOperationNode",operator:W.operator,expression:this.transformNode(W.expression,$),all:W.all}}transformReferences(W,$){return{kind:"ReferencesNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$),onDelete:W.onDelete,onUpdate:W.onUpdate}}transformCheckConstraint(W,$){return{kind:"CheckConstraintNode",expression:this.transformNode(W.expression,$),name:this.transformNode(W.name,$)}}transformWith(W,$){return{kind:"WithNode",expressions:this.transformNodeList(W.expressions,$),recursive:W.recursive}}transformCommonTableExpression(W,$){return{kind:"CommonTableExpressionNode",name:this.transformNode(W.name,$),materialized:W.materialized,expression:this.transformNode(W.expression,$)}}transformCommonTableExpressionName(W,$){return{kind:"CommonTableExpressionNameNode",table:this.transformNode(W.table,$),columns:this.transformNodeList(W.columns,$)}}transformHaving(W,$){return{kind:"HavingNode",having:this.transformNode(W.having,$)}}transformCreateSchema(W,$){return{kind:"CreateSchemaNode",schema:this.transformNode(W.schema,$),ifNotExists:W.ifNotExists}}transformDropSchema(W,$){return{kind:"DropSchemaNode",schema:this.transformNode(W.schema,$),ifExists:W.ifExists,cascade:W.cascade}}transformAlterTable(W,$){return{kind:"AlterTableNode",table:this.transformNode(W.table,$),renameTo:this.transformNode(W.renameTo,$),setSchema:this.transformNode(W.setSchema,$),columnAlterations:this.transformNodeList(W.columnAlterations,$),addConstraint:this.transformNode(W.addConstraint,$),dropConstraint:this.transformNode(W.dropConstraint,$),renameConstraint:this.transformNode(W.renameConstraint,$),addIndex:this.transformNode(W.addIndex,$),dropIndex:this.transformNode(W.dropIndex,$)}}transformDropColumn(W,$){return{kind:"DropColumnNode",column:this.transformNode(W.column,$),ifExists:W.ifExists}}transformRenameColumn(W,$){return{kind:"RenameColumnNode",column:this.transformNode(W.column,$),renameTo:this.transformNode(W.renameTo,$)}}transformAlterColumn(W,$){return{kind:"AlterColumnNode",column:this.transformNode(W.column,$),dataType:this.transformNode(W.dataType,$),dataTypeExpression:this.transformNode(W.dataTypeExpression,$),setDefault:this.transformNode(W.setDefault,$),dropDefault:W.dropDefault,setNotNull:W.setNotNull,dropNotNull:W.dropNotNull}}transformModifyColumn(W,$){return{kind:"ModifyColumnNode",column:this.transformNode(W.column,$)}}transformAddConstraint(W,$){return{kind:"AddConstraintNode",constraint:this.transformNode(W.constraint,$)}}transformDropConstraint(W,$){return{kind:"DropConstraintNode",constraintName:this.transformNode(W.constraintName,$),ifExists:W.ifExists,modifier:W.modifier}}transformRenameConstraint(W,$){return{kind:"RenameConstraintNode",oldName:this.transformNode(W.oldName,$),newName:this.transformNode(W.newName,$)}}transformCreateView(W,$){return{kind:"CreateViewNode",name:this.transformNode(W.name,$),temporary:W.temporary,orReplace:W.orReplace,ifNotExists:W.ifNotExists,materialized:W.materialized,columns:this.transformNodeList(W.columns,$),as:this.transformNode(W.as,$)}}transformRefreshMaterializedView(W,$){return{kind:"RefreshMaterializedViewNode",name:this.transformNode(W.name,$),concurrently:W.concurrently,withNoData:W.withNoData}}transformDropView(W,$){return{kind:"DropViewNode",name:this.transformNode(W.name,$),ifExists:W.ifExists,materialized:W.materialized,cascade:W.cascade}}transformGenerated(W,$){return{kind:"GeneratedNode",byDefault:W.byDefault,always:W.always,identity:W.identity,stored:W.stored,expression:this.transformNode(W.expression,$)}}transformDefaultValue(W,$){return{kind:"DefaultValueNode",defaultValue:this.transformNode(W.defaultValue,$)}}transformOn(W,$){return{kind:"OnNode",on:this.transformNode(W.on,$)}}transformSelectModifier(W,$){return{kind:"SelectModifierNode",modifier:W.modifier,rawModifier:this.transformNode(W.rawModifier,$),of:this.transformNodeList(W.of,$)}}transformCreateType(W,$){return{kind:"CreateTypeNode",name:this.transformNode(W.name,$),enum:this.transformNode(W.enum,$)}}transformDropType(W,$){return{kind:"DropTypeNode",name:this.transformNode(W.name,$),additionalNames:this.transformNodeList(W.additionalNames,$),cascade:W.cascade,ifExists:W.ifExists}}transformExplain(W,$){return{kind:"ExplainNode",format:W.format,options:this.transformNode(W.options,$)}}transformSchemableIdentifier(W,$){return{kind:"SchemableIdentifierNode",schema:this.transformNode(W.schema,$),identifier:this.transformNode(W.identifier,$)}}transformAggregateFunction(W,$){return{kind:"AggregateFunctionNode",func:W.func,aggregated:this.transformNodeList(W.aggregated,$),distinct:W.distinct,orderBy:this.transformNode(W.orderBy,$),withinGroup:this.transformNode(W.withinGroup,$),filter:this.transformNode(W.filter,$),over:this.transformNode(W.over,$)}}transformOver(W,$){return{kind:"OverNode",orderBy:this.transformNode(W.orderBy,$),partitionBy:this.transformNode(W.partitionBy,$)}}transformPartitionBy(W,$){return{kind:"PartitionByNode",items:this.transformNodeList(W.items,$)}}transformPartitionByItem(W,$){return{kind:"PartitionByItemNode",partitionBy:this.transformNode(W.partitionBy,$)}}transformBinaryOperation(W,$){return{kind:"BinaryOperationNode",leftOperand:this.transformNode(W.leftOperand,$),operator:this.transformNode(W.operator,$),rightOperand:this.transformNode(W.rightOperand,$)}}transformUnaryOperation(W,$){return{kind:"UnaryOperationNode",operator:this.transformNode(W.operator,$),operand:this.transformNode(W.operand,$)}}transformUsing(W,$){return{kind:"UsingNode",tables:this.transformNodeList(W.tables,$)}}transformFunction(W,$){return{kind:"FunctionNode",func:W.func,arguments:this.transformNodeList(W.arguments,$)}}transformCase(W,$){return{kind:"CaseNode",value:this.transformNode(W.value,$),when:this.transformNodeList(W.when,$),else:this.transformNode(W.else,$),isStatement:W.isStatement}}transformWhen(W,$){return{kind:"WhenNode",condition:this.transformNode(W.condition,$),result:this.transformNode(W.result,$)}}transformJSONReference(W,$){return{kind:"JSONReferenceNode",reference:this.transformNode(W.reference,$),traversal:this.transformNode(W.traversal,$)}}transformJSONPath(W,$){return{kind:"JSONPathNode",inOperator:this.transformNode(W.inOperator,$),pathLegs:this.transformNodeList(W.pathLegs,$)}}transformJSONPathLeg(W,$){return{kind:"JSONPathLegNode",type:W.type,value:W.value}}transformJSONOperatorChain(W,$){return{kind:"JSONOperatorChainNode",operator:this.transformNode(W.operator,$),values:this.transformNodeList(W.values,$)}}transformTuple(W,$){return{kind:"TupleNode",values:this.transformNodeList(W.values,$)}}transformMergeQuery(W,$){return{kind:"MergeQueryNode",into:this.transformNode(W.into,$),using:this.transformNode(W.using,$),whens:this.transformNodeList(W.whens,$),with:this.transformNode(W.with,$),top:this.transformNode(W.top,$),endModifiers:this.transformNodeList(W.endModifiers,$),output:this.transformNode(W.output,$),returning:this.transformNode(W.returning,$)}}transformMatched(W,$){return{kind:"MatchedNode",not:W.not,bySource:W.bySource}}transformAddIndex(W,$){return{kind:"AddIndexNode",name:this.transformNode(W.name,$),columns:this.transformNodeList(W.columns,$),unique:W.unique,using:this.transformNode(W.using,$),ifNotExists:W.ifNotExists}}transformCast(W,$){return{kind:"CastNode",expression:this.transformNode(W.expression,$),dataType:this.transformNode(W.dataType,$)}}transformFetch(W,$){return{kind:"FetchNode",rowCount:this.transformNode(W.rowCount,$),modifier:W.modifier}}transformTop(W,$){return{kind:"TopNode",expression:W.expression,modifiers:W.modifiers}}transformOutput(W,$){return{kind:"OutputNode",selections:this.transformNodeList(W.selections,$)}}transformAlterType(W,$){return{kind:"AlterTypeNode",name:this.transformNode(W.name,$),addValue:this.transformNode(W.addValue,$),renameTo:this.transformNode(W.renameTo,$),renameValue:this.transformNode(W.renameValue,$),setSchema:this.transformNode(W.setSchema,$)}}transformAddValue(W,$){return{kind:"AddValueNode",value:this.transformNode(W.value,$),ifNotExists:W.ifNotExists,isBefore:W.isBefore,neighborValue:this.transformNode(W.neighborValue,$)}}transformRenameValue(W,$){return{kind:"RenameValueNode",oldValue:this.transformNode(W.oldValue,$),newValue:this.transformNode(W.newValue,$)}}transformDataType(W,$){return W}transformSelectAll(W,$){return W}transformIdentifier(W,$){return W}transformValue(W,$){return W}transformPrimitiveValueList(W,$){return W}transformOperator(W,$){return W}transformDefaultInsertValue(W,$){return W}transformOrAction(W,$){return W}transformCollate(W,$){return W}}function N5(W){return Q1(W)&&a(W.kind)}var m2={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0};function C5(W){return N5(W)&&m2[W.kind]===!0}var c2=k({json_agg:!0,to_json:!0});class h6 extends SW{#W;#$=new Set;#Z=new Set;constructor(W){super();this.#W=W}transformNodeImpl(W,$){if(!C5(W))return super.transformNodeImpl(W,$);let Z=this.#k(W);for(let Y of Z)this.#Z.add(Y);let J=this.#Y(W);for(let Y of J)this.#$.add(Y);let X=super.transformNodeImpl(W,$);for(let Y of J)this.#$.delete(Y);for(let Y of Z)this.#Z.delete(Y);return X}transformSchemableIdentifier(W,$){let Z=super.transformSchemableIdentifier(W,$);if(Z.schema||!this.#$.has(W.identifier.name))return Z;return{...Z,schema:l.create(this.#W)}}transformReferences(W,$){let Z=super.transformReferences(W,$);if(Z.table.table.schema)return Z;return{...Z,table:u1.createWithSchema(this.#W,Z.table.table.identifier.name)}}transformAggregateFunction(W,$){return{...super.transformAggregateFunction({...W,aggregated:[]},$),aggregated:this.#X(W,$,"aggregated")}}transformFunction(W,$){return{...super.transformFunction({...W,arguments:[]},$),arguments:this.#X(W,$,"arguments")}}transformSelectModifier(W,$){return{...super.transformSelectModifier({...W,of:void 0},$),of:W.of?.map((Z)=>u1.is(Z)&&!Z.table.schema?{...Z,table:this.transformIdentifier(Z.table.identifier,$)}:this.transformNode(Z,$))}}#X(W,$,Z){return c2[W.func]?W[Z].map((J)=>!u1.is(J)||J.table.schema?this.transformNode(J,$):{...J,table:this.transformIdentifier(J.table.identifier,$)}):this.transformNodeList(W[Z],$)}#Y(W){let $=new Set;if("name"in W&&W.name&&g1.is(W.name))this.#H(W.name,$);if("from"in W&&W.from)for(let Z of W.from.froms)this.#J(Z,$);if("into"in W&&W.into)this.#J(W.into,$);if("table"in W&&W.table)this.#J(W.table,$);if("joins"in W&&W.joins)for(let Z of W.joins)this.#J(Z.table,$);if("using"in W&&W.using)if(G0.is(W.using))this.#J(W.using.table,$);else this.#J(W.using,$);return $}#k(W){let $=new Set;if("with"in W&&W.with)this.#G(W.with,$);return $}#J(W,$){if(u1.is(W))return this.#H(W.table,$);if(q1.is(W)&&u1.is(W.node))return this.#H(W.node.table,$);if(G4.is(W)){for(let Z of W.items)this.#J(Z,$);return}if(FW.is(W)){for(let Z of W.tables)this.#J(Z,$);return}}#H(W,$){let Z=W.identifier.name;if(!this.#$.has(Z)&&!this.#Z.has(Z))$.add(Z)}#G(W,$){for(let Z of W.expressions){let J=Z.name.table.table.identifier.name;if(!this.#Z.has(J))$.add(J)}}}class V0{#W;constructor(W){this.#W=new h6(W)}transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}async transformResult(W){return W.result}}var q5=k({is(W){return W.kind==="MatchedNode"},create(W,$=!1){return k({kind:"MatchedNode",not:W,bySource:$})}});function T6(W,$,Z){return i1.create(q8([q5.create(!W.isMatched,W.bySource),...$&&$.length>0?[$.length===3&&Z?E1($[0],$[1],$[2]):K1($)]:[]],"and",!1))}function g8(W){if(a(W))return X1.create([W],[]);if(G1(W))return W.toOperationNode();return W}class y0{#W;#$;#Z;constructor(){this.#W=new Promise((W,$)=>{this.#Z=$,this.#$=W})}get promise(){return this.#W}resolve=(W)=>{this.#$?.(W),this.#$=this.#Z=void 0};reject=(W)=>{this.#Z?.(W),this.#Z=this.#$=void 0}}async function m8(W,$){let Z=new y0,J=new y0;return W.provideConnection(async(X)=>{return Z.resolve(X),await J.promise},$).catch((X)=>Z.reject(X)),k({connection:await Z.promise,release:J.resolve})}function x5(W="ignore query",$,Z){if(W==="ignore query")return;if(W==="cancel query"){let J=$.cancelQuery;if(!J)O5(W,$.killSession?"kill session":void 0);return J.bind($)}if(W==="kill session"){let J=$.killSession;if(!J)O5(W,$.cancelQuery?"cancel query":void 0);return J.bind($)}throw Z(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${W}"`)}function O5(W,$){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${W}". Use "ignore query"${$?` or "${$}"`:""} instead.`)}function g0(W,$,Z){if(W?.aborted)Z?.(),Z8(W.reason,$)}function Z8(W,$){throw u2(W,$),W}var $0={};async function c8(W,$,Z,J){if(!$)return W;g0($,`before ${Z}`,J);let{promise:X,resolve:Y}=new y0,M=()=>Y($0);$.addEventListener("abort",M);try{g0($,`before ${Z}`,J);let G=await Promise.race([W,X]);if(G!==$0)return G;J?.(),Z8($.reason,`during ${Z}`)}finally{$.removeEventListener("abort",M),Y($0)}}function T0(W){return($)=>console.error(`\`${W}\` failed in the background after abortion: ${d9($)}`)}function u2(W,$){if(W!==null&&typeof W==="object"&&!Object.isFrozen(W))Object.defineProperty(W,"__kysely_timing__",{configurable:!0,enumerable:!1,value:$,writable:!1})}var l2=k([]);class _W{#W;constructor(W=l2){this.#W=W}get plugins(){return this.#W}transformQuery(W,$){for(let Z of this.#W){let J=Z.transformQuery({node:W,queryId:$});if(J.kind===W.kind)W=J;else throw Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${W.kind}`,`but it returned a ${J.kind}`].join(" "))}return W}async executeQuery(W,$){let{inflightQueryAbortStrategy:Z="ignore query",signal:J}=$||{};if(!J){let P=await this.provideConnection(async(w)=>{return await w.executeQuery(W)},$);return await this.#$(P,W.queryId)}g0(J,"before query execution"),$=k({signal:J});let{connection:X,release:Y}=await m8(this,$),M=this.provideConnection.bind(this),{promise:G,resolve:V}=new y0,R=()=>V($0);J.addEventListener("abort",R,{once:!0});try{g0(J,"before query execution",Y);let P=x5(Z,X,Y);if(P&&X.collectSessionInfo){g0(J,"before query execution",Y);let L=X.collectSessionInfo();if(await Promise.race([G,L]).catch((_)=>{throw Y(),_})===$0)L.catch(T0("collectSessionInfo")).finally(Y),Z8(J.reason,"before query execution")}let w=X.executeQuery(W,$),D=await Promise.race([G,w]).catch((L)=>{throw Y(),L});if(D===$0)Promise.allSettled([w.catch(T0("query")),P?.(M).catch(T0("inflightQueryAbortHandler"))]).finally(Y),Z8(J.reason,"during query execution");else Y();let S=this.#$(D,W.queryId,$),F=await Promise.race([G,S]);if(F===$0)S.catch(T0("plugins.transformResult")),Z8(J.reason,"during result transformation");return F}finally{V($0),J.removeEventListener("abort",R)}}async*stream(W,$,Z){let{signal:J}=Z||{};if(!J){let{connection:D,release:S}=await m8(this);try{for await(let F of D.streamQuery(W,$))yield await this.#$(F,W.queryId,Z)}finally{S()}return}Z=k({signal:J}),g0(J,"before connection acquisition");let{connection:X,release:Y}=await m8(this,Z),{promise:M,resolve:G}=new y0,V=()=>G($0);J.addEventListener("abort",V,{once:!0});let R,P;g0(J,"before query streaming",Y);let{queryId:w}=W;try{R=X.streamQuery(W,$,Z);while(!0){g0(J,"during query streaming");let D=R.next(),S=await Promise.race([M,D]);if(S===$0)P=D.catch(T0("iterator.next")),Z8(J.reason,"during query streaming");if(S.done)break;let F=this.#$(S.value,w,Z),L=await Promise.race([M,F]);if(L===$0)P=F.catch(T0("plugins.transformResult")),Z8(J.reason,"during result transformation");yield L}}finally{G($0),J.removeEventListener("abort",V);let D=(R?.return?.()||Promise.resolve()).finally(()=>P).finally(Y);if(!P)await D}}async#$(W,$,Z){let{signal:J}=Z||{};for(let X of this.#W)W=await X.transformResult(k({queryId:$,result:W,signal:J}));return W}}class u8 extends _W{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin(W){return new u8([...this.plugins,W])}withPlugins(W){return new u8([...this.plugins,...W])}withPluginAtFront(W){return new u8([W,...this.plugins])}withoutPlugins(){return new u8([])}}var J8=new u8;class f6{numChangedRows;constructor(W){this.numChangedRows=W}}class m0{#W;constructor(W){this.#W=k(W)}modifyEnd(W){return new m0({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new m0({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}using(...W){return new t1({...this.#W,queryNode:W0.cloneWithUsing(this.#W.queryNode,$8("Using",W))})}returning(W){return new m0({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new m0({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new m0({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new m0({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}}class t1{#W;constructor(W){this.#W=k(W)}modifyEnd(W){return new t1({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,W.toOperationNode())})}top(W,$){return new t1({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}whenMatched(){return this.#$([])}whenMatchedAnd(...W){return this.#$(W)}whenMatchedAndRef(W,$,Z){return this.#$([W,$,Z],!0)}#$(W,$){return new j6({...this.#W,queryNode:W0.cloneWithWhen(this.#W.queryNode,T6({isMatched:!0},W,$))})}whenNotMatched(){return this.#Z([])}whenNotMatchedAnd(...W){return this.#Z(W)}whenNotMatchedAndRef(W,$,Z){return this.#Z([W,$,Z],!0)}whenNotMatchedBySource(){return this.#Z([],!1,!0)}whenNotMatchedBySourceAnd(...W){return this.#Z(W,!1,!0)}whenNotMatchedBySourceAndRef(W,$,Z){return this.#Z([W,$,Z],!0,!0)}returning(W){return new t1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,j1(W))})}returningAll(W){return new t1({...this.#W,queryNode:y.cloneWithReturning(this.#W.queryNode,x1(W))})}output(W){return new t1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,j1(W))})}outputAll(W){return new t1({...this.#W,queryNode:y.cloneWithOutput(this.#W.queryNode,x1(W))})}#Z(W,$=!1,Z=!1){let J={...this.#W,queryNode:W0.cloneWithWhen(this.#W.queryNode,T6({isMatched:!1,bySource:Z},W,$))};return new(Z?j6:B5)(J)}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new t1({...this.#W})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile(),Z=await this.#W.executor.executeQuery($,W),{adapter:J}=this.#W.executor,X=$.query;if(X.returning&&J.supportsReturning||X.output&&J.supportsOutput)return Z.rows;return[new f6(Z.numAffectedRows)]}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??K0;throw E0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}}class j6{#W;constructor(W){this.#W=k(W)}thenDelete(){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,g8("delete"))})}thenDoNothing(){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,g8("do nothing"))})}thenUpdate(W){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,g8(W(new I8({queryId:this.#W.queryId,executor:J8,queryNode:v0.createWithoutTable()}))))})}thenUpdateSet(...W){return this.thenUpdate(($)=>$.set(...W))}}class B5{#W;constructor(W){this.#W=k(W)}thenDoNothing(){return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,g8("do nothing"))})}thenInsertValues(W){let[$,Z]=L4(W);return new t1({...this.#W,queryNode:W0.cloneWithThen(this.#W.queryNode,g8(S1.cloneWith(S1.createWithoutInto(),{columns:$,values:Z})))})}}class f0{#W;constructor(W){this.#W=k(W)}selectFrom(W){return vW({queryId:W1(),executor:this.#W.executor,queryNode:k1.createFrom(U0(W),this.#W.withNode)})}selectNoFrom(W){return vW({queryId:W1(),executor:this.#W.executor,queryNode:k1.cloneWithSelections(k1.create(this.#W.withNode),j1(W))})}insertInto(W){return new L1({queryId:W1(),executor:this.#W.executor,queryNode:S1.create(Z1(W),this.#W.withNode)})}replaceInto(W){return new L1({queryId:W1(),executor:this.#W.executor,queryNode:S1.create(Z1(W),this.#W.withNode,!0)})}deleteFrom(W){return new K4({queryId:W1(),executor:this.#W.executor,queryNode:W8.create(U0(W),this.#W.withNode)})}updateTable(W){return new I8({queryId:W1(),executor:this.#W.executor,queryNode:v0.create(U0(W),this.#W.withNode)})}mergeInto(W){return new m0({queryId:W1(),executor:this.#W.executor,queryNode:W0.create(A6(W),this.#W.withNode)})}with(W,$){let Z=E6(W,$);return new f0({...this.#W,withNode:this.#W.withNode?QW.cloneWithExpression(this.#W.withNode,Z):QW.create(Z)})}withRecursive(W,$){let Z=E6(W,$);return new f0({...this.#W,withNode:this.#W.withNode?QW.cloneWithExpression(this.#W.withNode,Z):QW.create(Z,{recursive:!0})})}withPlugin(W){return new f0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new f0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new f0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}}function T5(){return new f0({executor:J8})}function b5(W,$){return new O8({joinNode:G0.create(W,V8($))})}function I5(){return new x8({overNode:PW.create()})}function $8(W,$){if($.length===3)return i2(W,$[0],$[1],$[2]);else if($.length===2)return p2(W,$[0],$[1]);else if($.length===1)return t2(W,$[0]);else throw Error("not implemented")}function p2(W,$,Z){return Z(b5(W,$)).toOperationNode()}function i2(W,$,Z,J){return G0.createWithOn(W,V8($),E1(Z,"=",J))}function t2(W,$){return G0.create(W,V8($))}var y5=k({is(W){return W.kind==="OffsetNode"},create(W){return k({kind:"OffsetNode",offset:W})}});var g5=k({is(W){return W.kind==="GroupByItemNode"},create(W){return k({kind:"GroupByItemNode",groupBy:W})}});function m5(W){return W=R1(W)?W(L0()):W,b0(W).map(g5.create)}var z4=k({is(W){return W.kind==="SetOperationNode"},create(W,$,Z){return k({kind:"SetOperationNode",operator:W,expression:$,all:Z})}});function P8(W,$,Z){if(R1($))$=$(N6());if(!y1($))$=[$];return $.map((J)=>z4.create(W,O1(J),Z))}class Y1{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new P4(this,W)}or(...W){return new U4(k0.create(this.#W,K1(W)))}and(...W){return new V4(l1.create(this.#W,K1(W)))}$castTo(){return new Y1(this.#W)}$notNull(){return new Y1(this.#W)}toOperationNode(){return this.#W}}class P4{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return q1.create(this.#W.toOperationNode(),G1(this.#$)?this.#$.toOperationNode():l.create(this.#$))}}class U4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new P4(this,W)}or(...W){return new U4(k0.create(this.#W,K1(W)))}$castTo(){return new U4(this.#W)}toOperationNode(){return e1.create(this.#W)}}class V4{#W;constructor(W){this.#W=W}get expressionType(){return}as(W){return new P4(this,W)}and(...W){return new V4(l1.create(this.#W,K1(W)))}$castTo(){return new V4(this.#W)}toOperationNode(){return e1.create(this.#W)}}var c5=k({is(W){return W.kind==="FetchNode"},create(W,$){return{kind:"FetchNode",rowCount:D1.create(W),modifier:$}}});function u5(W,$){if(!d0(W)&&!h8(W))throw Error(`Invalid fetch row count: ${W}`);if(!a2($))throw Error(`Invalid fetch modifier: ${$}`);return c5.create(W,$)}function a2(W){return W==="only"||W==="with ties"}var n;class C6{#W;constructor(W){this.#W=k(W)}get expressionType(){return}get isSelectQueryBuilder(){return!0}where(...W){return new n({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,K1(W))})}whereRef(W,$,Z){return new n({...this.#W,queryNode:y.cloneWithWhere(this.#W.queryNode,E1(W,$,Z))})}having(...W){return new n({...this.#W,queryNode:k1.cloneWithHaving(this.#W.queryNode,K1(W))})}havingRef(W,$,Z){return new n({...this.#W,queryNode:k1.cloneWithHaving(this.#W.queryNode,E1(W,$,Z))})}select(W){return new n({...this.#W,queryNode:k1.cloneWithSelections(this.#W.queryNode,j1(W))})}distinctOn(W){return new n({...this.#W,queryNode:k1.cloneWithDistinctOn(this.#W.queryNode,b0(W))})}modifyFront(W){return new n({...this.#W,queryNode:k1.cloneWithFrontModifier(this.#W.queryNode,_0.createWithExpression(W.toOperationNode()))})}modifyEnd(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.createWithExpression(W.toOperationNode()))})}distinct(){return new n({...this.#W,queryNode:k1.cloneWithFrontModifier(this.#W.queryNode,_0.create("Distinct"))})}forUpdate(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForUpdate",W?zW(W).map(Z1):void 0))})}forShare(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForShare",W?zW(W).map(Z1):void 0))})}forKeyShare(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForKeyShare",W?zW(W).map(Z1):void 0))})}forNoKeyUpdate(W){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("ForNoKeyUpdate",W?zW(W).map(Z1):void 0))})}skipLocked(){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("SkipLocked"))})}noWait(){return new n({...this.#W,queryNode:y.cloneWithEndModifier(this.#W.queryNode,_0.create("NoWait"))})}selectAll(W){return new n({...this.#W,queryNode:k1.cloneWithSelections(this.#W.queryNode,x1(W))})}innerJoin(...W){return this.#$("InnerJoin",W)}leftJoin(...W){return this.#$("LeftJoin",W)}rightJoin(...W){return this.#$("RightJoin",W)}fullJoin(...W){return this.#$("FullJoin",W)}crossJoin(...W){return this.#$("CrossJoin",W)}innerJoinLateral(...W){return this.#$("LateralInnerJoin",W)}leftJoinLateral(...W){return this.#$("LateralLeftJoin",W)}crossJoinLateral(...W){return this.#$("LateralCrossJoin",W)}crossApply(...W){return this.#$("CrossApply",W)}outerApply(...W){return this.#$("OuterApply",W)}#$(W,$){return new n({...this.#W,queryNode:y.cloneWithJoin(this.#W.queryNode,$8(W,$))})}orderBy(...W){return new n({...this.#W,queryNode:y.cloneWithOrderByItems(this.#W.queryNode,o1(W))})}groupBy(W){return new n({...this.#W,queryNode:k1.cloneWithGroupByItems(this.#W.queryNode,m5(W))})}limit(W){return new n({...this.#W,queryNode:k1.cloneWithLimit(this.#W.queryNode,b8.create(M1(W)))})}offset(W){return new n({...this.#W,queryNode:k1.cloneWithOffset(this.#W.queryNode,y5.create(M1(W)))})}fetch(W,$="only"){return new n({...this.#W,queryNode:k1.cloneWithFetch(this.#W.queryNode,u5(W,$))})}top(W,$){return new n({...this.#W,queryNode:y.cloneWithTop(this.#W.queryNode,z0(W,$))})}union(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("union",W,!1))})}unionAll(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("union",W,!0))})}intersect(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("intersect",W,!1))})}intersectAll(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("intersect",W,!0))})}except(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("except",W,!1))})}exceptAll(W){return new n({...this.#W,queryNode:k1.cloneWithSetOperations(this.#W.queryNode,P8("except",W,!0))})}as(W){return new l5(this,W)}clearSelect(){return new n({...this.#W,queryNode:k1.cloneWithoutSelections(this.#W.queryNode)})}clearWhere(){return new n({...this.#W,queryNode:y.cloneWithoutWhere(this.#W.queryNode)})}clearLimit(){return new n({...this.#W,queryNode:k1.cloneWithoutLimit(this.#W.queryNode)})}clearOffset(){return new n({...this.#W,queryNode:k1.cloneWithoutOffset(this.#W.queryNode)})}clearOrderBy(){return new n({...this.#W,queryNode:y.cloneWithoutOrderBy(this.#W.queryNode)})}clearGroupBy(){return new n({...this.#W,queryNode:k1.cloneWithoutGroupBy(this.#W.queryNode)})}$call(W){return W(this)}$if(W,$){if(W)return $(this);return new n({...this.#W})}$castTo(){return new n(this.#W)}$narrowType(){return new n(this.#W)}$assertType(){return new n(this.#W)}$asTuple(){return new Y1(this.toOperationNode())}$asScalar(){return new Y1(this.toOperationNode())}withPlugin(W){return new n({...this.#W,executor:this.#W.executor.withPlugin(W)})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.queryNode,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){let $=this.compile();return(await this.#W.executor.executeQuery($,W)).rows}async executeTakeFirst(W){let[$]=await this.execute(W);return $}async executeTakeFirstOrThrow(W){if(typeof W==="function")W={errorConstructor:W};let $=await this.executeTakeFirst(W);if($===void 0){let Z=W?.errorConstructor??K0;throw E0(Z)?new Z(this.toOperationNode()):Z(this.toOperationNode())}return $}async*stream(W){if(typeof W!=="object")W={chunkSize:W};let $=this.compile(),Z=this.#W.executor.stream($,W.chunkSize??100,W);for await(let J of Z)yield*J.rows}async explain(W,$){return await new n({...this.#W,queryNode:y.cloneWithExplain(this.#W.queryNode,W,$)}).execute()}}n=C6;function vW(W){return new C6(W)}class l5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return q1.create(this.#W.toOperationNode(),l.create(this.#$))}}var j0=k({is(W){return W.kind==="AggregateFunctionNode"},create(W,$=[]){return k({kind:"AggregateFunctionNode",func:W,aggregated:$})},cloneWithDistinct(W){return k({...W,distinct:!0})},cloneWithOrderBy(W,$,Z=!1){let J=Z?"withinGroup":"orderBy";return k({...W,[J]:W[J]?I0.cloneWithItems(W[J],$):I0.create($)})},cloneWithFilter(W,$){return k({...W,filter:W.filter?b1.cloneWithOperation(W.filter,"And",$):b1.create($)})},cloneWithOrFilter(W,$){return k({...W,filter:W.filter?b1.cloneWithOperation(W.filter,"Or",$):b1.create($)})},cloneWithOver(W,$){return k({...W,over:$})}});var q6=k({is(W){return W.kind==="FunctionNode"},create(W,$){return k({kind:"FunctionNode",func:W,arguments:$})}});class a1{#W;constructor(W){this.#W=k(W)}get expressionType(){return}as(W){return new p5(this,W)}distinct(){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithDistinct(this.#W.aggregateFunctionNode)})}orderBy(...W){return new a1({...this.#W,aggregateFunctionNode:y.cloneWithOrderByItems(this.#W.aggregateFunctionNode,o1(W))})}clearOrderBy(){return new a1({...this.#W,aggregateFunctionNode:y.cloneWithoutOrderBy(this.#W.aggregateFunctionNode)})}withinGroupOrderBy(...W){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithOrderBy(this.#W.aggregateFunctionNode,o1(W),!0)})}filterWhere(...W){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithFilter(this.#W.aggregateFunctionNode,K1(W))})}filterWhereRef(W,$,Z){return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithFilter(this.#W.aggregateFunctionNode,E1(W,$,Z))})}over(W){let $=I5();return new a1({...this.#W,aggregateFunctionNode:j0.cloneWithOver(this.#W.aggregateFunctionNode,(W?W($):$).toOperationNode())})}$call(W){return W(this)}$castTo(){return new a1(this.#W)}$notNull(){return new a1(this.#W)}toOperationNode(){return this.#W.aggregateFunctionNode}}class p5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return q1.create(this.#W.toOperationNode(),l.create(this.#$))}}function F4(){let W=(Z,J)=>{return new Y1(q6.create(Z,b0(J??[])))},$=(Z,J)=>{return new a1({aggregateFunctionNode:j0.create(Z,J?b0(J):void 0)})};return Object.assign(W,{agg:$,avg(Z){return $("avg",[Z])},coalesce(...Z){return W("coalesce",Z)},count(Z){return $("count",[Z])},countAll(Z){return new a1({aggregateFunctionNode:j0.create("count",x1(Z))})},max(Z){return $("max",[Z])},min(Z){return $("min",[Z])},sum(Z){return $("sum",[Z])},any(Z){return W("any",[Z])},jsonAgg(Z){return new a1({aggregateFunctionNode:j0.create("json_agg",[a(Z)?Z1(Z):Z.toOperationNode()])})},toJson(Z){return new Y1(q6.create("to_json",[a(Z)?Z1(Z):Z.toOperationNode()]))}})}var i5=k({is(W){return W.kind==="UnaryOperationNode"},create(W,$){return k({kind:"UnaryOperationNode",operator:W,operand:$})}});function t5(W,$){if(Y5(W))return i5.create(r1.create(W),T1($));throw Error(`invalid unary operator ${JSON.stringify(W)}`)}var I1=k({is(W){return W.kind==="CaseNode"},create(W){return k({kind:"CaseNode",value:W})},cloneWithWhen(W,$){return k({...W,when:k(W.when?[...W.when,$]:[$])})},cloneWithThen(W,$){return k({...W,when:W.when?k([...W.when.slice(0,-1),i1.cloneWithResult(W.when[W.when.length-1],$)]):void 0})},cloneWith(W,$){return k({...W,...$})}});class hW{#W;constructor(W){this.#W=k(W)}when(...W){return new EW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(K1(W)))})}whenRef(W,$,Z){return new EW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(E1(W,$,Z)))})}}class EW{#W;constructor(W){this.#W=k(W)}then(W){return new O6({...this.#W,node:I1.cloneWithThen(this.#W.node,H4(W)?VW(W):M1(W))})}thenRef(W){return new O6({...this.#W,node:I1.cloneWithThen(this.#W.node,T1(W))})}}class O6{#W;constructor(W){this.#W=k(W)}when(...W){return new EW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(K1(W)))})}whenRef(W,$,Z){return new EW({...this.#W,node:I1.cloneWithWhen(this.#W.node,i1.create(E1(W,$,Z)))})}else(W){return new x6({...this.#W,node:I1.cloneWith(this.#W.node,{else:H4(W)?VW(W):M1(W)})})}elseRef(W){return new x6({...this.#W,node:I1.cloneWith(this.#W.node,{else:T1(W)})})}end(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!0}))}}class x6{#W;constructor(W){this.#W=k(W)}end(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!1}))}endCase(){return new Y1(I1.cloneWith(this.#W.node,{isStatement:!0}))}}var B6=k({is(W){return W.kind==="JSONPathLegNode"},create(W,$){return k({kind:"JSONPathLegNode",type:W,value:$})}});var d2=/^#-\d+$/;class fW{#W;constructor(W){this.#W=W}at(W){if(typeof W!=="number"&&typeof W!=="string"||typeof W==="number"&&!Number.isInteger(W)||typeof W==="string"&&W!=="last"&&!d2.test(W))throw Error(`Unexpected index value in .at(...): ${W}`);return this.#$("ArrayLocation",W)}key(W){return this.#$("Member",W)}#$(W,$){if(N8.is(this.#W))return new TW(N8.cloneWithTraversal(this.#W,o0.is(this.#W.traversal)?o0.cloneWithLeg(this.#W.traversal,B6.create(W,$)):X4.cloneWithValue(this.#W.traversal,D1.createImmediate($))));return new TW(o0.cloneWithLeg(this.#W,B6.create(W,$)))}}class TW extends fW{#W;constructor(W){super(W);this.#W=W}get expressionType(){return}as(W){return new a5(this,W)}$castTo(){return new TW(this.#W)}$notNull(){return new TW(this.#W)}toOperationNode(){return this.#W}}class a5{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}toOperationNode(){return q1.create(this.#W.toOperationNode(),G1(this.#$)?this.#$.toOperationNode():l.create(this.#$))}}var b6=k({is(W){return W.kind==="TupleNode"},create(W){return k({kind:"TupleNode",values:k(W)})}});var s2=k({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),n2=k([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),d5=k({is(W){return W.kind==="DataTypeNode"},create(W){return k({kind:"DataTypeNode",dataType:W})}});function s5(W){return s2[W]||n2.some(($)=>$.test(W))}function P0(W){if(G1(W))return W.toOperationNode();if(s5(W))return d5.create(W);throw Error(`invalid column data type ${JSON.stringify(W)}`)}var n5=k({is(W){return W.kind==="CastNode"},create(W,$){return k({kind:"CastNode",expression:W,dataType:$})}});function N6(W=J8){function $(X,Y,M){return new Y1(k4(X,Y,M))}function Z(X,Y){return new Y1(t5(X,Y))}let J=Object.assign($,{fn:void 0,eb:void 0,selectFrom(X){return vW({queryId:W1(),executor:W,queryNode:k1.createFrom(U0(X))})},case(X){return new hW({node:I1.create(n1(X)?void 0:T1(X))})},ref(X,Y){if(n1(Y))return new Y1(p1(X));return new fW(M5(X,Y))},jsonPath(){return new fW(o0.create())},table(X){return new Y1(Z1(X))},val(X){return new Y1(M1(X))},refTuple(...X){return new Y1(b6.create(X.map(T1)))},tuple(...X){return new Y1(b6.create(X.map(M1)))},lit(X){return new Y1(VW(X))},unary:Z,not(X){return Z("not",X)},exists(X){return Z("exists",X)},neg(X){return Z("-",X)},between(X,Y,M){return new Y1(n0.create(T1(X),r1.create("between"),l1.create(M1(Y),M1(M))))},betweenSymmetric(X,Y,M){return new Y1(n0.create(T1(X),r1.create("between symmetric"),l1.create(M1(Y),M1(M))))},and(X){if(y1(X))return new Y1(q8(X,"and"));return new Y1(U6(X,"and"))},or(X){if(y1(X))return new Y1(q8(X,"or"));return new Y1(U6(X,"or"))},parens(...X){let Y=K1(X);if(e1.is(Y))return new Y1(Y);else return new Y1(e1.create(Y))},cast(X,Y){return new Y1(n5.create(T1(X),P0(Y)))}});return J.fn=F4(),J.eb=J,J}function L0(W){return N6()}function O1(W){if(G1(W))return W.toOperationNode();else if(R1(W))return W(L0()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(W)}`)}function M4(W){if(G1(W))return W.toOperationNode();else if(R1(W))return W(L0()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(W)}`)}function B0(W){return $4(W)||n9(W)||R1(W)}class I6{#W;get table(){return this.#W}constructor(W){this.#W=W}as(W){return new r5(this.#W,W)}}class r5{#W;#$;get table(){return this.#W}get alias(){return this.#$}constructor(W,$){this.#W=W,this.#$=$}toOperationNode(){return q1.create(Z1(this.#W),l.create(this.#$))}}function o5(W){return Q1(W)&&G1(W)&&a(W.table)&&a(W.alias)}function U0(W){if(y1(W))return W.map(($)=>V8($));else return[V8(W)]}function V8(W){if(a(W))return A6(W);else if(o5(W))return W.toOperationNode();else return M4(W)}function A6(W){if(W.includes(" as ")){let[Z,J]=W.split(" as ").map(e5);return q1.create(Z1(Z),l.create(J))}else return Z1(W)}function Z1(W){if(W.includes(".")){let[Z,J]=W.split(".").map(e5);return u1.createWithSchema(Z,J)}else return u1.create(W)}function e5(W){return W.trim()}var y6=k({is(W){return W.kind==="AddColumnNode"},create(W){return k({kind:"AddColumnNode",column:W})}});var z1=k({is(W){return W.kind==="ColumnDefinitionNode"},create(W,$){return k({kind:"ColumnDefinitionNode",column:e.create(W),dataType:$})},cloneWithFrontModifier(W,$){return k({...W,frontModifiers:W.frontModifiers?k([...W.frontModifiers,$]):[$]})},cloneWithEndModifier(W,$){return k({...W,endModifiers:W.endModifiers?k([...W.endModifiers,$]):[$]})},cloneWith(W,$){return k({...W,...$})}});var jW=k({is(W){return W.kind==="DropColumnNode"},create(W){return k({kind:"DropColumnNode",column:e.create(W)})},cloneWith(W,$){return k({...W,...$})}});var g6=k({is(W){return W.kind==="RenameColumnNode"},create(W,$){return k({kind:"RenameColumnNode",column:e.create(W),renameTo:e.create($)})}});var l8=k({is(W){return W.kind==="CheckConstraintNode"},create(W,$){return k({kind:"CheckConstraintNode",expression:W,name:$?l.create($):void 0})}});var W7=k({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0}),$V=Object.keys(W7),p8=k({is(W){return W.kind==="ReferencesNode"},create(W,$){return k({kind:"ReferencesNode",table:W,columns:k([...$])})},cloneWithOnDelete(W,$){return k({...W,onDelete:$})},cloneWithOnUpdate(W,$){return k({...W,onUpdate:$})}});function $7(W){return a(W)&&W7[W]}function R4(W){return G1(W)?W.toOperationNode():D1.createImmediate(W)}var AW=k({is(W){return W.kind==="GeneratedNode"},create(W){return k({kind:"GeneratedNode",...W})},createWithExpression(W){return k({kind:"GeneratedNode",always:!0,expression:W})},cloneWith(W,$){return k({...W,...$})}});var Z7=k({is(W){return W.kind==="DefaultValueNode"},create(W){return k({kind:"DefaultValueNode",defaultValue:W})}});function i8(W){if($7(W))return W;throw Error(`invalid OnModifyForeignAction ${W}`)}class U1{#W;constructor(W){this.#W=W}autoIncrement(){return new U1(z1.cloneWith(this.#W,{autoIncrement:!0}))}identity(){return new U1(z1.cloneWith(this.#W,{identity:!0}))}primaryKey(){return new U1(z1.cloneWith(this.#W,{primaryKey:!0}))}references(W){let $=p1(W);if(!$.table||f8.is($.column))throw Error(`invalid call references('${W}'). The reference must have format table.column or schema.table.column`);return new U1(z1.cloneWith(this.#W,{references:p8.create($.table,[$.column])}))}onDelete(W){if(!this.#W.references)throw Error("on delete constraint can only be added for foreign keys");return new U1(z1.cloneWith(this.#W,{references:p8.cloneWithOnDelete(this.#W.references,i8(W))}))}onUpdate(W){if(!this.#W.references)throw Error("on update constraint can only be added for foreign keys");return new U1(z1.cloneWith(this.#W,{references:p8.cloneWithOnUpdate(this.#W.references,i8(W))}))}unique(){return new U1(z1.cloneWith(this.#W,{unique:!0}))}notNull(){return new U1(z1.cloneWith(this.#W,{notNull:!0}))}unsigned(){return new U1(z1.cloneWith(this.#W,{unsigned:!0}))}defaultTo(W){return new U1(z1.cloneWith(this.#W,{defaultTo:Z7.create(R4(W))}))}check(W){return new U1(z1.cloneWith(this.#W,{check:l8.create(W.toOperationNode())}))}generatedAlwaysAs(W){return new U1(z1.cloneWith(this.#W,{generated:AW.createWithExpression(W.toOperationNode())}))}generatedAlwaysAsIdentity(){return new U1(z1.cloneWith(this.#W,{generated:AW.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new U1(z1.cloneWith(this.#W,{generated:AW.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#W.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new U1(z1.cloneWith(this.#W,{generated:AW.cloneWith(this.#W.generated,{stored:!0})}))}modifyFront(W){return new U1(z1.cloneWithFrontModifier(this.#W,W.toOperationNode()))}nullsNotDistinct(){return new U1(z1.cloneWith(this.#W,{nullsNotDistinct:!0}))}ifNotExists(){return new U1(z1.cloneWith(this.#W,{ifNotExists:!0}))}modifyEnd(W){return new U1(z1.cloneWithEndModifier(this.#W,W.toOperationNode()))}$call(W){return W(this)}toOperationNode(){return this.#W}}var m6=k({is(W){return W.kind==="ModifyColumnNode"},create(W){return k({kind:"ModifyColumnNode",column:W})}});var F0=k({is(W){return W.kind==="ForeignKeyConstraintNode"},create(W,$,Z,J){return k({kind:"ForeignKeyConstraintNode",columns:W,references:p8.create($,Z),name:J?l.create(J):void 0})},cloneWith(W,$){return k({...W,...$})}});class R0{#W;constructor(W){this.#W=W}onDelete(W){return new R0(F0.cloneWith(this.#W,{onDelete:i8(W)}))}onUpdate(W){return new R0(F0.cloneWith(this.#W,{onUpdate:i8(W)}))}deferrable(){return new R0(F0.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new R0(F0.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new R0(F0.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new R0(F0.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}var t8=k({is(W){return W.kind==="AddConstraintNode"},create(W){return k({kind:"AddConstraintNode",constraint:W})}});var A0=k({is(W){return W.kind==="UniqueConstraintNode"},create(W,$,Z){if(a(W.at(0)))A8("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),W=W.map(e.create);return k({kind:"UniqueConstraintNode",columns:k(W),name:$?l.create($):void 0,nullsNotDistinct:Z})},cloneWith(W,$){return k({...W,...$})}});var a8=k({is(W){return W.kind==="DropConstraintNode"},create(W){return k({kind:"DropConstraintNode",constraintName:l.create(W)})},cloneWith(W,$){return k({...W,...$})}});var d8=k({is(W){return W.kind==="AlterColumnNode"},create(W,$,Z){return k({kind:"AlterColumnNode",column:e.create(W),[$]:Z})}});class D4{#W;constructor(W){this.#W=W}setDataType(W){return new s8(d8.create(this.#W,"dataType",P0(W)))}setDefault(W){return new s8(d8.create(this.#W,"setDefault",R4(W)))}dropDefault(){return new s8(d8.create(this.#W,"dropDefault",!0))}setNotNull(){return new s8(d8.create(this.#W,"setNotNull",!0))}dropNotNull(){return new s8(d8.create(this.#W,"dropNotNull",!0))}$call(W){return W(this)}}class s8{#W;constructor(W){this.#W=W}toOperationNode(){return this.#W}}class X8{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class c0{#W;constructor(W){this.#W=k(W)}onDelete(W){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.onDelete(W)})}onUpdate(W){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.onUpdate(W)})}deferrable(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.deferrable()})}notDeferrable(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new c0({...this.#W,constraintBuilder:this.#W.constraintBuilder.initiallyImmediate()})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery($1.cloneWithTableProps(this.#W.node,{addConstraint:t8.create(this.#W.constraintBuilder.toOperationNode())}),this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class F8{#W;constructor(W){this.#W=k(W)}ifExists(){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:a8.cloneWith(this.#W.node.dropConstraint,{ifExists:!0})})})}cascade(){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:a8.cloneWith(this.#W.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:a8.cloneWith(this.#W.node.dropConstraint,{modifier:"restrict"})})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var u0=k({is(W){return W.kind==="PrimaryKeyConstraintNode"},create(W,$){return k({kind:"PrimaryKeyConstraintNode",columns:k(W.map(e.create)),name:$?l.create($):void 0})},cloneWith(W,$){return k({...W,...$})}});var Z0=k({is(W){return W.kind==="AddIndexNode"},create(W){return k({kind:"AddIndexNode",name:l.create(W)})},cloneWith(W,$){return k({...W,...$})},cloneWithColumns(W,$){return k({...W,columns:[...W.columns||[],...$]})}});class Y8{#W;constructor(W){this.#W=k(W)}unique(){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWith(this.#W.node.addIndex,{unique:!0})})})}column(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWithColumns(this.#W.node.addIndex,[a(W)?C8(W):W.toOperationNode()])})})}columns(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWithColumns(this.#W.node.addIndex,W.map(($)=>a($)?C8($):$.toOperationNode()))})})}expression(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWithColumns(this.#W.node.addIndex,[W.toOperationNode()])})})}using(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.cloneWith(this.#W.node.addIndex,{using:X1.createWithSql(W)})})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class N0{#W;constructor(W){this.#W=W}nullsNotDistinct(){return new N0(A0.cloneWith(this.#W,{nullsNotDistinct:!0}))}deferrable(){return new N0(A0.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new N0(A0.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new N0(A0.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new N0(A0.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class l0{#W;constructor(W){this.#W=W}deferrable(){return new l0(u0.cloneWith(this.#W,{deferrable:!0}))}notDeferrable(){return new l0(u0.cloneWith(this.#W,{deferrable:!1}))}initiallyDeferred(){return new l0(u0.cloneWith(this.#W,{initiallyDeferred:!0}))}initiallyImmediate(){return new l0(u0.cloneWith(this.#W,{initiallyDeferred:!1}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class NW{#W;constructor(W){this.#W=W}$call(W){return W(this)}toOperationNode(){return this.#W}}var J7=k({is(W){return W.kind==="RenameConstraintNode"},create(W,$){return k({kind:"RenameConstraintNode",oldName:l.create(W),newName:l.create($)})}});class CW{#W;constructor(W){this.#W=k({...W})}ifExists(){return new CW({...this.#W,node:jW.cloneWith(this.#W.node,{ifExists:!0})})}toOperationNode(){return this.#W.node}}class c6{#W;constructor(W){this.#W=k(W)}renameTo(W){return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{renameTo:Z1(W)})})}setSchema(W){return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{setSchema:l.create(W)})})}alterColumn(W,$){let Z=$(new D4(W));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}dropColumn(W,$=N1){let Z=$(new CW({node:jW.create(W)}));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}renameColumn(W,$){return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,g6.create(W,$))})}addColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,y6.create(J.toOperationNode()))})}modifyColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,m6.create(J.toOperationNode()))})}addUniqueConstraint(W,$,Z=N1){let J=Z(new N0(A0.create($.map((X)=>a(X)?e.create(X):O1(X)),W)));return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addConstraint:t8.create(J.toOperationNode())})})}addCheckConstraint(W,$,Z=N1){let J=Z(new NW(l8.create($.toOperationNode(),W)));return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addConstraint:t8.create(J.toOperationNode())})})}addForeignKeyConstraint(W,$,Z,J,X=N1){let Y=X(new R0(F0.create($.map(e.create),Z1(Z),J.map(e.create),W)));return new c0({...this.#W,constraintBuilder:Y})}addPrimaryKeyConstraint(W,$,Z=N1){let J=Z(new l0(u0.create($,W)));return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addConstraint:t8.create(J.toOperationNode())})})}dropConstraint(W){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropConstraint:a8.create(W)})})}renameConstraint(W,$){return new F8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{renameConstraint:J7.create(W,$)})})}addIndex(W){return new Y8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{addIndex:Z0.create(W)})})}dropIndex(W){return new X8({...this.#W,node:$1.cloneWithTableProps(this.#W.node,{dropIndex:s0.create(W)})})}$call(W){return W(this)}}class D0{#W;constructor(W){this.#W=k(W)}alterColumn(W,$){let Z=$(new D4(W));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}dropColumn(W,$=N1){let Z=$(new CW({node:jW.create(W)}));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,Z.toOperationNode())})}renameColumn(W,$){return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,g6.create(W,$))})}addColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,y6.create(J.toOperationNode()))})}modifyColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new D0({...this.#W,node:$1.cloneWithColumnAlteration(this.#W.node,m6.create(J.toOperationNode()))})}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class qW extends SW{transformPrimitiveValueList(W){return e0.create(W.values.map(D1.createImmediate))}transformValue(W){return D1.createImmediate(W.value)}}class J0{#W;constructor(W){this.#W=k(W)}ifNotExists(){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{ifNotExists:!0})})}unique(){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{unique:!0})})}nullsNotDistinct(){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{nullsNotDistinct:!0})})}on(W){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{table:Z1(W)})})}column(W){return new J0({...this.#W,node:H0.cloneWithColumns(this.#W.node,[a(W)?C8(W):W.toOperationNode()])})}columns(W){return new J0({...this.#W,node:H0.cloneWithColumns(this.#W.node,W.map(($)=>a($)?C8($):$.toOperationNode()))})}expression(W){return new J0({...this.#W,node:H0.cloneWithColumns(this.#W.node,[W.toOperationNode()])})}using(W){return new J0({...this.#W,node:H0.cloneWith(this.#W.node,{using:X1.createWithSql(W)})})}where(...W){let $=new qW;return new J0({...this.#W,node:y.cloneWithWhere(this.#W.node,$.transformNode(K1(W),this.#W.queryId))})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class w4{#W;constructor(W){this.#W=k(W)}ifNotExists(){return new w4({...this.#W,node:W4.cloneWith(this.#W.node,{ifNotExists:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}function X7(W){if(s9.includes(W))return W;throw Error(`invalid OnCommitAction ${W}`)}class Q4{#W;constructor(W){this.#W=W}using(W){return new Q4(Z0.cloneWith(this.#W,{using:X1.createWithSql(W)}))}$call(W){return W(this)}toOperationNode(){return this.#W}}class c1{#W;constructor(W){this.#W=k(W)}temporary(){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{temporary:!0})})}onCommit(W){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{onCommit:X7(W)})})}ifNotExists(){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{ifNotExists:!0})})}addColumn(W,$,Z=N1){let J=Z(new U1(z1.create(W,P0($))));return new c1({...this.#W,node:C1.cloneWithColumn(this.#W.node,J.toOperationNode())})}addPrimaryKeyConstraint(W,$,Z=N1){let J=Z(new l0(u0.create($,W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addUniqueConstraint(W,$,Z=N1){let J=Z(new N0(A0.create($.map((X)=>a(X)?e.create(X):O1(X)),W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addIndex(W,$,Z=N1){let J=Z(new Q4(Z0.cloneWithColumns(Z0.create(W),$.map((X)=>a(X)?e.create(X):O1(X)))));return new c1({...this.#W,node:C1.cloneWithIndex(this.#W.node,J.toOperationNode())})}addCheckConstraint(W,$,Z=N1){let J=Z(new NW(l8.create($.toOperationNode(),W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,J.toOperationNode())})}addForeignKeyConstraint(W,$,Z,J,X=N1){let Y=X(new R0(F0.create($.map(e.create),Z1(Z),J.map(e.create),W)));return new c1({...this.#W,node:C1.cloneWithConstraint(this.#W.node,Y.toOperationNode())})}modifyFront(W){return new c1({...this.#W,node:C1.cloneWithFrontModifier(this.#W.node,W.toOperationNode())})}modifyEnd(W){return new c1({...this.#W,node:C1.cloneWithEndModifier(this.#W.node,W.toOperationNode())})}as(W){return new c1({...this.#W,node:C1.cloneWith(this.#W.node,{selectQuery:O1(W)})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class n8{#W;constructor(W){this.#W=k(W)}on(W){return new n8({...this.#W,node:s0.cloneWith(this.#W.node,{table:Z1(W)})})}ifExists(){return new n8({...this.#W,node:s0.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new n8({...this.#W,node:s0.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class OW{#W;constructor(W){this.#W=k(W)}ifExists(){return new OW({...this.#W,node:UW.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new OW({...this.#W,node:UW.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}class r8{#W;constructor(W){this.#W=k(W)}temporary(){return new r8({...this.#W,node:T8.cloneWith(this.#W.node,{temporary:!0})})}ifExists(){return new r8({...this.#W,node:T8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new r8({...this.#W,node:T8.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var w0=k({is(W){return W.kind==="CreateViewNode"},create(W){return k({kind:"CreateViewNode",name:g1.create(W)})},cloneWith(W,$){return k({...W,...$})}});class u6{#W=new qW;transformQuery(W){return this.#W.transformNode(W.node,W.queryId)}transformResult(W){return Promise.resolve(W.result)}}class p0{#W;constructor(W){this.#W=k(W)}temporary(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{temporary:!0})})}materialized(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{materialized:!0})})}ifNotExists(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{ifNotExists:!0})})}orReplace(){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{orReplace:!0})})}columns(W){return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{columns:W.map(L6)})})}as(W){let $=W.withPlugin(new u6).toOperationNode();return new p0({...this.#W,node:w0.cloneWith(this.#W.node,{as:$})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var o8=k({is(W){return W.kind==="DropViewNode"},create(W){return k({kind:"DropViewNode",name:g1.create(W)})},cloneWith(W,$){return k({...W,...$})}});class e8{#W;constructor(W){this.#W=k(W)}materialized(){return new e8({...this.#W,node:o8.cloneWith(this.#W.node,{materialized:!0})})}ifExists(){return new e8({...this.#W,node:o8.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new e8({...this.#W,node:o8.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var S4=k({is(W){return W.kind==="CreateTypeNode"},create(W){return k({kind:"CreateTypeNode",name:W})},cloneWithEnum(W,$){return k({...W,enum:e0.create($.map(D1.createImmediate))})}});class _4{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}asEnum(W){return new _4({...this.#W,node:S4.cloneWithEnum(this.#W.node,W)})}$call(W){return W(this)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var xW=k({is(W){return W.kind==="DropTypeNode"},create(W){if(!Array.isArray(W))W=[W];return k({kind:"DropTypeNode",name:W[0],additionalNames:W.slice(1)})},cloneWith(W,$){return k({...W,...$})}});class BW{#W;constructor(W){this.#W=k(W)}ifExists(){return new BW({...this.#W,node:xW.cloneWith(this.#W.node,{ifExists:!0})})}cascade(){return new BW({...this.#W,node:xW.cloneWith(this.#W.node,{cascade:!0})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}function v4(W){if(W.includes(".")){let Z=W.split(".").map(r2);if(Z.length===2)return g1.createWithSchema(Z[0],Z[1]);else throw Error(`invalid schemable identifier ${W}`)}else return g1.create(W)}function Y7(W){if(!Array.isArray(W))W=[W];return W.map(v4)}function r2(W){return W.trim()}var WW=k({is(W){return W.kind==="RefreshMaterializedViewNode"},create(W){return k({kind:"RefreshMaterializedViewNode",name:g1.create(W)})},cloneWith(W,$){return k({...W,...$})}});class $W{#W;constructor(W){this.#W=k(W)}concurrently(){return new $W({...this.#W,node:WW.cloneWith(this.#W.node,{concurrently:!0,withNoData:!1})})}withData(){return new $W({...this.#W,node:WW.cloneWith(this.#W.node,{withNoData:!1})})}withNoData(){return new $W({...this.#W,node:WW.cloneWith(this.#W.node,{withNoData:!0,concurrently:!1})})}$call(W){return W(this)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){await this.#W.executor.executeQuery(this.compile(),W)}}var C0=k({is(W){return W.kind==="AlterTypeNode"},create(W){return k({kind:"AlterTypeNode",name:W})},cloneWith(W,$){return k({...W,...$})}});var bW=k({is(W){return W.kind==="AddValueNode"},create(W){return k({kind:"AddValueNode",value:W})},cloneWith(W,$){return k({...W,...$})}});class R8{#W;constructor(W){this.#W=k(W)}toOperationNode(){return this.#W.executor.transformQuery(this.#W.node,this.#W.queryId)}compile(){return this.#W.executor.compileQuery(this.toOperationNode(),this.#W.queryId)}async execute(W){return await this.#W.executor.executeQuery(this.compile(),W)}}var l6;class E4 extends R8{#W;constructor(W){super(W);this.#W=W}ifNotExists(){return new l6({...this.#W,node:C0.cloneWith(this.#W.node,{addValue:bW.cloneWith(this.#W.node.addValue,{ifNotExists:!0})})})}before(W){return this.#$(W,!0)}after(W){return this.#$(W,!1)}#$(W,$){return new l6({...this.#W,node:C0.cloneWith(this.#W.node,{addValue:bW.cloneWith(this.#W.node.addValue,{isBefore:$,neighborValue:D1.createImmediate(W)})})})}}l6=E4;var H7=k({is(W){return W.kind==="RenameValueNode"},create(W,$){return k({kind:"RenameValueNode",oldValue:W,newValue:$})}});class p6{#W;constructor(W){this.#W=k(W)}addValue(W){return new E4({...this.#W,node:C0.cloneWith(this.#W.node,{addValue:bW.create(D1.createImmediate(W))})})}renameTo(W){return new R8({...this.#W,node:C0.cloneWith(this.#W.node,{renameTo:l.create(W)})})}renameValue(W,$){return new R8({...this.#W,node:C0.cloneWith(this.#W.node,{renameValue:H7.create(D1.createImmediate(W),D1.createImmediate($))})})}setSchema(W){return new R8({...this.#W,node:C0.cloneWith(this.#W.node,{setSchema:l.create(W)})})}}class ZW{#W;constructor(W){this.#W=W}createTable(W){return new c1({queryId:W1(),executor:this.#W,node:C1.create(Z1(W))})}dropTable(W){return new r8({queryId:W1(),executor:this.#W,node:T8.create(Z1(W))})}createIndex(W){return new J0({queryId:W1(),executor:this.#W,node:H0.create(W)})}dropIndex(W){return new n8({queryId:W1(),executor:this.#W,node:s0.create(W)})}createSchema(W){return new w4({queryId:W1(),executor:this.#W,node:W4.create(W)})}dropSchema(W){return new OW({queryId:W1(),executor:this.#W,node:UW.create(W)})}alterTable(W){return new c6({queryId:W1(),executor:this.#W,node:$1.create(Z1(W))})}createView(W){return new p0({queryId:W1(),executor:this.#W,node:w0.create(W)})}refreshMaterializedView(W){return new $W({queryId:W1(),executor:this.#W,node:WW.create(W)})}dropView(W){return new e8({queryId:W1(),executor:this.#W,node:o8.create(W)})}createType(W){return new _4({queryId:W1(),executor:this.#W,node:S4.create(v4(W))})}alterType(W){return new p6({executor:this.#W,node:C0.create(v4(W)),queryId:W1()})}dropType(W){return new BW({queryId:W1(),executor:this.#W,node:xW.create(Y7(W))})}withPlugin(W){return new ZW(this.#W.withPlugin(W))}withoutPlugins(){return new ZW(this.#W.withoutPlugins())}withSchema(W){return new ZW(this.#W.withPluginAtFront(new V0(W)))}}class i6{ref(W){return new H6(W)}table(W){return new I6(W)}}class t6{#W;constructor(W){this.#W=W}async provideConnection(W,$){let Z=await this.#W.acquireConnection($);try{return await W(Z)}finally{await this.#W.releaseConnection(Z,$)}}}class H8 extends _W{#W;#$;#Z;constructor(W,$,Z,J=[]){super(J);this.#W=W,this.#$=$,this.#Z=Z}get adapter(){return this.#$}compileQuery(W,$){return this.#W.compileQuery(W,$)}provideConnection(W,$){return this.#Z.provideConnection(W,$)}withPlugins(W){return new H8(this.#W,this.#$,this.#Z,[...this.plugins,...W])}withPlugin(W){return new H8(this.#W,this.#$,this.#Z,[...this.plugins,W])}withPluginAtFront(W){return new H8(this.#W,this.#$,this.#Z,[W,...this.plugins])}withConnectionProvider(W){return new H8(this.#W,this.#$,W,[...this.plugins])}withoutPlugins(){return new H8(this.#W,this.#$,this.#Z,[])}}function h4(){if(typeof performance<"u"&&R1(performance.now))return performance.now();else return Date.now()}class a6{#W;#$;async obtainLock(){while(this.#W)await this.#W;this.#W=new Promise((W)=>{this.#$=W})}releaseLock(){let W=this.#$;this.#W=void 0,this.#$=void 0,W?.()}}class d6{#W;#$;#Z;#X;#Y;#k=new WeakSet;#J;constructor(W,$,Z){if(this.#W=W,this.#X=!1,this.#$=Z,$.supportsMultipleConnections===!1)this.#J=new a6}async init(W){if(this.#Y)throw Error("driver has already been destroyed");this.#Z??=this.#W.init(W).then(()=>{this.#X=!0}).catch(($)=>{throw this.#Z=void 0,$}),await c8(this.#Z,W?.signal,"init")}async acquireConnection(W){if(this.#Y)throw Error("driver has already been destroyed");if(!this.#X)await this.init(W);if(this.#J){let J=this.#J.obtainLock();await c8(J,W?.signal,"acquireConnection:mutex",()=>J.then(()=>this.#J?.releaseLock()))}let $=this.#W.acquireConnection(W),Z=await c8($,W?.signal,"acquireConnection:acquire",()=>$?.then((J)=>this.releaseConnection(J).catch(T0("driver.releaseConnection"))).catch(T0("driver.acquireConnection")));if(!this.#k.has(Z)){if(this.#H())this.#G(Z);this.#k.add(Z)}return Z}async releaseConnection(W,$){await this.#W.releaseConnection(W,$),this.#J?.releaseLock()}async beginTransaction(W,$){return await this.#W.beginTransaction(W,$)}async commitTransaction(W){return await this.#W.commitTransaction(W)}async rollbackTransaction(W){return await this.#W.rollbackTransaction(W)}async savepoint(W,$,Z){if(this.#W.savepoint)return await this.#W.savepoint(W,$,Z);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint(W,$,Z){if(this.#W.rollbackToSavepoint)return await this.#W.rollbackToSavepoint(W,$,Z);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint(W,$,Z){if(this.#W.releaseSavepoint)return await this.#W.releaseSavepoint(W,$,Z);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(W){if(!this.#Z)return;await c8(this.#Z,W?.signal,"destroy:initPromise"),this.#Y??=this.#W.destroy(W).catch(($)=>{throw this.#Y=void 0,$}),await c8(this.#Y,W?.signal,"destroy")}#H(){return this.#$.isLevelEnabled("query")||this.#$.isLevelEnabled("error")}#G(W){let{executeQuery:$,streamQuery:Z}=W,J=this;W.executeQuery=async(X,Y)=>{let M,G=h4();try{return await $.call(W,X,Y)}catch(V){throw M=V,await J.#K(V,X,G),V}finally{if(!M)await J.#z(X,G)}},W.streamQuery=async function*(X,Y,M){let G,V=h4();try{for await(let R of Z.call(W,X,Y,M))yield R}catch(R){throw G=R,await J.#K(R,X,V),R}finally{if(!G)await J.#z(X,V,!0)}}}async#K(W,$,Z){await this.#$.error(()=>({level:"error",error:W,query:$,queryDurationMillis:this.#M(Z)}))}async#z(W,$,Z=!1){await this.#$.query(()=>({level:"query",isStream:Z,query:W,queryDurationMillis:this.#M($)}))}#M(W){return h4()-W}}var o2=()=>{};class IW{#W;#$;constructor(W){this.#W=W}async provideConnection(W){while(this.#$)await this.#$.catch(o2);return this.#$=this.#Z(W).finally(()=>{this.#$=void 0}),this.#$}async#Z(W){return await W(this.#W)}}var e2=["read only","read write"],WZ=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function s6(W){if(W.accessMode&&!e2.includes(W.accessMode))throw Error(`invalid transaction access mode ${W.accessMode}`);if(W.isolationLevel&&!WZ.includes(W.isolationLevel))throw Error(`invalid transaction isolation level ${W.isolationLevel}`)}var $Z=["query","error"],$w=k($Z);class n6{#W;#$;constructor(W){if(R1(W))this.#$=W,this.#W=k({query:!0,error:!0});else this.#$=ZZ,this.#W=k({query:W.includes("query"),error:W.includes("error")})}isLevelEnabled(W){return this.#W[W]}async query(W){if(this.#W.query)await this.#$(W())}async error(W){if(this.#W.error)await this.#$(W())}}function ZZ(W){if(W.level==="query"){let $=`kysely:query:${W.isStream?"stream:":""}`;console.log(`${$} ${W.query.sql}`),console.log(`${$} duration: ${W.queryDurationMillis.toFixed(1)}ms`)}else if(W.level==="error")if(W.error instanceof Error)console.error(`kysely:error: ${W.error.stack??W.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:W.error,query:W.query.sql,queryDurationMillis:W.queryDurationMillis})}`)}function k7(W){return Q1(W)&&R1(W.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class Q0 extends f0{#W;constructor(W){let $,Z;if(JZ(W))$={executor:W.executor},Z={...W};else{let J=W.dialect,X=J.createDriver(),Y=J.createQueryCompiler(),M=J.createAdapter(),G=new n6(W.log??[]),V=new d6(X,M,G),R=new t6(V),P=new H8(Y,M,R,W.plugins??[]);$={executor:P},Z={config:W,executor:P,dialect:J,driver:V}}super($);this.#W=k(Z)}get schema(){return new ZW(this.#W.executor)}get dynamic(){return new i6}get introspection(){return this.#W.dialect.createIntrospector(this.withoutPlugins())}case(W){return new hW({node:I1.create(n1(W)?void 0:O1(W))})}get fn(){return F4()}transaction(){return new T4({...this.#W})}startTransaction(){return new f4({...this.#W})}connection(){return new G7({...this.#W})}withPlugin(W){return new Q0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new Q0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new Q0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}$extendTables(){return new Q0({...this.#W})}$omitTables(){return new Q0({...this.#W})}$pickTables(){return new Q0({...this.#W})}withTables(){return this.$extendTables()}async destroy(){await this.#W.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#W.executor}async executeQuery(W,$){let Z=k7(W)?W.compile():W;return await this.#W.executor.executeQuery(Z,$)}async[Symbol.asyncDispose](){await this.destroy()}}class q0 extends Q0{#W;constructor(W){super(W);this.#W=W}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}startTransaction(){throw Error("calling the controlled transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(W){return new q0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new q0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new q0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}withTables(){return new q0({...this.#W})}$extendTables(){return new q0({...this.#W})}$omitTables(){return new q0({...this.#W})}$pickTables(){return new q0({...this.#W})}}function JZ(W){return Q1(W)&&Q1(W.config)&&Q1(W.driver)&&Q1(W.executor)&&Q1(W.dialect)}class G7{#W;constructor(W){this.#W=k(W)}async execute(W,$){return this.#W.executor.provideConnection(async(Z)=>{let J=this.#W.executor.withConnectionProvider(new IW(Z)),X=new Q0({...this.#W,executor:J});return await W(X)},k({signal:$?.signal}))}}class T4{#W;constructor(W){this.#W=k(W)}setAccessMode(W){return new T4({...this.#W,accessMode:W})}setIsolationLevel(W){return new T4({...this.#W,isolationLevel:W})}async execute(W){let{isolationLevel:$,accessMode:Z,...J}=this.#W,X={isolationLevel:$,accessMode:Z};return s6(X),this.#W.executor.provideConnection(async(Y)=>{let M={isCommitted:!1,isRolledBack:!1},G=new i0(this.#W.executor.withConnectionProvider(new IW(Y)),M),V=new q0({...J,executor:G}),R=!1;try{await this.#W.driver.beginTransaction(Y,X),R=!0;let P=await W(V);return await this.#W.driver.commitTransaction(Y),M.isCommitted=!0,P}catch(P){if(R)await this.#W.driver.rollbackTransaction(Y),M.isRolledBack=!0;throw P}})}}class f4{#W;constructor(W){this.#W=k(W)}setAccessMode(W){return new f4({...this.#W,accessMode:W})}setIsolationLevel(W){return new f4({...this.#W,isolationLevel:W})}async execute(){let{isolationLevel:W,accessMode:$,...Z}=this.#W,J={isolationLevel:W,accessMode:$};s6(J);let X=await m8(this.#W.executor);return await this.#W.driver.beginTransaction(X.connection,J),new X0({...Z,connection:X,executor:this.#W.executor.withConnectionProvider(new IW(X.connection))})}}class X0 extends q0{#W;#$;#Z;constructor(W){let $={isCommitted:!1,isRolledBack:!1};W={...W,executor:new i0(W.executor,$)};let{connection:Z,...J}=W;super(J);this.#W=k(W),this.#Z=$;let X=W1();this.#$=(Y)=>W.executor.compileQuery(Y,X)}get isCommitted(){return this.#Z.isCommitted}get isRolledBack(){return this.#Z.isRolledBack}commit(){return D8(this.#Z),new JW(async()=>{await this.#W.driver.commitTransaction(this.#W.connection.connection),this.#Z.isCommitted=!0,this.#W.connection.release()})}rollback(){return D8(this.#Z),new JW(async()=>{await this.#W.driver.rollbackTransaction(this.#W.connection.connection),this.#Z.isRolledBack=!0,this.#W.connection.release()})}savepoint(W){return D8(this.#Z),new JW(async()=>{return await this.#W.driver.savepoint?.(this.#W.connection.connection,W,this.#$),new X0({...this.#W})})}rollbackToSavepoint(W){return D8(this.#Z),new JW(async()=>{return await this.#W.driver.rollbackToSavepoint?.(this.#W.connection.connection,W,this.#$),new X0({...this.#W})})}releaseSavepoint(W){return D8(this.#Z),new JW(async()=>{return await this.#W.driver.releaseSavepoint?.(this.#W.connection.connection,W,this.#$),new X0({...this.#W})})}withPlugin(W){return new X0({...this.#W,executor:this.#W.executor.withPlugin(W)})}withoutPlugins(){return new X0({...this.#W,executor:this.#W.executor.withoutPlugins()})}withSchema(W){return new X0({...this.#W,executor:this.#W.executor.withPluginAtFront(new V0(W))})}withTables(){return new X0({...this.#W})}$extendTables(){return new X0({...this.#W})}$omitTables(){return new X0({...this.#W})}$pickTables(){return new X0({...this.#W})}}class JW{#W;constructor(W){this.#W=W}async execute(){return await this.#W()}}function D8(W){if(W.isCommitted)throw Error("Transaction is already committed");if(W.isRolledBack)throw Error("Transaction is already rolled back")}class i0{#W;#$;constructor(W,$){this.#W=W instanceof i0?W.#W:W,this.#$=$}get adapter(){return this.#W.adapter}get plugins(){return this.#W.plugins}transformQuery(W,$){return this.#W.transformQuery(W,$)}compileQuery(W,$){return this.#W.compileQuery(W,$)}provideConnection(W,$){return this.#W.provideConnection(W,$)}executeQuery(W,$){return D8(this.#$),this.#W.executeQuery(W,$)}stream(W,$,Z){return D8(this.#$),this.#W.stream(W,$,Z)}withConnectionProvider(W){return new i0(this.#W.withConnectionProvider(W),this.#$)}withPlugin(W){return new i0(this.#W.withPlugin(W),this.#$)}withPlugins(W){return new i0(this.#W.withPlugins(W),this.#$)}withPluginAtFront(W){return new i0(this.#W.withPluginAtFront(W),this.#$)}withoutPlugins(){return new i0(this.#W.withoutPlugins(),this.#$)}}class yW{#W;constructor(W){this.#W=k(W)}get expressionType(){return}get isRawBuilder(){return!0}as(W){return new M7(this,W)}$castTo(){return new yW({...this.#W})}$notNull(){return new yW(this.#W)}withPlugin(W){return new yW({...this.#W,plugins:this.#W.plugins!==void 0?k([...this.#W.plugins,W]):k([W])})}toOperationNode(){return this.#Z(this.#$())}compile(W){return this.#X(this.#$(W))}async execute(W,$){let Z=this.#$(W);return Z.executeQuery(this.#X(Z),$)}#$(W){let $=W!==void 0?W.getExecutor():J8;return this.#W.plugins!==void 0?$.withPlugins(this.#W.plugins):$}#Z(W){return W.transformQuery(this.#W.rawNode,this.#W.queryId)}#X(W){return W.compileQuery(this.#Z(W),this.#W.queryId)}}function t0(W){return new yW(W)}class M7{#W;#$;constructor(W,$){this.#W=W,this.#$=$}get expression(){return this.#W}get alias(){return this.#$}get rawBuilder(){return this.#W}toOperationNode(){return q1.create(this.#W.toOperationNode(),G1(this.#$)?this.#$.toOperationNode():l.create(this.#$))}}var k8=Object.assign((W,...$)=>{return t0({queryId:W1(),rawNode:X1.create(W,$?.map(L7)??[])})},{ref(W){return t0({queryId:W1(),rawNode:X1.createWithChild(p1(W))})},val(W){return t0({queryId:W1(),rawNode:X1.createWithChild(M1(W))})},table(W){return t0({queryId:W1(),rawNode:X1.createWithChild(Z1(W))})},id(...W){let $=Array(W.length+1).fill(".");return $[0]="",$[$.length-1]="",t0({queryId:W1(),rawNode:X1.create($,W.map(l.create))})},lit(W){return t0({queryId:W1(),rawNode:X1.createWithChild(D1.createImmediate(W))})},raw(W){return t0({queryId:W1(),rawNode:X1.createWithSql(W)})},join(W,$=k8`, `){let Z=Array(Math.max(2*W.length-1,0)),J=$.toOperationNode();for(let X=0;X<W.length;++X)if(Z[2*X]=L7(W[X]),X!==W.length-1)Z[2*X+1]=J;return t0({queryId:W1(),rawNode:X1.createWithChildren(Z)})}});function L7(W){if(G1(W))return W.toOperationNode();return M1(W)}class r6{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#W=k({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),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.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),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=(W)=>{this.nodeStack.push(W),this.#W[W.kind](W),this.nodeStack.pop()}}var XZ=/'/g,YZ=/['"]/g;class o6 extends r6{#W="";#$=[];get numParameters(){return this.#$.length}compileQuery(W,$){return this.#W="",this.#$=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(W),k({query:W,queryId:$,sql:this.getSql(),parameters:[...this.#$]})}getSql(){return this.#W}visitSelectQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!S1.is(this.parentNode)&&!C1.is(this.parentNode)&&!w0.is(this.parentNode)&&!z4.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("select"),W.distinctOn)this.append(" "),this.compileDistinctOn(W.distinctOn);if(W.frontModifiers?.length)this.append(" "),this.compileList(W.frontModifiers," ");if(W.top)this.append(" "),this.visitNode(W.top);if(W.selections)this.append(" "),this.compileList(W.selections);if(W.from)this.append(" "),this.visitNode(W.from);if(W.joins)this.append(" "),this.compileList(W.joins," ");if(W.where)this.append(" "),this.visitNode(W.where);if(W.groupBy)this.append(" "),this.visitNode(W.groupBy);if(W.having)this.append(" "),this.visitNode(W.having);if(W.setOperations)this.append(" "),this.compileList(W.setOperations," ");if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if(W.offset)this.append(" "),this.visitNode(W.offset);if(W.fetch)this.append(" "),this.visitNode(W.fetch);if(W.endModifiers?.length)this.append(" "),this.compileList(this.sortSelectModifiers(W.endModifiers)," ");if($)this.append(")")}visitFrom(W){this.append("from "),this.compileList(W.froms)}visitSelection(W){this.visitNode(W.selection)}visitColumn(W){this.visitNode(W.column)}compileDistinctOn(W){this.append("distinct on ("),this.compileList(W),this.append(")")}compileList(W,$=", "){let Z=W.length-1;for(let J=0;J<=Z;J++)if(this.visitNode(W[J]),J<Z)this.append($)}visitWhere(W){this.append("where "),this.visitNode(W.where)}visitHaving(W){this.append("having "),this.visitNode(W.having)}visitInsertQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!X1.is(this.parentNode)&&!i1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append(W.replace?"replace":"insert"),W.orAction)this.append(" "),this.visitNode(W.orAction);if(W.top)this.append(" "),this.visitNode(W.top);if(W.into)this.append(" into "),this.visitNode(W.into);if(W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.output)this.append(" "),this.visitNode(W.output);if(W.values)this.append(" "),this.visitNode(W.values);if(W.defaultValues)this.append(" "),this.append("default values");if(W.onConflict)this.append(" "),this.visitNode(W.onConflict);if(W.onDuplicateKey)this.append(" "),this.visitNode(W.onDuplicateKey);if(W.returning)this.append(" "),this.visitNode(W.returning);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitValues(W){this.append("values "),this.compileList(W.values)}visitDeleteQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!X1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("delete "),W.top)this.visitNode(W.top),this.append(" ");if(this.visitNode(W.from),W.output)this.append(" "),this.visitNode(W.output);if(W.using)this.append(" "),this.visitNode(W.using);if(W.joins)this.append(" "),this.compileList(W.joins," ");if(W.where)this.append(" "),this.visitNode(W.where);if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if(W.returning)this.append(" "),this.visitNode(W.returning);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitReturning(W){this.append("returning "),this.compileList(W.selections)}visitAlias(W){this.visitNode(W.node),this.append(" as "),this.visitNode(W.alias)}visitReference(W){if(W.table)this.visitNode(W.table),this.append(".");this.visitNode(W.column)}visitSelectAll(W){this.append("*")}visitIdentifier(W){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(W),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(W){if(!a(W.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(W.name))}visitAnd(W){this.visitNode(W.left),this.append(" and "),this.visitNode(W.right)}visitOr(W){this.visitNode(W.left),this.append(" or "),this.visitNode(W.right)}visitValue(W){if(W.immediate)this.appendImmediateValue(W.value);else this.appendValue(W.value)}visitValueList(W){this.append("("),this.compileList(W.values),this.append(")")}visitTuple(W){this.append("("),this.compileList(W.values),this.append(")")}visitPrimitiveValueList(W){this.append("(");let{values:$}=W;for(let Z=0;Z<$.length;++Z)if(this.appendValue($[Z]),Z!==$.length-1)this.append(", ");this.append(")")}visitParens(W){this.append("("),this.visitNode(W.node),this.append(")")}visitJoin(W){if(this.append(kZ[W.joinType]),this.append(" "),this.visitNode(W.table),W.on)this.append(" "),this.visitNode(W.on)}visitOn(W){this.append("on "),this.visitNode(W.on)}visitRaw(W){let{sqlFragments:$,parameters:Z}=W;for(let J=0;J<$.length;++J)if(this.append($[J]),Z.length>J)this.visitNode(Z[J])}visitOperator(W){this.append(W.operator)}visitTable(W){this.visitNode(W.table)}visitSchemableIdentifier(W){if(W.schema)this.visitNode(W.schema),this.append(".");this.visitNode(W.identifier)}visitCreateTable(W){if(this.append("create "),W.frontModifiers?.length)this.compileList(W.frontModifiers," "),this.append(" ");if(W.temporary)this.append("temporary ");if(this.append("table "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.table),!W.selectQuery)this.append(" ("),this.compileList([...W.columns,...W.constraints??[],...W.indexes??[]]),this.append(")");if(W.onCommit)this.append(" on commit "),this.append(W.onCommit);if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ");if(W.selectQuery)this.append(" as "),this.visitNode(W.selectQuery)}visitColumnDefinition(W){if(W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.column),this.append(" "),this.visitNode(W.dataType),W.unsigned)this.append(" unsigned");if(W.frontModifiers&&W.frontModifiers.length>0)this.append(" "),this.compileList(W.frontModifiers," ");if(W.generated)this.append(" "),this.visitNode(W.generated);if(W.identity)this.append(" identity");if(W.defaultTo)this.append(" "),this.visitNode(W.defaultTo);if(W.notNull)this.append(" not null");if(W.unique)this.append(" unique");if(W.nullsNotDistinct)this.append(" nulls not distinct");if(W.primaryKey)this.append(" primary key");if(W.autoIncrement)this.append(" "),this.append(this.getAutoIncrement());if(W.references)this.append(" "),this.visitNode(W.references);if(W.check)this.append(" "),this.visitNode(W.check);if(W.endModifiers&&W.endModifiers.length>0)this.append(" "),this.compileList(W.endModifiers," ")}getAutoIncrement(){return"auto_increment"}visitReferences(W){if(this.append("references "),this.visitNode(W.table),this.append(" ("),this.compileList(W.columns),this.append(")"),W.onDelete)this.append(" on delete "),this.append(W.onDelete);if(W.onUpdate)this.append(" on update "),this.append(W.onUpdate)}visitDropTable(W){if(this.append("drop "),W.temporary)this.append("temporary ");if(this.append("table "),W.ifExists)this.append("if exists ");if(this.visitNode(W.table),W.cascade)this.append(" cascade")}visitDataType(W){this.append(W.dataType)}visitOrderBy(W){this.append("order by "),this.compileList(W.items)}visitOrderByItem(W){if(this.visitNode(W.orderBy),W.collation)this.append(" "),this.visitNode(W.collation);if(W.direction)this.append(" "),this.visitNode(W.direction);if(W.nulls)this.append(" nulls "),this.append(W.nulls)}visitGroupBy(W){this.append("group by "),this.compileList(W.items)}visitGroupByItem(W){this.visitNode(W.groupBy)}visitUpdateQuery(W){let $=this.parentNode!==void 0&&!e1.is(this.parentNode)&&!X1.is(this.parentNode)&&!i1.is(this.parentNode);if(this.parentNode===void 0&&W.explain)this.visitNode(W.explain),this.append(" ");if($)this.append("(");if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("update "),W.top)this.visitNode(W.top),this.append(" ");if(W.table)this.visitNode(W.table),this.append(" ");if(this.append("set "),W.updates)this.compileList(W.updates);if(W.output)this.append(" "),this.visitNode(W.output);if(W.from)this.append(" "),this.visitNode(W.from);if(W.joins){if(!W.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(W.joins," ")}if(W.where)this.append(" "),this.visitNode(W.where);if(W.returning)this.append(" "),this.visitNode(W.returning);if(W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(W.limit)this.append(" "),this.visitNode(W.limit);if($)this.append(")");if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitColumnUpdate(W){this.visitNode(W.column),this.append(" = "),this.visitNode(W.value)}visitLimit(W){this.append("limit "),this.visitNode(W.limit)}visitOffset(W){this.append("offset "),this.visitNode(W.offset)}visitOnConflict(W){if(this.append("on conflict"),W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");else if(W.constraint)this.append(" on constraint "),this.visitNode(W.constraint);else if(W.indexExpression)this.append(" ("),this.visitNode(W.indexExpression),this.append(")");if(W.indexWhere)this.append(" "),this.visitNode(W.indexWhere);if(W.doNothing===!0)this.append(" do nothing");else if(W.updates){if(this.append(" do update set "),this.compileList(W.updates),W.updateWhere)this.append(" "),this.visitNode(W.updateWhere)}}visitOnDuplicateKey(W){this.append("on duplicate key update "),this.compileList(W.updates)}visitCreateIndex(W){if(this.append("create "),W.unique)this.append("unique ");if(this.append("index "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.name),W.table)this.append(" on "),this.visitNode(W.table);if(W.using)this.append(" using "),this.visitNode(W.using);if(W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.nullsNotDistinct)this.append(" nulls not distinct");if(W.where)this.append(" "),this.visitNode(W.where)}visitDropIndex(W){if(this.append("drop index "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.table)this.append(" on "),this.visitNode(W.table);if(W.cascade)this.append(" cascade")}visitCreateSchema(W){if(this.append("create schema "),W.ifNotExists)this.append("if not exists ");this.visitNode(W.schema)}visitDropSchema(W){if(this.append("drop schema "),W.ifExists)this.append("if exists ");if(this.visitNode(W.schema),W.cascade)this.append(" cascade")}visitPrimaryKeyConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");this.append("primary key ("),this.compileList(W.columns),this.append(")"),this.buildDeferrable(W)}buildDeferrable(W){if(W.deferrable!==void 0)if(W.deferrable)this.append(" deferrable");else this.append(" not deferrable");if(W.initiallyDeferred!==void 0)if(W.initiallyDeferred)this.append(" initially deferred");else this.append(" initially immediate")}visitUniqueConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");if(this.append("unique"),W.nullsNotDistinct)this.append(" nulls not distinct");this.append(" ("),this.compileList(W.columns),this.append(")"),this.buildDeferrable(W)}visitCheckConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");this.append("check ("),this.visitNode(W.expression),this.append(")")}visitForeignKeyConstraint(W){if(W.name)this.append("constraint "),this.visitNode(W.name),this.append(" ");if(this.append("foreign key ("),this.compileList(W.columns),this.append(") "),this.visitNode(W.references),W.onDelete)this.append(" on delete "),this.append(W.onDelete);if(W.onUpdate)this.append(" on update "),this.append(W.onUpdate);this.buildDeferrable(W)}visitList(W){this.compileList(W.items)}visitWith(W){if(this.append("with "),W.recursive)this.append("recursive ");this.compileList(W.expressions)}visitCommonTableExpression(W){if(this.visitNode(W.name),this.append(" as "),K8(W.materialized)){if(!W.materialized)this.append("not ");this.append("materialized ")}this.visitNode(W.expression)}visitCommonTableExpressionName(W){if(this.visitNode(W.table),W.columns)this.append("("),this.compileList(W.columns),this.append(")")}visitAlterTable(W){if(this.append("alter table "),this.visitNode(W.table),this.append(" "),W.renameTo)this.append("rename to "),this.visitNode(W.renameTo);if(W.setSchema)this.append("set schema "),this.visitNode(W.setSchema);if(W.addConstraint)this.visitNode(W.addConstraint);if(W.dropConstraint)this.visitNode(W.dropConstraint);if(W.renameConstraint)this.visitNode(W.renameConstraint);if(W.columnAlterations)this.compileColumnAlterations(W.columnAlterations);if(W.addIndex)this.visitNode(W.addIndex);if(W.dropIndex)this.visitNode(W.dropIndex)}visitAddColumn(W){this.append("add column "),this.visitNode(W.column)}visitRenameColumn(W){this.append("rename column "),this.visitNode(W.column),this.append(" to "),this.visitNode(W.renameTo)}visitDropColumn(W){if(this.append("drop column "),W.ifExists)this.append("if exists ");this.visitNode(W.column)}visitAlterColumn(W){if(this.append("alter column "),this.visitNode(W.column),this.append(" "),W.dataType){if(this.announcesNewColumnDataType())this.append("type ");if(this.visitNode(W.dataType),W.dataTypeExpression)this.append("using "),this.visitNode(W.dataTypeExpression)}if(W.setDefault)this.append("set default "),this.visitNode(W.setDefault);if(W.dropDefault)this.append("drop default");if(W.setNotNull)this.append("set not null");if(W.dropNotNull)this.append("drop not null")}visitModifyColumn(W){this.append("modify column "),this.visitNode(W.column)}visitAddConstraint(W){this.append("add "),this.visitNode(W.constraint)}visitDropConstraint(W){if(this.append("drop constraint "),W.ifExists)this.append("if exists ");if(this.visitNode(W.constraintName),W.modifier==="cascade")this.append(" cascade");else if(W.modifier==="restrict")this.append(" restrict")}visitRenameConstraint(W){this.append("rename constraint "),this.visitNode(W.oldName),this.append(" to "),this.visitNode(W.newName)}visitSetOperation(W){if(this.append(W.operator),this.append(" "),W.all)this.append("all ");this.visitNode(W.expression)}visitCreateView(W){if(this.append("create "),W.orReplace)this.append("or replace ");if(W.materialized)this.append("materialized ");if(W.temporary)this.append("temporary ");if(this.append("view "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.name),this.append(" "),W.columns)this.append("("),this.compileList(W.columns),this.append(") ");if(W.as)this.append("as "),this.visitNode(W.as)}visitRefreshMaterializedView(W){if(this.append("refresh materialized view "),W.concurrently)this.append("concurrently ");if(this.visitNode(W.name),W.withNoData)this.append(" with no data");else this.append(" with data")}visitDropView(W){if(this.append("drop "),W.materialized)this.append("materialized ");if(this.append("view "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.cascade)this.append(" cascade")}visitGenerated(W){if(this.append("generated "),W.always)this.append("always ");if(W.byDefault)this.append("by default ");if(this.append("as "),W.identity)this.append("identity");if(W.expression)this.append("("),this.visitNode(W.expression),this.append(")");if(W.stored)this.append(" stored")}visitDefaultValue(W){this.append("default "),this.visitNode(W.defaultValue)}visitSelectModifier(W){if(W.rawModifier)this.visitNode(W.rawModifier);else this.append(HZ[W.modifier]);if(W.of)this.append(" of "),this.compileList(W.of,", ")}visitCreateType(W){if(this.append("create type "),this.visitNode(W.name),W.enum)this.append(" as enum "),this.visitNode(W.enum)}visitDropType(W){if(this.append("drop type "),W.ifExists)this.append("if exists ");if(this.visitNode(W.name),W.additionalNames?.length)this.append(", "),this.compileList(W.additionalNames);if(W.cascade)this.append(" cascade")}visitAlterType(W){if(this.append("alter type "),this.visitNode(W.name),this.append(" "),W.addValue)this.visitNode(W.addValue);else if(W.renameTo)this.append("rename to "),this.visitNode(W.renameTo);else if(W.renameValue)this.visitNode(W.renameValue);else if(W.setSchema)this.append("set schema "),this.visitNode(W.setSchema)}visitAddValue(W){if(this.append("add value "),W.ifNotExists)this.append("if not exists ");if(this.visitNode(W.value),W.neighborValue)this.append(W.isBefore?" before ":" after "),this.visitNode(W.neighborValue)}visitRenameValue(W){this.append("rename value "),this.visitNode(W.oldValue),this.append(" to "),this.visitNode(W.newValue)}visitExplain(W){if(this.append("explain"),W.options||W.format){if(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),W.options){if(this.visitNode(W.options),W.format)this.append(this.getExplainOptionsDelimiter())}if(W.format)this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(W.format);this.append(this.getRightExplainOptionsWrapper())}}visitDefaultInsertValue(W){this.append("default")}visitAggregateFunction(W){if(this.append(W.func),this.append("("),W.distinct)this.append("distinct ");if(this.compileList(W.aggregated),W.orderBy)this.append(" "),this.visitNode(W.orderBy);if(this.append(")"),W.withinGroup)this.append(" within group ("),this.visitNode(W.withinGroup),this.append(")");if(W.filter)this.append(" filter("),this.visitNode(W.filter),this.append(")");if(W.over)this.append(" "),this.visitNode(W.over)}visitOver(W){if(this.append("over("),W.partitionBy){if(this.visitNode(W.partitionBy),W.orderBy)this.append(" ")}if(W.orderBy)this.visitNode(W.orderBy);this.append(")")}visitPartitionBy(W){this.append("partition by "),this.compileList(W.items)}visitPartitionByItem(W){this.visitNode(W.partitionBy)}visitBinaryOperation(W){this.visitNode(W.leftOperand),this.append(" "),this.visitNode(W.operator),this.append(" "),this.visitNode(W.rightOperand)}visitUnaryOperation(W){if(this.visitNode(W.operator),!this.isMinusOperator(W.operator))this.append(" ");this.visitNode(W.operand)}isMinusOperator(W){return r1.is(W)&&W.operator==="-"}visitUsing(W){this.append("using "),this.compileList(W.tables)}visitFunction(W){this.append(W.func),this.append("("),this.compileList(W.arguments),this.append(")")}visitCase(W){if(this.append("case"),W.value)this.append(" "),this.visitNode(W.value);if(W.when)this.append(" "),this.compileList(W.when," ");if(W.else)this.append(" else "),this.visitNode(W.else);if(this.append(" end"),W.isStatement)this.append(" case")}visitWhen(W){if(this.append("when "),this.visitNode(W.condition),W.result)this.append(" then "),this.visitNode(W.result)}visitJSONReference(W){this.visitNode(W.reference),this.visitNode(W.traversal)}visitJSONPath(W){if(W.inOperator)this.visitNode(W.inOperator);this.append("'$");for(let $ of W.pathLegs)this.visitNode($);this.append("'")}visitJSONPathLeg(W){let $=W.type==="ArrayLocation",Z=String(W.value);if($)this.append("["),this.append(this.sanitizeStringLiteral(Z)),this.append("]");else this.append('."'),this.append(this.sanitizeJSONPathMemberValue(Z)),this.append('"')}visitJSONOperatorChain(W){for(let $=0,Z=W.values.length;$<Z;$++){if($===Z-1)this.visitNode(W.operator);else this.append("->");this.visitNode(W.values[$])}}visitMergeQuery(W){if(W.with)this.visitNode(W.with),this.append(" ");if(this.append("merge "),W.top)this.visitNode(W.top),this.append(" ");if(this.append("into "),this.visitNode(W.into),W.using)this.append(" "),this.visitNode(W.using);if(W.whens)this.append(" "),this.compileList(W.whens," ");if(W.returning)this.append(" "),this.visitNode(W.returning);if(W.output)this.append(" "),this.visitNode(W.output);if(W.endModifiers?.length)this.append(" "),this.compileList(W.endModifiers," ")}visitMatched(W){if(W.not)this.append("not ");if(this.append("matched"),W.bySource)this.append(" by source")}visitAddIndex(W){if(!this.parentNode||!C1.is(this.parentNode))this.append("add ");if(W.unique)this.append("unique ");if(this.append("index "),this.visitNode(W.name),W.columns)this.append(" ("),this.compileList(W.columns),this.append(")");if(W.using)this.append(" using "),this.visitNode(W.using)}visitCast(W){this.append("cast("),this.visitNode(W.expression),this.append(" as "),this.visitNode(W.dataType),this.append(")")}visitFetch(W){this.append("fetch next "),this.visitNode(W.rowCount),this.append(` rows ${W.modifier}`)}visitOutput(W){this.append("output "),this.compileList(W.selections)}visitTop(W){if(this.append(`top(${W.expression})`),W.modifiers)this.append(` ${W.modifiers}`)}visitOrAction(W){this.append(W.action)}visitCollate(W){this.append("collate "),this.visitNode(W.collation)}append(W){this.#W+=W}appendValue(W){this.addParameter(W),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(W){let $=this.getLeftIdentifierWrapper(),Z=this.getRightIdentifierWrapper(),J="";for(let X of W)if(J+=X,X===$)J+=$;else if(X===Z)J+=Z;return J}sanitizeStringLiteral(W){return W.replace(XZ,"''")}sanitizeJSONPathMemberValue(W){return W.replace(YZ,($)=>$==="'"?"''":"\\\"")}addParameter(W){this.#$.push(W)}appendImmediateValue(W){if(a(W))this.appendStringLiteral(W);else if(d0(W)||K8(W)||h8(W))this.append(W.toString());else if(E8(W))this.append("null");else if(t9(W))this.appendImmediateValue(W.toISOString());else throw Error(`invalid immediate value ${W}`)}appendStringLiteral(W){this.append("'"),this.append(this.sanitizeStringLiteral(W)),this.append("'")}sortSelectModifiers(W){return k(W.toSorted(($,Z)=>$.modifier&&Z.modifier?K7[$.modifier]-K7[Z.modifier]:1))}compileColumnAlterations(W){this.compileList(W)}announcesNewColumnDataType(){return!0}}var HZ=k({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),K7=k({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),kZ=k({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"});var gW=k({raw(W,$=[]){return k({sql:W,query:X1.createWithSql(W),parameters:k($),queryId:W1()})}});class e6{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}class W9{transformQuery(W){return W.node}async transformResult(W){return W.result}}var Z9="kysely_migration",A4="kysely_migration_lock",GZ=!1,$9="migration_lock",GQ=k({__noMigrations__:!0});class J9{#W;constructor(W){this.#W=k(W)}async getMigrations(){let $=await this.#L(this.#X)?await this.#W.db.withPlugin(this.#J).selectFrom(this.#X).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#P()).map(({name:J,...X})=>{let Y=$.find((M)=>M.name===J);return{name:J,migration:X,executedAt:Y?new Date(Y.timestamp):void 0}})}async migrateToLatest(W){return this.#$(()=>({direction:"Up",step:1/0}),W)}async migrateTo(W,$){return this.#$(({migrations:Z,executedMigrations:J,pendingMigrations:X})=>{if(Q1(W)&&W.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!Z.find((G)=>G.name===W))throw Error(`migration "${W}" doesn't exist`);let Y=J.indexOf(W),M=X.findIndex((G)=>G.name===W);if(Y!==-1)return{direction:"Down",step:J.length-Y-1};if(M!==-1)return{direction:"Up",step:M+1};throw Error(`migration "${W}" isn't executed or pending`)},$)}async migrateUp(W){return this.#$(()=>({direction:"Up",step:1}),W)}async migrateDown(W){return this.#$(()=>({direction:"Down",step:1}),W)}async#$(W,$){try{return await this.#H(),await this.#G(),await this.#K(),await this.#z(),await this.#F(W,$)}catch(Z){if(Z instanceof j4)return Z.resultSet;return{error:Z}}}get#Z(){return this.#W.migrationTableSchema}get#X(){return this.#W.migrationTableName??Z9}get#Y(){return this.#W.migrationLockTableName??A4}get#k(){return this.#W.allowUnorderedMigrations??GZ}get#J(){if(this.#Z)return new V0(this.#Z);return new W9}async#H(){if(!this.#Z)return;if(await this.#M())return;try{await this.#U(this.#W.db.schema.createSchema(this.#Z))}catch($){if(!await this.#M())throw $}}async#G(){if(await this.#L(this.#X))return;try{await this.#U(this.#W.db.schema.withPlugin(this.#J).createTable(this.#X).addColumn("name","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("timestamp","varchar(255)",($)=>$.notNull()))}catch($){if(!await this.#L(this.#X))throw $}}async#K(){if(await this.#L(this.#Y))return;try{await this.#U(this.#W.db.schema.withPlugin(this.#J).createTable(this.#Y).addColumn("id","varchar(255)",($)=>$.notNull().primaryKey()).addColumn("is_locked","integer",($)=>$.notNull().defaultTo(0)))}catch($){if(!await this.#L(this.#Y))throw $}}async#z(){if(await this.#V())return;try{await this.#W.db.withPlugin(this.#J).insertInto(this.#Y).values({id:$9,is_locked:0}).execute()}catch($){if(!await this.#V())throw $}}async#M(){return(await this.#W.db.introspection.getSchemas()).some(($)=>$.name===this.#Z)}async#L(W){let $=this.#Z;return(await this.#W.db.introspection.getTables({withInternalKyselyTables:!0})).some((J)=>J.name===W&&(!$||J.schema===$))}async#V(){return!!await this.#W.db.withPlugin(this.#J).selectFrom(this.#Y).where("id","=",$9).select("id").executeTakeFirst()}async#F(W,$){let Z=this.#W.db.getExecutor().adapter,J=k({lockTable:this.#W.migrationLockTableName??A4,lockRowId:$9,lockTableSchema:this.#W.migrationTableSchema}),X=async(M)=>{try{await Z.acquireMigrationLock(M,J);let G=await this.#R(M);if(G.migrations.length===0)return{results:[]};let{direction:V,step:R}=W(G);if(R<=0)return{results:[]};if(V==="Down")return await this.#_(M,G,R);else if(V==="Up")return await this.#v(M,G,R);return{results:[]}}finally{await Z.releaseMigrationLock(M,J)}},Y=$?.disableTransactions??this.#W.disableTransactions;if(this.#W.db.isTransaction){if(!Z.supportsTransactionalDdl)throw Error("Transactional DDL is not supported in this dialect. Passing a transaction to this migrator would result in failure or unexpected behavior.");if(Y)throw Error("`disableTransactions` is true but the migrator was given a transaction. Passing a transaction to this migrator would result in failure or unexpected behavior.");return X(this.#W.db)}if(Z.supportsTransactionalDdl&&!Y)return this.#W.db.transaction().execute(X);return this.#W.db.connection().execute(X)}async#R(W){let $=await this.#P(),Z=await this.#w(W);if(this.#Q($,Z),!this.#k)this.#S($,Z);let J=this.#D($,Z);return k({migrations:$,executedMigrations:Z,lastMigration:a9(Z),pendingMigrations:J})}#D(W,$){return W.filter((Z)=>{return!$.includes(Z.name)})}async#P(){let W=await this.#W.provider.getMigrations();return Object.keys(W).sort().map(($)=>({...W[$],name:$}))}async#w(W){let $=await W.withPlugin(this.#J).selectFrom(this.#X).select(["name","timestamp"]).$narrowType().execute(),Z=this.#W.nameComparator||((J,X)=>J.localeCompare(X));return $.sort((J,X)=>{if(J.timestamp===X.timestamp)return Z(J.name,X.name);return new Date(J.timestamp).getTime()-new Date(X.timestamp).getTime()}).map((J)=>J.name)}#Q(W,$){for(let Z of $)if(!W.some((J)=>J.name===Z))throw Error(`corrupted migrations: previously executed migration ${Z} is missing`)}#S(W,$){for(let Z=0;Z<$.length;++Z)if(W[Z].name!==$[Z])throw Error(`corrupted migrations: expected previously executed migration ${$[Z]} to be at index ${Z} but ${W[Z].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#_(W,$,Z){let J=$.executedMigrations.toReversed().slice(0,Z).map((Y)=>{return $.migrations.find((M)=>M.name===Y)}),X=J.map((Y)=>{return{migrationName:Y.name,direction:"Down",status:"NotExecuted"}});for(let Y=0;Y<X.length;++Y){let M=J[Y];try{if(M.down)await M.down(W),await W.withPlugin(this.#J).deleteFrom(this.#X).where("name","=",M.name).execute(),X[Y]={migrationName:M.name,direction:"Down",status:"Success"}}catch(G){throw X[Y]={migrationName:M.name,direction:"Down",status:"Error"},new j4({error:G,results:X})}}return{results:X}}async#v(W,$,Z){let X=$.pendingMigrations.slice(0,Z).map((Y)=>{return{migrationName:Y.name,direction:"Up",status:"NotExecuted"}});for(let Y=0;Y<X.length;Y++){let M=$.pendingMigrations[Y];try{await M.up(W),await W.withPlugin(this.#J).insertInto(this.#X).values({name:M.name,timestamp:new Date().toISOString()}).execute(),X[Y]={migrationName:M.name,direction:"Up",status:"Success"}}catch(G){throw X[Y]={migrationName:M.name,direction:"Up",status:"Error"},new j4({error:G,results:X})}}return{results:X}}async#U(W){if(this.#W.db.getExecutor().adapter.supportsCreateIfNotExists)W=W.ifNotExists();await W.execute()}}class j4 extends Error{#W;constructor(W){super();this.#W=W}get resultSet(){return this.#W}}class mW{#W;constructor(W){this.#W=W}async getSchemas(){return(await this.#W.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map(($)=>({name:$.nspname}))}async getTables(W={withInternalKyselyTables:!1}){let $=this.#W.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",k8`col_description(a.attrelid, a.attnum)`.as("column_description"),k8`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p","f"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(k8`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!W.withInternalKyselyTables)$=$.where("c.relname","!=",Z9).where("c.relname","!=",A4);let Z=await $.execute();return this.#$(Z)}#$(W){let $=[],Z=new Map;for(let J of W){let X=Z.get(J.schema);if(!X)X=new Map,Z.set(J.schema,X);let Y=X.get(J.table);if(!Y)Y=k({columns:[],isForeign:J.table_type==="f",isView:J.table_type==="v",name:J.table,schema:J.schema}),X.set(J.table,Y),$.push(Y);Y.columns.push(k({comment:J.column_description??void 0,dataType:J.type,dataTypeSchema:J.type_schema,hasDefaultValue:J.has_default,isAutoIncrementing:J.auto_incrementing!==null,isNullable:!J.not_null,name:J.column}))}return $}}var MZ=/"/g;class cW extends o6{sanitizeIdentifier(W){return W.replace(MZ,'""')}}var LZ=BigInt("3853314791062309107");class uW extends e6{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(W,$){await k8`select pg_advisory_xact_lock(${k8.lit(LZ)})`.execute(W)}async releaseMigrationLock(W,$){}}var{create:KZ,defineProperty:YW,getOwnPropertyDescriptor:zZ,getOwnPropertyNames:UZ,getPrototypeOf:VZ}=Object,PZ=Object.prototype.hasOwnProperty,FZ=(W,$,Z)=>($ in W)?YW(W,$,{enumerable:!0,configurable:!0,writable:!0,value:Z}):W[$]=Z,U=(W,$)=>YW(W,"name",{value:$,configurable:!0}),d1=(W,$)=>()=>(W&&($=W(W=0)),$),o=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports),S0=(W,$)=>{for(var Z in $)YW(W,Z,{get:$[Z],enumerable:!0})},D7=(W,$,Z,J)=>{if($&&typeof $=="object"||typeof $=="function")for(let X of UZ($))!PZ.call(W,X)&&X!==Z&&YW(W,X,{get:()=>$[X],enumerable:!(J=zZ($,X))||J.enumerable});return W},Q8=(W,$,Z)=>(Z=W!=null?KZ(VZ(W)):{},D7($||!W||!W.__esModule?YW(Z,"default",{value:W,enumerable:!0}):Z,W)),B1=(W)=>D7(YW({},"__esModule",{value:!0}),W),t=(W,$,Z)=>FZ(W,typeof $!="symbol"?$+"":$,Z),RZ=o((W)=>{u(),W.byteLength=V,W.toByteArray=P,W.fromByteArray=S;var $=[],Z=[],J=typeof Uint8Array<"u"?Uint8Array:Array,X="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Y=0,M=X.length;Y<M;++Y)$[Y]=X[Y],Z[X.charCodeAt(Y)]=Y;var Y,M;Z[45]=62,Z[95]=63;function G(F){var L=F.length;if(L%4>0)throw Error("Invalid string. Length must be a multiple of 4");var Q=F.indexOf("=");Q===-1&&(Q=L);var _=Q===L?0:4-Q%4;return[Q,_]}U(G,"getLens");function V(F){var L=G(F),Q=L[0],_=L[1];return(Q+_)*3/4-_}U(V,"byteLength");function R(F,L,Q){return(L+Q)*3/4-Q}U(R,"_byteLength");function P(F){var L,Q=G(F),_=Q[0],v=Q[1],T=new J(R(F,_,v)),x=0,q=v>0?_-4:_,E;for(E=0;E<q;E+=4)L=Z[F.charCodeAt(E)]<<18|Z[F.charCodeAt(E+1)]<<12|Z[F.charCodeAt(E+2)]<<6|Z[F.charCodeAt(E+3)],T[x++]=L>>16&255,T[x++]=L>>8&255,T[x++]=L&255;return v===2&&(L=Z[F.charCodeAt(E)]<<2|Z[F.charCodeAt(E+1)]>>4,T[x++]=L&255),v===1&&(L=Z[F.charCodeAt(E)]<<10|Z[F.charCodeAt(E+1)]<<4|Z[F.charCodeAt(E+2)]>>2,T[x++]=L>>8&255,T[x++]=L&255),T}U(P,"toByteArray");function w(F){return $[F>>18&63]+$[F>>12&63]+$[F>>6&63]+$[F&63]}U(w,"tripletToBase64");function D(F,L,Q){for(var _,v=[],T=L;T<Q;T+=3)_=(F[T]<<16&16711680)+(F[T+1]<<8&65280)+(F[T+2]&255),v.push(w(_));return v.join("")}U(D,"encodeChunk");function S(F){for(var L,Q=F.length,_=Q%3,v=[],T=16383,x=0,q=Q-_;x<q;x+=T)v.push(D(F,x,x+T>q?q:x+T));return _===1?(L=F[Q-1],v.push($[L>>2]+$[L<<4&63]+"==")):_===2&&(L=(F[Q-2]<<8)+F[Q-1],v.push($[L>>10]+$[L>>4&63]+$[L<<2&63]+"=")),v.join("")}U(S,"fromByteArray")}),DZ=o((W)=>{u(),W.read=function($,Z,J,X,Y){var M,G,V=Y*8-X-1,R=(1<<V)-1,P=R>>1,w=-7,D=J?Y-1:0,S=J?-1:1,F=$[Z+D];for(D+=S,M=F&(1<<-w)-1,F>>=-w,w+=V;w>0;M=M*256+$[Z+D],D+=S,w-=8);for(G=M&(1<<-w)-1,M>>=-w,w+=X;w>0;G=G*256+$[Z+D],D+=S,w-=8);if(M===0)M=1-P;else{if(M===R)return G?NaN:(F?-1:1)*(1/0);G=G+Math.pow(2,X),M=M-P}return(F?-1:1)*G*Math.pow(2,M-X)},W.write=function($,Z,J,X,Y,M){var G,V,R,P=M*8-Y-1,w=(1<<P)-1,D=w>>1,S=Y===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=X?0:M-1,L=X?1:-1,Q=Z<0||Z===0&&1/Z<0?1:0;for(Z=Math.abs(Z),isNaN(Z)||Z===1/0?(V=isNaN(Z)?1:0,G=w):(G=Math.floor(Math.log(Z)/Math.LN2),Z*(R=Math.pow(2,-G))<1&&(G--,R*=2),G+D>=1?Z+=S/R:Z+=S*Math.pow(2,1-D),Z*R>=2&&(G++,R/=2),G+D>=w?(V=0,G=w):G+D>=1?(V=(Z*R-1)*Math.pow(2,Y),G=G+D):(V=Z*Math.pow(2,D-1)*Math.pow(2,Y),G=0));Y>=8;$[J+F]=V&255,F+=L,V/=256,Y-=8);for(G=G<<Y|V,P+=Y;P>0;$[J+F]=G&255,F+=L,G/=256,P-=8);$[J+F-L]|=Q*128}}),wZ=o((W)=>{u();var $=RZ(),Z=DZ(),J=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;W.Buffer=G,W.SlowBuffer=v,W.INSPECT_MAX_BYTES=50;var X=2147483647;W.kMaxLength=X,G.TYPED_ARRAY_SUPPORT=Y(),!G.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Y(){try{let H=new Uint8Array(1),K={foo:U(function(){return 42},"foo")};return Object.setPrototypeOf(K,Uint8Array.prototype),Object.setPrototypeOf(H,K),H.foo()===42}catch{return!1}}U(Y,"typedArraySupport"),Object.defineProperty(G.prototype,"parent",{enumerable:!0,get:U(function(){if(G.isBuffer(this))return this.buffer},"get")}),Object.defineProperty(G.prototype,"offset",{enumerable:!0,get:U(function(){if(G.isBuffer(this))return this.byteOffset},"get")});function M(H){if(H>X)throw RangeError('The value "'+H+'" is invalid for option "size"');let K=new Uint8Array(H);return Object.setPrototypeOf(K,G.prototype),K}U(M,"createBuffer");function G(H,K,z){if(typeof H=="number"){if(typeof K=="string")throw TypeError('The "string" argument must be of type string. Received type number');return w(H)}return V(H,K,z)}U(G,"Buffer"),G.poolSize=8192;function V(H,K,z){if(typeof H=="string")return D(H,K);if(ArrayBuffer.isView(H))return F(H);if(H==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof H);if(Y0(H,ArrayBuffer)||H&&Y0(H.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Y0(H,SharedArrayBuffer)||H&&Y0(H.buffer,SharedArrayBuffer)))return L(H,K,z);if(typeof H=="number")throw TypeError('The "value" argument must not be of type number. Received type number');let h=H.valueOf&&H.valueOf();if(h!=null&&h!==H)return G.from(h,K,z);let j=Q(H);if(j)return j;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof H[Symbol.toPrimitive]=="function")return G.from(H[Symbol.toPrimitive]("string"),K,z);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof H)}U(V,"from"),G.from=function(H,K,z){return V(H,K,z)},Object.setPrototypeOf(G.prototype,Uint8Array.prototype),Object.setPrototypeOf(G,Uint8Array);function R(H){if(typeof H!="number")throw TypeError('"size" argument must be of type number');if(H<0)throw RangeError('The value "'+H+'" is invalid for option "size"')}U(R,"assertSize");function P(H,K,z){return R(H),H<=0?M(H):K!==void 0?typeof z=="string"?M(H).fill(K,z):M(H).fill(K):M(H)}U(P,"alloc"),G.alloc=function(H,K,z){return P(H,K,z)};function w(H){return R(H),M(H<0?0:_(H)|0)}U(w,"allocUnsafe"),G.allocUnsafe=function(H){return w(H)},G.allocUnsafeSlow=function(H){return w(H)};function D(H,K){if((typeof K!="string"||K==="")&&(K="utf8"),!G.isEncoding(K))throw TypeError("Unknown encoding: "+K);let z=T(H,K)|0,h=M(z),j=h.write(H,K);return j!==z&&(h=h.slice(0,j)),h}U(D,"fromString");function S(H){let K=H.length<0?0:_(H.length)|0,z=M(K);for(let h=0;h<K;h+=1)z[h]=H[h]&255;return z}U(S,"fromArrayLike");function F(H){if(Y0(H,Uint8Array)){let K=new Uint8Array(H);return L(K.buffer,K.byteOffset,K.byteLength)}return S(H)}U(F,"fromArrayView");function L(H,K,z){if(K<0||H.byteLength<K)throw RangeError('"offset" is outside of buffer bounds');if(H.byteLength<K+(z||0))throw RangeError('"length" is outside of buffer bounds');let h;return K===void 0&&z===void 0?h=new Uint8Array(H):z===void 0?h=new Uint8Array(H,K):h=new Uint8Array(H,K,z),Object.setPrototypeOf(h,G.prototype),h}U(L,"fromArrayBuffer");function Q(H){if(G.isBuffer(H)){let K=_(H.length)|0,z=M(K);return z.length===0||H.copy(z,0,0,K),z}if(H.length!==void 0)return typeof H.length!="number"||rW(H.length)?M(0):S(H);if(H.type==="Buffer"&&Array.isArray(H.data))return S(H.data)}U(Q,"fromObject");function _(H){if(H>=X)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+X.toString(16)+" bytes");return H|0}U(_,"checked");function v(H){return+H!=H&&(H=0),G.alloc(+H)}U(v,"SlowBuffer"),G.isBuffer=U(function(H){return H!=null&&H._isBuffer===!0&&H!==G.prototype},"isBuffer"),G.compare=U(function(H,K){if(Y0(H,Uint8Array)&&(H=G.from(H,H.offset,H.byteLength)),Y0(K,Uint8Array)&&(K=G.from(K,K.offset,K.byteLength)),!G.isBuffer(H)||!G.isBuffer(K))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(H===K)return 0;let z=H.length,h=K.length;for(let j=0,O=Math.min(z,h);j<O;++j)if(H[j]!==K[j]){z=H[j],h=K[j];break}return z<h?-1:h<z?1:0},"compare"),G.isEncoding=U(function(H){switch(String(H).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},"isEncoding"),G.concat=U(function(H,K){if(!Array.isArray(H))throw TypeError('"list" argument must be an Array of Buffers');if(H.length===0)return G.alloc(0);let z;if(K===void 0)for(K=0,z=0;z<H.length;++z)K+=H[z].length;let h=G.allocUnsafe(K),j=0;for(z=0;z<H.length;++z){let O=H[z];if(Y0(O,Uint8Array))j+O.length>h.length?(G.isBuffer(O)||(O=G.from(O)),O.copy(h,j)):Uint8Array.prototype.set.call(h,O,j);else if(G.isBuffer(O))O.copy(h,j);else throw TypeError('"list" argument must be an Array of Buffers');j+=O.length}return h},"concat");function T(H,K){if(G.isBuffer(H))return H.length;if(ArrayBuffer.isView(H)||Y0(H,ArrayBuffer))return H.byteLength;if(typeof H!="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof H);let z=H.length,h=arguments.length>2&&arguments[2]===!0;if(!h&&z===0)return 0;let j=!1;for(;;)switch(K){case"ascii":case"latin1":case"binary":return z;case"utf8":case"utf-8":return nW(H).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z*2;case"hex":return z>>>1;case"base64":return r4(H).length;default:if(j)return h?-1:nW(H).length;K=(""+K).toLowerCase(),j=!0}}U(T,"byteLength"),G.byteLength=T;function x(H,K,z){let h=!1;if((K===void 0||K<0)&&(K=0),K>this.length||((z===void 0||z>this.length)&&(z=this.length),z<=0)||(z>>>=0,K>>>=0,z<=K))return"";for(H||(H="utf8");;)switch(H){case"hex":return s(this,K,z);case"utf8":case"utf-8":return b(this,K,z);case"ascii":return d(this,K,z);case"latin1":case"binary":return J1(this,K,z);case"base64":return m(this,K,z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return s1(this,K,z);default:if(h)throw TypeError("Unknown encoding: "+H);H=(H+"").toLowerCase(),h=!0}}U(x,"slowToString"),G.prototype._isBuffer=!0;function q(H,K,z){let h=H[K];H[K]=H[z],H[z]=h}U(q,"swap"),G.prototype.swap16=U(function(){let H=this.length;if(H%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let K=0;K<H;K+=2)q(this,K,K+1);return this},"swap16"),G.prototype.swap32=U(function(){let H=this.length;if(H%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let K=0;K<H;K+=4)q(this,K,K+3),q(this,K+1,K+2);return this},"swap32"),G.prototype.swap64=U(function(){let H=this.length;if(H%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(let K=0;K<H;K+=8)q(this,K,K+7),q(this,K+1,K+6),q(this,K+2,K+5),q(this,K+3,K+4);return this},"swap64"),G.prototype.toString=U(function(){let H=this.length;return H===0?"":arguments.length===0?b(this,0,H):x.apply(this,arguments)},"toString"),G.prototype.toLocaleString=G.prototype.toString,G.prototype.equals=U(function(H){if(!G.isBuffer(H))throw TypeError("Argument must be a Buffer");return this===H?!0:G.compare(this,H)===0},"equals"),G.prototype.inspect=U(function(){let H="",K=W.INSPECT_MAX_BYTES;return H=this.toString("hex",0,K).replace(/(.{2})/g,"$1 ").trim(),this.length>K&&(H+=" ... "),"<Buffer "+H+">"},"inspect"),J&&(G.prototype[J]=G.prototype.inspect),G.prototype.compare=U(function(H,K,z,h,j){if(Y0(H,Uint8Array)&&(H=G.from(H,H.offset,H.byteLength)),!G.isBuffer(H))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof H);if(K===void 0&&(K=0),z===void 0&&(z=H?H.length:0),h===void 0&&(h=0),j===void 0&&(j=this.length),K<0||z>H.length||h<0||j>this.length)throw RangeError("out of range index");if(h>=j&&K>=z)return 0;if(h>=j)return-1;if(K>=z)return 1;if(K>>>=0,z>>>=0,h>>>=0,j>>>=0,this===H)return 0;let O=j-h,I=z-K,P1=Math.min(O,I),A1=this.slice(h,j),w1=H.slice(K,z);for(let F1=0;F1<P1;++F1)if(A1[F1]!==w1[F1]){O=A1[F1],I=w1[F1];break}return O<I?-1:I<O?1:0},"compare");function E(H,K,z,h,j){if(H.length===0)return-1;if(typeof z=="string"?(h=z,z=0):z>2147483647?z=2147483647:z<-2147483648&&(z=-2147483648),z=+z,rW(z)&&(z=j?0:H.length-1),z<0&&(z=H.length+z),z>=H.length){if(j)return-1;z=H.length-1}else if(z<0)if(j)z=0;else return-1;if(typeof K=="string"&&(K=G.from(K,h)),G.isBuffer(K))return K.length===0?-1:N(H,K,z,h,j);if(typeof K=="number")return K=K&255,typeof Uint8Array.prototype.indexOf=="function"?j?Uint8Array.prototype.indexOf.call(H,K,z):Uint8Array.prototype.lastIndexOf.call(H,K,z):N(H,[K],z,h,j);throw TypeError("val must be string, number or Buffer")}U(E,"bidirectionalIndexOf");function N(H,K,z,h,j){let O=1,I=H.length,P1=K.length;if(h!==void 0&&(h=String(h).toLowerCase(),h==="ucs2"||h==="ucs-2"||h==="utf16le"||h==="utf-16le")){if(H.length<2||K.length<2)return-1;O=2,I/=2,P1/=2,z/=2}function A1(F1,h1){return O===1?F1[h1]:F1.readUInt16BE(h1*O)}U(A1,"read");let w1;if(j){let F1=-1;for(w1=z;w1<I;w1++)if(A1(H,w1)===A1(K,F1===-1?0:w1-F1)){if(F1===-1&&(F1=w1),w1-F1+1===P1)return F1*O}else F1!==-1&&(w1-=w1-F1),F1=-1}else for(z+P1>I&&(z=I-P1),w1=z;w1>=0;w1--){let F1=!0;for(let h1=0;h1<P1;h1++)if(A1(H,w1+h1)!==A1(K,h1)){F1=!1;break}if(F1)return w1}return-1}U(N,"arrayIndexOf"),G.prototype.includes=U(function(H,K,z){return this.indexOf(H,K,z)!==-1},"includes"),G.prototype.indexOf=U(function(H,K,z){return E(this,H,K,z,!0)},"indexOf"),G.prototype.lastIndexOf=U(function(H,K,z){return E(this,H,K,z,!1)},"lastIndexOf");function A(H,K,z,h){z=Number(z)||0;let j=H.length-z;h?(h=Number(h),h>j&&(h=j)):h=j;let O=K.length;h>O/2&&(h=O/2);let I;for(I=0;I<h;++I){let P1=parseInt(K.substr(I*2,2),16);if(rW(P1))return I;H[z+I]=P1}return I}U(A,"hexWrite");function f(H,K,z,h){return MW(nW(K,H.length-z),H,z,h)}U(f,"utf8Write");function B(H,K,z,h){return MW(E9(K),H,z,h)}U(B,"asciiWrite");function C(H,K,z,h){return MW(r4(K),H,z,h)}U(C,"base64Write");function c(H,K,z,h){return MW(h9(K,H.length-z),H,z,h)}U(c,"ucs2Write"),G.prototype.write=U(function(H,K,z,h){if(K===void 0)h="utf8",z=this.length,K=0;else if(z===void 0&&typeof K=="string")h=K,z=this.length,K=0;else if(isFinite(K))K=K>>>0,isFinite(z)?(z=z>>>0,h===void 0&&(h="utf8")):(h=z,z=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let j=this.length-K;if((z===void 0||z>j)&&(z=j),H.length>0&&(z<0||K<0)||K>this.length)throw RangeError("Attempt to write outside buffer bounds");h||(h="utf8");let O=!1;for(;;)switch(h){case"hex":return A(this,H,K,z);case"utf8":case"utf-8":return f(this,H,K,z);case"ascii":case"latin1":case"binary":return B(this,H,K,z);case"base64":return C(this,H,K,z);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return c(this,H,K,z);default:if(O)throw TypeError("Unknown encoding: "+h);h=(""+h).toLowerCase(),O=!0}},"write"),G.prototype.toJSON=U(function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},"toJSON");function m(H,K,z){return K===0&&z===H.length?$.fromByteArray(H):$.fromByteArray(H.slice(K,z))}U(m,"base64Slice");function b(H,K,z){z=Math.min(H.length,z);let h=[],j=K;for(;j<z;){let O=H[j],I=null,P1=O>239?4:O>223?3:O>191?2:1;if(j+P1<=z){let A1,w1,F1,h1;switch(P1){case 1:O<128&&(I=O);break;case 2:A1=H[j+1],(A1&192)===128&&(h1=(O&31)<<6|A1&63,h1>127&&(I=h1));break;case 3:A1=H[j+1],w1=H[j+2],(A1&192)===128&&(w1&192)===128&&(h1=(O&15)<<12|(A1&63)<<6|w1&63,h1>2047&&(h1<55296||h1>57343)&&(I=h1));break;case 4:A1=H[j+1],w1=H[j+2],F1=H[j+3],(A1&192)===128&&(w1&192)===128&&(F1&192)===128&&(h1=(O&15)<<18|(A1&63)<<12|(w1&63)<<6|F1&63,h1>65535&&h1<1114112&&(I=h1))}}I===null?(I=65533,P1=1):I>65535&&(I-=65536,h.push(I>>>10&1023|55296),I=56320|I&1023),h.push(I),j+=P1}return p(h)}U(b,"utf8Slice");var g=4096;function p(H){let K=H.length;if(K<=g)return String.fromCharCode.apply(String,H);let z="",h=0;for(;h<K;)z+=String.fromCharCode.apply(String,H.slice(h,h+=g));return z}U(p,"decodeCodePointsArray");function d(H,K,z){let h="";z=Math.min(H.length,z);for(let j=K;j<z;++j)h+=String.fromCharCode(H[j]&127);return h}U(d,"asciiSlice");function J1(H,K,z){let h="";z=Math.min(H.length,z);for(let j=K;j<z;++j)h+=String.fromCharCode(H[j]);return h}U(J1,"latin1Slice");function s(H,K,z){let h=H.length;(!K||K<0)&&(K=0),(!z||z<0||z>h)&&(z=h);let j="";for(let O=K;O<z;++O)j+=T$[H[O]];return j}U(s,"hexSlice");function s1(H,K,z){let h=H.slice(K,z),j="";for(let O=0;O<h.length-1;O+=2)j+=String.fromCharCode(h[O]+h[O+1]*256);return j}U(s1,"utf16leSlice"),G.prototype.slice=U(function(H,K){let z=this.length;H=~~H,K=K===void 0?z:~~K,H<0?(H+=z,H<0&&(H=0)):H>z&&(H=z),K<0?(K+=z,K<0&&(K=0)):K>z&&(K=z),K<H&&(K=H);let h=this.subarray(H,K);return Object.setPrototypeOf(h,G.prototype),h},"slice");function V1(H,K,z){if(H%1!==0||H<0)throw RangeError("offset is not uint");if(H+K>z)throw RangeError("Trying to access beyond buffer length")}U(V1,"checkOffset"),G.prototype.readUintLE=G.prototype.readUIntLE=U(function(H,K,z){H=H>>>0,K=K>>>0,z||V1(H,K,this.length);let h=this[H],j=1,O=0;for(;++O<K&&(j*=256);)h+=this[H+O]*j;return h},"readUIntLE"),G.prototype.readUintBE=G.prototype.readUIntBE=U(function(H,K,z){H=H>>>0,K=K>>>0,z||V1(H,K,this.length);let h=this[H+--K],j=1;for(;K>0&&(j*=256);)h+=this[H+--K]*j;return h},"readUIntBE"),G.prototype.readUint8=G.prototype.readUInt8=U(function(H,K){return H=H>>>0,K||V1(H,1,this.length),this[H]},"readUInt8"),G.prototype.readUint16LE=G.prototype.readUInt16LE=U(function(H,K){return H=H>>>0,K||V1(H,2,this.length),this[H]|this[H+1]<<8},"readUInt16LE"),G.prototype.readUint16BE=G.prototype.readUInt16BE=U(function(H,K){return H=H>>>0,K||V1(H,2,this.length),this[H]<<8|this[H+1]},"readUInt16BE"),G.prototype.readUint32LE=G.prototype.readUInt32LE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),(this[H]|this[H+1]<<8|this[H+2]<<16)+this[H+3]*16777216},"readUInt32LE"),G.prototype.readUint32BE=G.prototype.readUInt32BE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),this[H]*16777216+(this[H+1]<<16|this[H+2]<<8|this[H+3])},"readUInt32BE"),G.prototype.readBigUInt64LE=O0(U(function(H){H=H>>>0,M8(H,"offset");let K=this[H],z=this[H+7];(K===void 0||z===void 0)&&v8(H,this.length-8);let h=K+this[++H]*256+this[++H]*65536+this[++H]*16777216,j=this[++H]+this[++H]*256+this[++H]*65536+z*16777216;return BigInt(h)+(BigInt(j)<<BigInt(32))},"readBigUInt64LE")),G.prototype.readBigUInt64BE=O0(U(function(H){H=H>>>0,M8(H,"offset");let K=this[H],z=this[H+7];(K===void 0||z===void 0)&&v8(H,this.length-8);let h=K*16777216+this[++H]*65536+this[++H]*256+this[++H],j=this[++H]*16777216+this[++H]*65536+this[++H]*256+z;return(BigInt(h)<<BigInt(32))+BigInt(j)},"readBigUInt64BE")),G.prototype.readIntLE=U(function(H,K,z){H=H>>>0,K=K>>>0,z||V1(H,K,this.length);let h=this[H],j=1,O=0;for(;++O<K&&(j*=256);)h+=this[H+O]*j;return j*=128,h>=j&&(h-=Math.pow(2,8*K)),h},"readIntLE"),G.prototype.readIntBE=U(function(H,K,z){H=H>>>0,K=K>>>0,z||V1(H,K,this.length);let h=K,j=1,O=this[H+--h];for(;h>0&&(j*=256);)O+=this[H+--h]*j;return j*=128,O>=j&&(O-=Math.pow(2,8*K)),O},"readIntBE"),G.prototype.readInt8=U(function(H,K){return H=H>>>0,K||V1(H,1,this.length),this[H]&128?(255-this[H]+1)*-1:this[H]},"readInt8"),G.prototype.readInt16LE=U(function(H,K){H=H>>>0,K||V1(H,2,this.length);let z=this[H]|this[H+1]<<8;return z&32768?z|4294901760:z},"readInt16LE"),G.prototype.readInt16BE=U(function(H,K){H=H>>>0,K||V1(H,2,this.length);let z=this[H+1]|this[H]<<8;return z&32768?z|4294901760:z},"readInt16BE"),G.prototype.readInt32LE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),this[H]|this[H+1]<<8|this[H+2]<<16|this[H+3]<<24},"readInt32LE"),G.prototype.readInt32BE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),this[H]<<24|this[H+1]<<16|this[H+2]<<8|this[H+3]},"readInt32BE"),G.prototype.readBigInt64LE=O0(U(function(H){H=H>>>0,M8(H,"offset");let K=this[H],z=this[H+7];(K===void 0||z===void 0)&&v8(H,this.length-8);let h=this[H+4]+this[H+5]*256+this[H+6]*65536+(z<<24);return(BigInt(h)<<BigInt(32))+BigInt(K+this[++H]*256+this[++H]*65536+this[++H]*16777216)},"readBigInt64LE")),G.prototype.readBigInt64BE=O0(U(function(H){H=H>>>0,M8(H,"offset");let K=this[H],z=this[H+7];(K===void 0||z===void 0)&&v8(H,this.length-8);let h=(K<<24)+this[++H]*65536+this[++H]*256+this[++H];return(BigInt(h)<<BigInt(32))+BigInt(this[++H]*16777216+this[++H]*65536+this[++H]*256+z)},"readBigInt64BE")),G.prototype.readFloatLE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),Z.read(this,H,!0,23,4)},"readFloatLE"),G.prototype.readFloatBE=U(function(H,K){return H=H>>>0,K||V1(H,4,this.length),Z.read(this,H,!1,23,4)},"readFloatBE"),G.prototype.readDoubleLE=U(function(H,K){return H=H>>>0,K||V1(H,8,this.length),Z.read(this,H,!0,52,8)},"readDoubleLE"),G.prototype.readDoubleBE=U(function(H,K){return H=H>>>0,K||V1(H,8,this.length),Z.read(this,H,!1,52,8)},"readDoubleBE");function f1(H,K,z,h,j,O){if(!G.isBuffer(H))throw TypeError('"buffer" argument must be a Buffer instance');if(K>j||K<O)throw RangeError('"value" argument is out of bounds');if(z+h>H.length)throw RangeError("Index out of range")}U(f1,"checkInt"),G.prototype.writeUintLE=G.prototype.writeUIntLE=U(function(H,K,z,h){if(H=+H,K=K>>>0,z=z>>>0,!h){let I=Math.pow(2,8*z)-1;f1(this,H,K,z,I,0)}let j=1,O=0;for(this[K]=H&255;++O<z&&(j*=256);)this[K+O]=H/j&255;return K+z},"writeUIntLE"),G.prototype.writeUintBE=G.prototype.writeUIntBE=U(function(H,K,z,h){if(H=+H,K=K>>>0,z=z>>>0,!h){let I=Math.pow(2,8*z)-1;f1(this,H,K,z,I,0)}let j=z-1,O=1;for(this[K+j]=H&255;--j>=0&&(O*=256);)this[K+j]=H/O&255;return K+z},"writeUIntBE"),G.prototype.writeUint8=G.prototype.writeUInt8=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,1,255,0),this[K]=H&255,K+1},"writeUInt8"),G.prototype.writeUint16LE=G.prototype.writeUInt16LE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,2,65535,0),this[K]=H&255,this[K+1]=H>>>8,K+2},"writeUInt16LE"),G.prototype.writeUint16BE=G.prototype.writeUInt16BE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,2,65535,0),this[K]=H>>>8,this[K+1]=H&255,K+2},"writeUInt16BE"),G.prototype.writeUint32LE=G.prototype.writeUInt32LE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,4,4294967295,0),this[K+3]=H>>>24,this[K+2]=H>>>16,this[K+1]=H>>>8,this[K]=H&255,K+4},"writeUInt32LE"),G.prototype.writeUint32BE=G.prototype.writeUInt32BE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,4,4294967295,0),this[K]=H>>>24,this[K+1]=H>>>16,this[K+2]=H>>>8,this[K+3]=H&255,K+4},"writeUInt32BE");function kW(H,K,z,h,j){n4(K,h,j,H,z,7);let O=Number(K&BigInt(4294967295));H[z++]=O,O=O>>8,H[z++]=O,O=O>>8,H[z++]=O,O=O>>8,H[z++]=O;let I=Number(K>>BigInt(32)&BigInt(4294967295));return H[z++]=I,I=I>>8,H[z++]=I,I=I>>8,H[z++]=I,I=I>>8,H[z++]=I,z}U(kW,"wrtBigUInt64LE");function GW(H,K,z,h,j){n4(K,h,j,H,z,7);let O=Number(K&BigInt(4294967295));H[z+7]=O,O=O>>8,H[z+6]=O,O=O>>8,H[z+5]=O,O=O>>8,H[z+4]=O;let I=Number(K>>BigInt(32)&BigInt(4294967295));return H[z+3]=I,I=I>>8,H[z+2]=I,I=I>>8,H[z+1]=I,I=I>>8,H[z]=I,z+8}U(GW,"wrtBigUInt64BE"),G.prototype.writeBigUInt64LE=O0(U(function(H,K=0){return kW(this,H,K,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64LE")),G.prototype.writeBigUInt64BE=O0(U(function(H,K=0){return GW(this,H,K,BigInt(0),BigInt("0xffffffffffffffff"))},"writeBigUInt64BE")),G.prototype.writeIntLE=U(function(H,K,z,h){if(H=+H,K=K>>>0,!h){let P1=Math.pow(2,8*z-1);f1(this,H,K,z,P1-1,-P1)}let j=0,O=1,I=0;for(this[K]=H&255;++j<z&&(O*=256);)H<0&&I===0&&this[K+j-1]!==0&&(I=1),this[K+j]=(H/O>>0)-I&255;return K+z},"writeIntLE"),G.prototype.writeIntBE=U(function(H,K,z,h){if(H=+H,K=K>>>0,!h){let P1=Math.pow(2,8*z-1);f1(this,H,K,z,P1-1,-P1)}let j=z-1,O=1,I=0;for(this[K+j]=H&255;--j>=0&&(O*=256);)H<0&&I===0&&this[K+j+1]!==0&&(I=1),this[K+j]=(H/O>>0)-I&255;return K+z},"writeIntBE"),G.prototype.writeInt8=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,1,127,-128),H<0&&(H=255+H+1),this[K]=H&255,K+1},"writeInt8"),G.prototype.writeInt16LE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,2,32767,-32768),this[K]=H&255,this[K+1]=H>>>8,K+2},"writeInt16LE"),G.prototype.writeInt16BE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,2,32767,-32768),this[K]=H>>>8,this[K+1]=H&255,K+2},"writeInt16BE"),G.prototype.writeInt32LE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,4,2147483647,-2147483648),this[K]=H&255,this[K+1]=H>>>8,this[K+2]=H>>>16,this[K+3]=H>>>24,K+4},"writeInt32LE"),G.prototype.writeInt32BE=U(function(H,K,z){return H=+H,K=K>>>0,z||f1(this,H,K,4,2147483647,-2147483648),H<0&&(H=4294967295+H+1),this[K]=H>>>24,this[K+1]=H>>>16,this[K+2]=H>>>8,this[K+3]=H&255,K+4},"writeInt32BE"),G.prototype.writeBigInt64LE=O0(U(function(H,K=0){return kW(this,H,K,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64LE")),G.prototype.writeBigInt64BE=O0(U(function(H,K=0){return GW(this,H,K,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))},"writeBigInt64BE"));function t4(H,K,z,h,j,O){if(z+h>H.length)throw RangeError("Index out of range");if(z<0)throw RangeError("Index out of range")}U(t4,"checkIEEE754");function a4(H,K,z,h,j){return K=+K,z=z>>>0,j||t4(H,K,z,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),Z.write(H,K,z,h,23,4),z+4}U(a4,"writeFloat"),G.prototype.writeFloatLE=U(function(H,K,z){return a4(this,H,K,!0,z)},"writeFloatLE"),G.prototype.writeFloatBE=U(function(H,K,z){return a4(this,H,K,!1,z)},"writeFloatBE");function d4(H,K,z,h,j){return K=+K,z=z>>>0,j||t4(H,K,z,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),Z.write(H,K,z,h,52,8),z+8}U(d4,"writeDouble"),G.prototype.writeDoubleLE=U(function(H,K,z){return d4(this,H,K,!0,z)},"writeDoubleLE"),G.prototype.writeDoubleBE=U(function(H,K,z){return d4(this,H,K,!1,z)},"writeDoubleBE"),G.prototype.copy=U(function(H,K,z,h){if(!G.isBuffer(H))throw TypeError("argument should be a Buffer");if(z||(z=0),!h&&h!==0&&(h=this.length),K>=H.length&&(K=H.length),K||(K=0),h>0&&h<z&&(h=z),h===z||H.length===0||this.length===0)return 0;if(K<0)throw RangeError("targetStart out of bounds");if(z<0||z>=this.length)throw RangeError("Index out of range");if(h<0)throw RangeError("sourceEnd out of bounds");h>this.length&&(h=this.length),H.length-K<h-z&&(h=H.length-K+z);let j=h-z;return this===H&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(K,z,h):Uint8Array.prototype.set.call(H,this.subarray(z,h),K),j},"copy"),G.prototype.fill=U(function(H,K,z,h){if(typeof H=="string"){if(typeof K=="string"?(h=K,K=0,z=this.length):typeof z=="string"&&(h=z,z=this.length),h!==void 0&&typeof h!="string")throw TypeError("encoding must be a string");if(typeof h=="string"&&!G.isEncoding(h))throw TypeError("Unknown encoding: "+h);if(H.length===1){let O=H.charCodeAt(0);(h==="utf8"&&O<128||h==="latin1")&&(H=O)}}else typeof H=="number"?H=H&255:typeof H=="boolean"&&(H=Number(H));if(K<0||this.length<K||this.length<z)throw RangeError("Out of range index");if(z<=K)return this;K=K>>>0,z=z===void 0?this.length:z>>>0,H||(H=0);let j;if(typeof H=="number")for(j=K;j<z;++j)this[j]=H;else{let O=G.isBuffer(H)?H:G.from(H,h),I=O.length;if(I===0)throw TypeError('The value "'+H+'" is invalid for argument "value"');for(j=0;j<z-K;++j)this[j+K]=O[j%I]}return this},"fill");var _8={};function sW(H,K,z){var h;_8[H]=(h=class extends z{constructor(){super(),Object.defineProperty(this,"message",{value:K.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${H}]`,this.stack,delete this.name}get code(){return H}set code(j){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:j,writable:!0})}toString(){return`${this.name} [${H}]: ${this.message}`}},U(h,"NodeError"),h)}U(sW,"E"),sW("ERR_BUFFER_OUT_OF_BOUNDS",function(H){return H?`${H} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),sW("ERR_INVALID_ARG_TYPE",function(H,K){return`The "${H}" argument must be of type number. Received type ${typeof K}`},TypeError),sW("ERR_OUT_OF_RANGE",function(H,K,z){let h=`The value of "${H}" is out of range.`,j=z;return Number.isInteger(z)&&Math.abs(z)>4294967296?j=s4(String(z)):typeof z=="bigint"&&(j=String(z),(z>BigInt(2)**BigInt(32)||z<-(BigInt(2)**BigInt(32)))&&(j=s4(j)),j+="n"),h+=` It must be ${K}. Received ${j}`,h},RangeError);function s4(H){let K="",z=H.length,h=H[0]==="-"?1:0;for(;z>=h+4;z-=3)K=`_${H.slice(z-3,z)}${K}`;return`${H.slice(0,z)}${K}`}U(s4,"addNumericalSeparator");function _9(H,K,z){M8(K,"offset"),(H[K]===void 0||H[K+z]===void 0)&&v8(K,H.length-(z+1))}U(_9,"checkBounds");function n4(H,K,z,h,j,O){if(H>z||H<K){let I=typeof K=="bigint"?"n":"",P1;throw O>3?K===0||K===BigInt(0)?P1=`>= 0${I} and < 2${I} ** ${(O+1)*8}${I}`:P1=`>= -(2${I} ** ${(O+1)*8-1}${I}) and < 2 ** ${(O+1)*8-1}${I}`:P1=`>= ${K}${I} and <= ${z}${I}`,new _8.ERR_OUT_OF_RANGE("value",P1,H)}_9(h,j,O)}U(n4,"checkIntBI");function M8(H,K){if(typeof H!="number")throw new _8.ERR_INVALID_ARG_TYPE(K,"number",H)}U(M8,"validateNumber");function v8(H,K,z){throw Math.floor(H)!==H?(M8(H,z),new _8.ERR_OUT_OF_RANGE(z||"offset","an integer",H)):K<0?new _8.ERR_BUFFER_OUT_OF_BOUNDS:new _8.ERR_OUT_OF_RANGE(z||"offset",`>= ${z?1:0} and <= ${K}`,H)}U(v8,"boundsError");var h$=/[^+/0-9A-Za-z-_]/g;function v9(H){if(H=H.split("=")[0],H=H.trim().replace(h$,""),H.length<2)return"";for(;H.length%4!==0;)H=H+"=";return H}U(v9,"base64clean");function nW(H,K){K=K||1/0;let z,h=H.length,j=null,O=[];for(let I=0;I<h;++I){if(z=H.charCodeAt(I),z>55295&&z<57344){if(!j){if(z>56319){(K-=3)>-1&&O.push(239,191,189);continue}else if(I+1===h){(K-=3)>-1&&O.push(239,191,189);continue}j=z;continue}if(z<56320){(K-=3)>-1&&O.push(239,191,189),j=z;continue}z=(j-55296<<10|z-56320)+65536}else j&&(K-=3)>-1&&O.push(239,191,189);if(j=null,z<128){if((K-=1)<0)break;O.push(z)}else if(z<2048){if((K-=2)<0)break;O.push(z>>6|192,z&63|128)}else if(z<65536){if((K-=3)<0)break;O.push(z>>12|224,z>>6&63|128,z&63|128)}else if(z<1114112){if((K-=4)<0)break;O.push(z>>18|240,z>>12&63|128,z>>6&63|128,z&63|128)}else throw Error("Invalid code point")}return O}U(nW,"utf8ToBytes");function E9(H){let K=[];for(let z=0;z<H.length;++z)K.push(H.charCodeAt(z)&255);return K}U(E9,"asciiToBytes");function h9(H,K){let z,h,j,O=[];for(let I=0;I<H.length&&!((K-=2)<0);++I)z=H.charCodeAt(I),h=z>>8,j=z%256,O.push(j),O.push(h);return O}U(h9,"utf16leToBytes");function r4(H){return $.toByteArray(v9(H))}U(r4,"base64ToBytes");function MW(H,K,z,h){let j;for(j=0;j<h&&!(j+z>=K.length||j>=H.length);++j)K[j+z]=H[j];return j}U(MW,"blitBuffer");function Y0(H,K){return H instanceof K||H!=null&&H.constructor!=null&&H.constructor.name!=null&&H.constructor.name===K.name}U(Y0,"isInstance");function rW(H){return H!==H}U(rW,"numberIsNaN");var T$=function(){let H="0123456789abcdef",K=Array(256);for(let z=0;z<16;++z){let h=z*16;for(let j=0;j<16;++j)K[h+j]=H[z]+H[j]}return K}();function O0(H){return typeof BigInt>"u"?T9:H}U(O0,"defineBigIntMethod");function T9(){throw Error("BigInt not supported")}U(T9,"BufferBigIntNotDefined")}),x4,M9,QZ,i,r,u=d1(()=>{x4=globalThis,M9=globalThis.setImmediate??((W)=>setTimeout(W,0)),QZ=globalThis.clearImmediate??((W)=>clearTimeout(W)),i=typeof globalThis.Buffer=="function"&&typeof globalThis.Buffer.allocUnsafe=="function"?globalThis.Buffer:wZ().Buffer,r=globalThis.process??{},r.env??(r.env={});try{r.nextTick(()=>{})}catch{let W=Promise.resolve();r.nextTick=W.then.bind(W)}}),S8=o((W,$)=>{u();var Z=typeof Reflect=="object"?Reflect:null,J=Z&&typeof Z.apply=="function"?Z.apply:U(function(E,N,A){return Function.prototype.apply.call(E,N,A)},"ReflectApply"),X;Z&&typeof Z.ownKeys=="function"?X=Z.ownKeys:Object.getOwnPropertySymbols?X=U(function(E){return Object.getOwnPropertyNames(E).concat(Object.getOwnPropertySymbols(E))},"ReflectOwnKeys"):X=U(function(E){return Object.getOwnPropertyNames(E)},"ReflectOwnKeys");function Y(E){console&&console.warn&&console.warn(E)}U(Y,"ProcessEmitWarning");var M=Number.isNaN||U(function(E){return E!==E},"NumberIsNaN");function G(){G.init.call(this)}U(G,"EventEmitter"),$.exports=G,$.exports.once=T,G.EventEmitter=G,G.prototype._events=void 0,G.prototype._eventsCount=0,G.prototype._maxListeners=void 0;var V=10;function R(E){if(typeof E!="function")throw TypeError('The "listener" argument must be of type Function. Received type '+typeof E)}U(R,"checkListener"),Object.defineProperty(G,"defaultMaxListeners",{enumerable:!0,get:U(function(){return V},"get"),set:U(function(E){if(typeof E!="number"||E<0||M(E))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+E+".");V=E},"set")}),G.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},G.prototype.setMaxListeners=U(function(E){if(typeof E!="number"||E<0||M(E))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+E+".");return this._maxListeners=E,this},"setMaxListeners");function P(E){return E._maxListeners===void 0?G.defaultMaxListeners:E._maxListeners}U(P,"_getMaxListeners"),G.prototype.getMaxListeners=U(function(){return P(this)},"getMaxListeners"),G.prototype.emit=U(function(E){for(var N=[],A=1;A<arguments.length;A++)N.push(arguments[A]);var f=E==="error",B=this._events;if(B!==void 0)f=f&&B.error===void 0;else if(!f)return!1;if(f){var C;if(N.length>0&&(C=N[0]),C instanceof Error)throw C;var c=Error("Unhandled error."+(C?" ("+C.message+")":""));throw c.context=C,c}var m=B[E];if(m===void 0)return!1;if(typeof m=="function")J(m,this,N);else for(var b=m.length,g=Q(m,b),A=0;A<b;++A)J(g[A],this,N);return!0},"emit");function w(E,N,A,f){var B,C,c;if(R(A),C=E._events,C===void 0?(C=E._events=Object.create(null),E._eventsCount=0):(C.newListener!==void 0&&(E.emit("newListener",N,A.listener?A.listener:A),C=E._events),c=C[N]),c===void 0)c=C[N]=A,++E._eventsCount;else if(typeof c=="function"?c=C[N]=f?[A,c]:[c,A]:f?c.unshift(A):c.push(A),B=P(E),B>0&&c.length>B&&!c.warned){c.warned=!0;var m=Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(N)+" listeners added. Use emitter.setMaxListeners() to increase limit");m.name="MaxListenersExceededWarning",m.emitter=E,m.type=N,m.count=c.length,Y(m)}return E}U(w,"_addListener"),G.prototype.addListener=U(function(E,N){return w(this,E,N,!1)},"addListener"),G.prototype.on=G.prototype.addListener,G.prototype.prependListener=U(function(E,N){return w(this,E,N,!0)},"prependListener");function D(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}U(D,"onceWrapper");function S(E,N,A){var f={fired:!1,wrapFn:void 0,target:E,type:N,listener:A},B=D.bind(f);return B.listener=A,f.wrapFn=B,B}U(S,"_onceWrap"),G.prototype.once=U(function(E,N){return R(N),this.on(E,S(this,E,N)),this},"once"),G.prototype.prependOnceListener=U(function(E,N){return R(N),this.prependListener(E,S(this,E,N)),this},"prependOnceListener"),G.prototype.removeListener=U(function(E,N){var A,f,B,C,c;if(R(N),f=this._events,f===void 0)return this;if(A=f[E],A===void 0)return this;if(A===N||A.listener===N)--this._eventsCount===0?this._events=Object.create(null):(delete f[E],f.removeListener&&this.emit("removeListener",E,A.listener||N));else if(typeof A!="function"){for(B=-1,C=A.length-1;C>=0;C--)if(A[C]===N||A[C].listener===N){c=A[C].listener,B=C;break}if(B<0)return this;B===0?A.shift():_(A,B),A.length===1&&(f[E]=A[0]),f.removeListener!==void 0&&this.emit("removeListener",E,c||N)}return this},"removeListener"),G.prototype.off=G.prototype.removeListener,G.prototype.removeAllListeners=U(function(E){var N,A,f;if(A=this._events,A===void 0)return this;if(A.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):A[E]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete A[E]),this;if(arguments.length===0){var B=Object.keys(A),C;for(f=0;f<B.length;++f)C=B[f],C!=="removeListener"&&this.removeAllListeners(C);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(N=A[E],typeof N=="function")this.removeListener(E,N);else if(N!==void 0)for(f=N.length-1;f>=0;f--)this.removeListener(E,N[f]);return this},"removeAllListeners");function F(E,N,A){var f=E._events;if(f===void 0)return[];var B=f[N];return B===void 0?[]:typeof B=="function"?A?[B.listener||B]:[B]:A?v(B):Q(B,B.length)}U(F,"_listeners"),G.prototype.listeners=U(function(E){return F(this,E,!0)},"listeners"),G.prototype.rawListeners=U(function(E){return F(this,E,!1)},"rawListeners"),G.listenerCount=function(E,N){return typeof E.listenerCount=="function"?E.listenerCount(N):L.call(E,N)},G.prototype.listenerCount=L;function L(E){var N=this._events;if(N!==void 0){var A=N[E];if(typeof A=="function")return 1;if(A!==void 0)return A.length}return 0}U(L,"listenerCount"),G.prototype.eventNames=U(function(){return this._eventsCount>0?X(this._events):[]},"eventNames");function Q(E,N){for(var A=Array(N),f=0;f<N;++f)A[f]=E[f];return A}U(Q,"arrayClone");function _(E,N){for(;N+1<E.length;N++)E[N]=E[N+1];E.pop()}U(_,"spliceOne");function v(E){for(var N=Array(E.length),A=0;A<N.length;++A)N[A]=E[A].listener||E[A];return N}U(v,"unwrapListeners");function T(E,N){return new Promise(function(A,f){function B(c){E.removeListener(N,C),f(c)}U(B,"errorListener");function C(){typeof E.removeListener=="function"&&E.removeListener("error",B),A([].slice.call(arguments))}U(C,"resolver"),q(E,N,C,{once:!0}),N!=="error"&&x(E,B,{once:!0})})}U(T,"once");function x(E,N,A){typeof E.on=="function"&&q(E,"error",N,A)}U(x,"addErrorHandlerIfEventEmitter");function q(E,N,A,f){if(typeof E.on=="function")f.once?E.once(N,A):E.on(N,A);else if(typeof E.addEventListener=="function")E.addEventListener(N,U(function B(C){f.once&&E.removeEventListener(N,B),A(C)},"wrapListener"));else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof E)}U(q,"eventTargetAgnosticAddListener")}),w7={};S0(w7,{Socket:()=>w8,isIP:()=>Q7});function Q7(W){return 0}var z7,X9,lW,w8,tW=d1(()=>{u(),z7=Q8(S8(),1),U(Q7,"isIP"),X9=/^[^.]+\./,lW=class W extends z7.EventEmitter{constructor(){super(...arguments);t(this,"opts",{}),t(this,"connecting",!1),t(this,"pending",!0),t(this,"writable",!0),t(this,"encrypted",!1),t(this,"authorized",!1),t(this,"destroyed",!1),t(this,"ws",null),t(this,"writeBuffer"),t(this,"tlsState",0),t(this,"tlsRead"),t(this,"tlsWrite")}static get poolQueryViaFetch(){return W.opts.poolQueryViaFetch??W.defaults.poolQueryViaFetch}static set poolQueryViaFetch($){W.opts.poolQueryViaFetch=$}static get fetchEndpoint(){return W.opts.fetchEndpoint??W.defaults.fetchEndpoint}static set fetchEndpoint($){W.opts.fetchEndpoint=$}static get fetchConnectionCache(){return!0}static set fetchConnectionCache($){console.warn("The `fetchConnectionCache` option is deprecated (now always `true`)")}static get fetchFunction(){return W.opts.fetchFunction??W.defaults.fetchFunction}static set fetchFunction($){W.opts.fetchFunction=$}static get webSocketConstructor(){return W.opts.webSocketConstructor??W.defaults.webSocketConstructor}static set webSocketConstructor($){W.opts.webSocketConstructor=$}get webSocketConstructor(){return this.opts.webSocketConstructor??W.webSocketConstructor}set webSocketConstructor($){this.opts.webSocketConstructor=$}static get wsProxy(){return W.opts.wsProxy??W.defaults.wsProxy}static set wsProxy($){W.opts.wsProxy=$}get wsProxy(){return this.opts.wsProxy??W.wsProxy}set wsProxy($){this.opts.wsProxy=$}static get coalesceWrites(){return W.opts.coalesceWrites??W.defaults.coalesceWrites}static set coalesceWrites($){W.opts.coalesceWrites=$}get coalesceWrites(){return this.opts.coalesceWrites??W.coalesceWrites}set coalesceWrites($){this.opts.coalesceWrites=$}static get useSecureWebSocket(){return W.opts.useSecureWebSocket??W.defaults.useSecureWebSocket}static set useSecureWebSocket($){W.opts.useSecureWebSocket=$}get useSecureWebSocket(){return this.opts.useSecureWebSocket??W.useSecureWebSocket}set useSecureWebSocket($){this.opts.useSecureWebSocket=$}static get forceDisablePgSSL(){return W.opts.forceDisablePgSSL??W.defaults.forceDisablePgSSL}static set forceDisablePgSSL($){W.opts.forceDisablePgSSL=$}get forceDisablePgSSL(){return this.opts.forceDisablePgSSL??W.forceDisablePgSSL}set forceDisablePgSSL($){this.opts.forceDisablePgSSL=$}static get disableSNI(){return W.opts.disableSNI??W.defaults.disableSNI}static set disableSNI($){W.opts.disableSNI=$}get disableSNI(){return this.opts.disableSNI??W.disableSNI}set disableSNI($){this.opts.disableSNI=$}static get disableWarningInBrowsers(){return W.opts.disableWarningInBrowsers??W.defaults.disableWarningInBrowsers}static set disableWarningInBrowsers($){W.opts.disableWarningInBrowsers=$}get disableWarningInBrowsers(){return this.opts.disableWarningInBrowsers??W.disableWarningInBrowsers}set disableWarningInBrowsers($){this.opts.disableWarningInBrowsers=$}static get pipelineConnect(){return W.opts.pipelineConnect??W.defaults.pipelineConnect}static set pipelineConnect($){W.opts.pipelineConnect=$}get pipelineConnect(){return this.opts.pipelineConnect??W.pipelineConnect}set pipelineConnect($){this.opts.pipelineConnect=$}static get subtls(){return W.opts.subtls??W.defaults.subtls}static set subtls($){W.opts.subtls=$}get subtls(){return this.opts.subtls??W.subtls}set subtls($){this.opts.subtls=$}static get pipelineTLS(){return W.opts.pipelineTLS??W.defaults.pipelineTLS}static set pipelineTLS($){W.opts.pipelineTLS=$}get pipelineTLS(){return this.opts.pipelineTLS??W.pipelineTLS}set pipelineTLS($){this.opts.pipelineTLS=$}static get rootCerts(){return W.opts.rootCerts??W.defaults.rootCerts}static set rootCerts($){W.opts.rootCerts=$}get rootCerts(){return this.opts.rootCerts??W.rootCerts}set rootCerts($){this.opts.rootCerts=$}wsProxyAddrForHost($,Z){let J=this.wsProxy;if(J===void 0)throw Error("No WebSocket proxy is configured. Please see https://github.com/neondatabase/serverless/blob/main/CONFIG.md#wsproxy-string--host-string-port-number--string--string");return typeof J=="function"?J($,Z):`${J}?address=${$}:${Z}`}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}connect($,Z,J){this.connecting=!0,J&&this.once("connect",J);let X=U(()=>{this.connecting=!1,this.pending=!1,this.emit("connect"),this.emit("ready")},"handleWebSocketOpen"),Y=U((G,V=!1)=>{G.binaryType="arraybuffer",G.addEventListener("error",(R)=>{this.emit("error",R),this.emit("close")}),G.addEventListener("message",(R)=>{if(this.tlsState===0){let P=i.from(R.data);this.emit("data",P)}}),G.addEventListener("close",()=>{this.emit("close")}),V?X():G.addEventListener("open",X)},"configureWebSocket"),M;try{M=this.wsProxyAddrForHost(Z,typeof $=="string"?parseInt($,10):$)}catch(G){this.emit("error",G),this.emit("close");return}try{let G=(this.useSecureWebSocket?"wss:":"ws:")+"//"+M;if(this.webSocketConstructor!==void 0)this.ws=new this.webSocketConstructor(G),Y(this.ws);else try{this.ws=new WebSocket(G),Y(this.ws)}catch{this.ws=new __unstable_WebSocket(G),Y(this.ws)}}catch(G){let V=(this.useSecureWebSocket?"https:":"http:")+"//"+M;fetch(V,{headers:{Upgrade:"websocket"}}).then((R)=>{if(this.ws=R.webSocket,this.ws==null)throw G;this.ws.accept(),Y(this.ws,!0)}).catch((R)=>{this.emit("error",Error(`All attempts to open a WebSocket to connect to the database failed. Please refer to https://github.com/neondatabase/serverless/blob/main/CONFIG.md#websocketconstructor-typeof-websocket--undefined. Details: ${R}`)),this.emit("close")})}}async startTls($){if(this.subtls===void 0)throw Error("For Postgres SSL connections, you must set `neonConfig.subtls` to the subtls library. See https://github.com/neondatabase/serverless/blob/main/CONFIG.md for more information.");this.tlsState=1;let Z=await this.subtls.TrustedCert.databaseFromPEM(this.rootCerts),J=new this.subtls.WebSocketReadQueue(this.ws),X=J.read.bind(J),Y=this.rawWrite.bind(this),{read:M,write:G}=await this.subtls.startTls($,Z,X,Y,{useSNI:!this.disableSNI,expectPreData:this.pipelineTLS?new Uint8Array([83]):void 0});this.tlsRead=M,this.tlsWrite=G,this.tlsState=2,this.encrypted=!0,this.authorized=!0,this.emit("secureConnection",this),this.tlsReadLoop()}async tlsReadLoop(){for(;;){let $=await this.tlsRead();if($===void 0)break;{let Z=i.from($);this.emit("data",Z)}}}rawWrite($){if(!this.coalesceWrites){this.ws&&this.ws.send($);return}if(this.writeBuffer===void 0)this.writeBuffer=$,setTimeout(()=>{this.ws&&this.ws.send(this.writeBuffer),this.writeBuffer=void 0},0);else{let Z=new Uint8Array(this.writeBuffer.length+$.length);Z.set(this.writeBuffer),Z.set($,this.writeBuffer.length),this.writeBuffer=Z}}write($,Z="utf8",J=(X)=>{}){return $.length===0?(J(),!0):(typeof $=="string"&&($=i.from($,Z)),this.tlsState===0?(this.rawWrite($),J()):this.tlsState===1?this.once("secureConnection",()=>{this.write($,Z,J)}):(this.tlsWrite($),J()),!0)}end($=i.alloc(0),Z="utf8",J=()=>{}){return this.write($,Z,()=>{this.ws.close(),J()}),this}destroy(){return this.destroyed=!0,this.end()}},U(lW,"Socket"),t(lW,"defaults",{poolQueryViaFetch:!1,fetchEndpoint:U((W,$,Z)=>{let J;return Z?.jwtAuth?J=W.replace(X9,"apiauth."):J=W.replace(X9,"api."),"https://"+J+"/sql"},"fetchEndpoint"),fetchConnectionCache:!0,fetchFunction:void 0,webSocketConstructor:void 0,wsProxy:U((W)=>W+"/v2","wsProxy"),useSecureWebSocket:!0,forceDisablePgSSL:!0,coalesceWrites:!0,pipelineConnect:"password",subtls:void 0,rootCerts:"",pipelineTLS:!1,disableSNI:!1,disableWarningInBrowsers:!1}),t(lW,"opts",{}),w8=lW}),S7={};S0(S7,{parse:()=>L9});function L9(W,$=!1){let{protocol:Z}=new URL(W),J="http:"+W.substring(Z.length),{username:X,password:Y,host:M,hostname:G,port:V,pathname:R,search:P,searchParams:w,hash:D}=new URL(J);Y=decodeURIComponent(Y),X=decodeURIComponent(X),R=decodeURIComponent(R);let S=X+":"+Y,F=$?Object.fromEntries(w.entries()):P;return{href:W,protocol:Z,auth:S,username:X,password:Y,host:M,hostname:G,port:V,pathname:R,search:P,query:F,hash:D}}var _7=d1(()=>{u(),U(L9,"parse")}),v7=o((W)=>{u(),W.parse=function(X,Y){return new Z(X,Y).parse()};var $=class X{constructor(Y,M){this.source=Y,this.transform=M||J,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var Y=this.source[this.position++];return Y==="\\"?{value:this.source[this.position++],escaped:!0}:{value:Y,escaped:!1}}record(Y){this.recorded.push(Y)}newEntry(Y){var M;(this.recorded.length>0||Y)&&(M=this.recorded.join(""),M==="NULL"&&!Y&&(M=null),M!==null&&(M=this.transform(M)),this.entries.push(M),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var Y=this.nextCharacter();if(Y.value==="=")break}}parse(Y){var M,G,V;for(this.consumeDimensions();!this.isEof();)if(M=this.nextCharacter(),M.value==="{"&&!V)this.dimension++,this.dimension>1&&(G=new X(this.source.substr(this.position-1),this.transform),this.entries.push(G.parse(!0)),this.position+=G.position-2);else if(M.value==="}"&&!V){if(this.dimension--,!this.dimension&&(this.newEntry(),Y))return this.entries}else M.value==='"'&&!M.escaped?(V&&this.newEntry(!0),V=!V):M.value===","&&!V?this.newEntry():this.record(M.value);if(this.dimension!==0)throw Error("array dimension not balanced");return this.entries}};U($,"ArrayParser");var Z=$;function J(X){return X}U(J,"identity")}),E7=o((W,$)=>{u();var Z=v7();$.exports={create:U(function(J,X){return{parse:U(function(){return Z.parse(J,X)},"parse")}},"create")}}),SZ=o((W,$)=>{u();var Z=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,J=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,X=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,Y=/^-?infinity$/;$.exports=U(function(P){if(Y.test(P))return Number(P.replace("i","I"));var w=Z.exec(P);if(!w)return M(P)||null;var D=!!w[8],S=parseInt(w[1],10);D&&(S=V(S));var F=parseInt(w[2],10)-1,L=w[3],Q=parseInt(w[4],10),_=parseInt(w[5],10),v=parseInt(w[6],10),T=w[7];T=T?1000*parseFloat(T):0;var x,q=G(P);return q!=null?(x=new Date(Date.UTC(S,F,L,Q,_,v,T)),R(S)&&x.setUTCFullYear(S),q!==0&&x.setTime(x.getTime()-q)):(x=new Date(S,F,L,Q,_,v,T),R(S)&&x.setFullYear(S)),x},"parseDate");function M(P){var w=J.exec(P);if(w){var D=parseInt(w[1],10),S=!!w[4];S&&(D=V(D));var F=parseInt(w[2],10)-1,L=w[3],Q=new Date(D,F,L);return R(D)&&Q.setFullYear(D),Q}}U(M,"getDate");function G(P){if(P.endsWith("+00"))return 0;var w=X.exec(P.split(" ")[1]);if(w){var D=w[1];if(D==="Z")return 0;var S=D==="-"?-1:1,F=parseInt(w[2],10)*3600+parseInt(w[3]||0,10)*60+parseInt(w[4]||0,10);return F*S*1000}}U(G,"timeZoneOffset");function V(P){return-(P-1)}U(V,"bcYearToNegativeYear");function R(P){return P>=0&&P<100}U(R,"is0To99")}),_Z=o((W,$)=>{u(),$.exports=J;var Z=Object.prototype.hasOwnProperty;function J(X){for(var Y=1;Y<arguments.length;Y++){var M=arguments[Y];for(var G in M)Z.call(M,G)&&(X[G]=M[G])}return X}U(J,"extend")}),vZ=o((W,$)=>{u();var Z=_Z();$.exports=J;function J(v){if(!(this instanceof J))return new J(v);Z(this,_(v))}U(J,"PostgresInterval");var X=["seconds","minutes","hours","days","months","years"];J.prototype.toPostgres=function(){var v=X.filter(this.hasOwnProperty,this);return this.milliseconds&&v.indexOf("seconds")<0&&v.push("seconds"),v.length===0?"0":v.map(function(T){var x=this[T]||0;return T==="seconds"&&this.milliseconds&&(x=(x+this.milliseconds/1000).toFixed(6).replace(/\.?0+$/,"")),x+" "+T},this).join(" ")};var Y={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},M=["years","months","days"],G=["hours","minutes","seconds"];J.prototype.toISOString=J.prototype.toISO=function(){var v=M.map(x,this).join(""),T=G.map(x,this).join("");return"P"+v+"T"+T;function x(q){var E=this[q]||0;return q==="seconds"&&this.milliseconds&&(E=(E+this.milliseconds/1000).toFixed(6).replace(/0+$/,"")),E+Y[q]}};var V="([+-]?\\d+)",R=V+"\\s+years?",P=V+"\\s+mons?",w=V+"\\s+days?",D="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",S=new RegExp([R,P,w,D].map(function(v){return"("+v+")?"}).join("\\s*")),F={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},L=["hours","minutes","seconds","milliseconds"];function Q(v){var T=v+"000000".slice(v.length);return parseInt(T,10)/1000}U(Q,"parseMilliseconds");function _(v){if(!v)return{};var T=S.exec(v),x=T[8]==="-";return Object.keys(F).reduce(function(q,E){var N=F[E],A=T[N];return!A||(A=E==="milliseconds"?Q(A):parseInt(A,10),!A)||(x&&~L.indexOf(E)&&(A*=-1),q[E]=A),q},{})}U(_,"parse")}),EZ=o((W,$)=>{u(),$.exports=U(function(Z){if(/^\\x/.test(Z))return new i(Z.substr(2),"hex");for(var J="",X=0;X<Z.length;)if(Z[X]!=="\\")J+=Z[X],++X;else if(/[0-7]{3}/.test(Z.substr(X+1,3)))J+=String.fromCharCode(parseInt(Z.substr(X+1,3),8)),X+=4;else{for(var Y=1;X+Y<Z.length&&Z[X+Y]==="\\";)Y++;for(var M=0;M<Math.floor(Y/2);++M)J+="\\";X+=Math.floor(Y/2)*2}return new i(J,"binary")},"parseBytea")}),hZ=o((W,$)=>{u();var Z=v7(),J=E7(),X=SZ(),Y=vZ(),M=EZ();function G(f){return U(function(B){return B===null?B:f(B)},"nullAllowed")}U(G,"allowNull");function V(f){return f===null?f:f==="TRUE"||f==="t"||f==="true"||f==="y"||f==="yes"||f==="on"||f==="1"}U(V,"parseBool");function R(f){return f?Z.parse(f,V):null}U(R,"parseBoolArray");function P(f){return parseInt(f,10)}U(P,"parseBaseTenInt");function w(f){return f?Z.parse(f,G(P)):null}U(w,"parseIntegerArray");function D(f){return f?Z.parse(f,G(function(B){return x(B).trim()})):null}U(D,"parseBigIntegerArray");var S=U(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=E(C)),C});return B.parse()},"parsePointArray"),F=U(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=parseFloat(C)),C});return B.parse()},"parseFloatArray"),L=U(function(f){if(!f)return null;var B=J.create(f);return B.parse()},"parseStringArray"),Q=U(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=X(C)),C});return B.parse()},"parseDateArray"),_=U(function(f){if(!f)return null;var B=J.create(f,function(C){return C!==null&&(C=Y(C)),C});return B.parse()},"parseIntervalArray"),v=U(function(f){return f?Z.parse(f,G(M)):null},"parseByteAArray"),T=U(function(f){return parseInt(f,10)},"parseInteger"),x=U(function(f){var B=String(f);return/^\d+$/.test(B)?B:f},"parseBigInteger"),q=U(function(f){return f?Z.parse(f,G(JSON.parse)):null},"parseJsonArray"),E=U(function(f){return f[0]!=="("?null:(f=f.substring(1,f.length-1).split(","),{x:parseFloat(f[0]),y:parseFloat(f[1])})},"parsePoint"),N=U(function(f){if(f[0]!=="<"&&f[1]!=="(")return null;for(var B="(",C="",c=!1,m=2;m<f.length-1;m++){if(c||(B+=f[m]),f[m]===")"){c=!0;continue}else if(!c)continue;f[m]!==","&&(C+=f[m])}var b=E(B);return b.radius=parseFloat(C),b},"parseCircle"),A=U(function(f){f(20,x),f(21,T),f(23,T),f(26,T),f(700,parseFloat),f(701,parseFloat),f(16,V),f(1082,X),f(1114,X),f(1184,X),f(600,E),f(651,L),f(718,N),f(1000,R),f(1001,v),f(1005,w),f(1007,w),f(1028,w),f(1016,D),f(1017,S),f(1021,F),f(1022,F),f(1231,F),f(1014,L),f(1015,L),f(1008,L),f(1009,L),f(1040,L),f(1041,L),f(1115,Q),f(1182,Q),f(1185,Q),f(1186,Y),f(1187,_),f(17,M),f(114,JSON.parse.bind(JSON)),f(3802,JSON.parse.bind(JSON)),f(199,q),f(3807,q),f(3907,L),f(2951,L),f(791,L),f(1183,L),f(1270,L)},"init");$.exports={init:A}}),TZ=o((W,$)=>{u();var Z=1e6;function J(X){var Y=X.readInt32BE(0),M=X.readUInt32BE(4),G="";Y<0&&(Y=~Y+(M===0),M=~M+1>>>0,G="-");var V="",R,P,w,D,S,F;{if(R=Y%Z,Y=Y/Z>>>0,P=4294967296*R+M,M=P/Z>>>0,w=""+(P-Z*M),M===0&&Y===0)return G+w+V;for(D="",S=6-w.length,F=0;F<S;F++)D+="0";V=D+w+V}{if(R=Y%Z,Y=Y/Z>>>0,P=4294967296*R+M,M=P/Z>>>0,w=""+(P-Z*M),M===0&&Y===0)return G+w+V;for(D="",S=6-w.length,F=0;F<S;F++)D+="0";V=D+w+V}{if(R=Y%Z,Y=Y/Z>>>0,P=4294967296*R+M,M=P/Z>>>0,w=""+(P-Z*M),M===0&&Y===0)return G+w+V;for(D="",S=6-w.length,F=0;F<S;F++)D+="0";V=D+w+V}return R=Y%Z,P=4294967296*R+M,w=""+P%Z,G+w+V}U(J,"readInt8"),$.exports=J}),fZ=o((W,$)=>{u();var Z=TZ(),J=U(function(L,Q,_,v,T){_=_||0,v=v||!1,T=T||function(c,m,b){return c*Math.pow(2,b)+m};var x=_>>3,q=U(function(c){return v?~c&255:c},"inv"),E=255,N=8-_%8;Q<N&&(E=255<<8-Q&255,N=Q),_&&(E=E>>_%8);var A=0;_%8+Q>=8&&(A=T(0,q(L[x])&E,N));for(var f=Q+_>>3,B=x+1;B<f;B++)A=T(A,q(L[B]),8);var C=(Q+_)%8;return C>0&&(A=T(A,q(L[f])>>8-C,C)),A},"parseBits"),X=U(function(L,Q,_){var v=Math.pow(2,_-1)-1,T=J(L,1),x=J(L,_,1);if(x===0)return 0;var q=1,E=U(function(A,f,B){A===0&&(A=1);for(var C=1;C<=B;C++)q/=2,(f&1<<B-C)>0&&(A+=q);return A},"parsePrecisionBits"),N=J(L,Q,_+1,!1,E);return x==Math.pow(2,_+1)-1?N===0?T===0?1/0:-1/0:NaN:(T===0?1:-1)*Math.pow(2,x-v)*N},"parseFloatFromBits"),Y=U(function(L){return J(L,1)==1?-1*(J(L,15,1,!0)+1):J(L,15,1)},"parseInt16"),M=U(function(L){return J(L,1)==1?-1*(J(L,31,1,!0)+1):J(L,31,1)},"parseInt32"),G=U(function(L){return X(L,23,8)},"parseFloat32"),V=U(function(L){return X(L,52,11)},"parseFloat64"),R=U(function(L){var Q=J(L,16,32);if(Q==49152)return NaN;for(var _=Math.pow(1e4,J(L,16,16)),v=0,T=[],x=J(L,16),q=0;q<x;q++)v+=J(L,16,64+16*q)*_,_/=1e4;var E=Math.pow(10,J(L,16,48));return(Q===0?1:-1)*Math.round(v*E)/E},"parseNumeric"),P=U(function(L,Q){var _=J(Q,1),v=J(Q,63,1),T=new Date((_===0?1:-1)*v/1000+946684800000);return L||T.setTime(T.getTime()+T.getTimezoneOffset()*60000),T.usec=v%1000,T.getMicroSeconds=function(){return this.usec},T.setMicroSeconds=function(x){this.usec=x},T.getUTCMicroSeconds=function(){return this.usec},T},"parseDate"),w=U(function(L){for(var Q=J(L,32),_=J(L,32,32),v=J(L,32,64),T=96,x=[],q=0;q<Q;q++)x[q]=J(L,32,T),T+=32,T+=32;var E=U(function(A){var f=J(L,32,T);if(T+=32,f==4294967295)return null;var B;if(A==23||A==20)return B=J(L,f*8,T),T+=f*8,B;if(A==25)return B=L.toString(this.encoding,T>>3,(T+=f<<3)>>3),B;console.log("ERROR: ElementType not implemented: "+A)},"parseElement"),N=U(function(A,f){var B=[],C;if(A.length>1){var c=A.shift();for(C=0;C<c;C++)B[C]=N(A,f);A.unshift(c)}else for(C=0;C<A[0];C++)B[C]=E(f);return B},"parse");return N(x,v)},"parseArray"),D=U(function(L){return L.toString("utf8")},"parseText"),S=U(function(L){return L===null?null:J(L,8)>0},"parseBool"),F=U(function(L){L(20,Z),L(21,Y),L(23,M),L(26,M),L(1700,R),L(700,G),L(701,V),L(16,S),L(1114,P.bind(null,!1)),L(1184,P.bind(null,!0)),L(1000,w),L(1007,w),L(1016,w),L(1008,w),L(1009,w),L(25,D)},"init");$.exports={init:F}}),jZ=o((W,$)=>{u(),$.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}}),B4=o((W)=>{u();var $=hZ(),Z=fZ(),J=E7(),X=jZ();W.getTypeParser=G,W.setTypeParser=V,W.arrayParser=J,W.builtins=X;var Y={text:{},binary:{}};function M(R){return String(R)}U(M,"noParse");function G(R,P){return P=P||"text",Y[P]&&Y[P][R]||M}U(G,"getTypeParser");function V(R,P,w){typeof P=="function"&&(w=P,P="text"),Y[P][R]=w}U(V,"setTypeParser"),$.init(function(R,P){Y.text[R]=P}),Z.init(function(R,P){Y.binary[R]=P})}),K9=o((W,$)=>{u();var Z=B4();function J(X){this._types=X||Z,this.text={},this.binary={}}U(J,"TypeOverrides"),J.prototype.getOverrides=function(X){switch(X){case"text":return this.text;case"binary":return this.binary;default:return{}}},J.prototype.setTypeParser=function(X,Y,M){typeof Y=="function"&&(M=Y,Y="text"),this.getOverrides(Y)[X]=M},J.prototype.getTypeParser=function(X,Y){return Y=Y||"text",this.getOverrides(Y)[X]||this._types.getTypeParser(X,Y)},$.exports=J});function iW(W){let $=1779033703,Z=3144134277,J=1013904242,X=2773480762,Y=1359893119,M=2600822924,G=528734635,V=1541459225,R=0,P=0,w=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],D=U((v,T)=>v>>>T|v<<32-T,"rrot"),S=new Uint32Array(64),F=new Uint8Array(64),L=U(()=>{for(let B=0,C=0;B<16;B++,C+=4)S[B]=F[C]<<24|F[C+1]<<16|F[C+2]<<8|F[C+3];for(let B=16;B<64;B++){let C=D(S[B-15],7)^D(S[B-15],18)^S[B-15]>>>3,c=D(S[B-2],17)^D(S[B-2],19)^S[B-2]>>>10;S[B]=S[B-16]+C+S[B-7]+c|0}let v=$,T=Z,x=J,q=X,E=Y,N=M,A=G,f=V;for(let B=0;B<64;B++){let C=D(E,6)^D(E,11)^D(E,25),c=E&N^~E&A,m=f+C+c+w[B]+S[B]|0,b=D(v,2)^D(v,13)^D(v,22),g=v&T^v&x^T&x,p=b+g|0;f=A,A=N,N=E,E=q+m|0,q=x,x=T,T=v,v=m+p|0}$=$+v|0,Z=Z+T|0,J=J+x|0,X=X+q|0,Y=Y+E|0,M=M+N|0,G=G+A|0,V=V+f|0,P=0},"process"),Q=U((v)=>{typeof v=="string"&&(v=new TextEncoder().encode(v));for(let T=0;T<v.length;T++)F[P++]=v[T],P===64&&L();R+=v.length},"add"),_=U(()=>{if(F[P++]=128,P==64&&L(),P+8>64){for(;P<64;)F[P++]=0;L()}for(;P<58;)F[P++]=0;let v=R*8;F[P++]=v/1099511627776&255,F[P++]=v/4294967296&255,F[P++]=v>>>24,F[P++]=v>>>16&255,F[P++]=v>>>8&255,F[P++]=v&255,L();let T=new Uint8Array(32);return T[0]=$>>>24,T[1]=$>>>16&255,T[2]=$>>>8&255,T[3]=$&255,T[4]=Z>>>24,T[5]=Z>>>16&255,T[6]=Z>>>8&255,T[7]=Z&255,T[8]=J>>>24,T[9]=J>>>16&255,T[10]=J>>>8&255,T[11]=J&255,T[12]=X>>>24,T[13]=X>>>16&255,T[14]=X>>>8&255,T[15]=X&255,T[16]=Y>>>24,T[17]=Y>>>16&255,T[18]=Y>>>8&255,T[19]=Y&255,T[20]=M>>>24,T[21]=M>>>16&255,T[22]=M>>>8&255,T[23]=M&255,T[24]=G>>>24,T[25]=G>>>16&255,T[26]=G>>>8&255,T[27]=G&255,T[28]=V>>>24,T[29]=V>>>16&255,T[30]=V>>>8&255,T[31]=V&255,T},"digest");return W===void 0?{add:Q,digest:_}:(Q(W),_())}var AZ=d1(()=>{u(),U(iW,"sha256")}),a0,H9,NZ=d1(()=>{u(),a0=class W{constructor(){t(this,"_dataLength",0),t(this,"_bufferLength",0),t(this,"_state",new Int32Array(4)),t(this,"_buffer",new ArrayBuffer(68)),t(this,"_buffer8"),t(this,"_buffer32"),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashByteArray($,Z=!1){return this.onePassHasher.start().appendByteArray($).end(Z)}static hashStr($,Z=!1){return this.onePassHasher.start().appendStr($).end(Z)}static hashAsciiStr($,Z=!1){return this.onePassHasher.start().appendAsciiStr($).end(Z)}static _hex($){let{hexChars:Z,hexOut:J}=W,X,Y,M,G;for(G=0;G<4;G+=1)for(Y=G*8,X=$[G],M=0;M<8;M+=2)J[Y+1+M]=Z.charAt(X&15),X>>>=4,J[Y+0+M]=Z.charAt(X&15),X>>>=4;return J.join("")}static _md5cycle($,Z){let J=$[0],X=$[1],Y=$[2],M=$[3];J+=(X&Y|~X&M)+Z[0]-680876936|0,J=(J<<7|J>>>25)+X|0,M+=(J&X|~J&Y)+Z[1]-389564586|0,M=(M<<12|M>>>20)+J|0,Y+=(M&J|~M&X)+Z[2]+606105819|0,Y=(Y<<17|Y>>>15)+M|0,X+=(Y&M|~Y&J)+Z[3]-1044525330|0,X=(X<<22|X>>>10)+Y|0,J+=(X&Y|~X&M)+Z[4]-176418897|0,J=(J<<7|J>>>25)+X|0,M+=(J&X|~J&Y)+Z[5]+1200080426|0,M=(M<<12|M>>>20)+J|0,Y+=(M&J|~M&X)+Z[6]-1473231341|0,Y=(Y<<17|Y>>>15)+M|0,X+=(Y&M|~Y&J)+Z[7]-45705983|0,X=(X<<22|X>>>10)+Y|0,J+=(X&Y|~X&M)+Z[8]+1770035416|0,J=(J<<7|J>>>25)+X|0,M+=(J&X|~J&Y)+Z[9]-1958414417|0,M=(M<<12|M>>>20)+J|0,Y+=(M&J|~M&X)+Z[10]-42063|0,Y=(Y<<17|Y>>>15)+M|0,X+=(Y&M|~Y&J)+Z[11]-1990404162|0,X=(X<<22|X>>>10)+Y|0,J+=(X&Y|~X&M)+Z[12]+1804603682|0,J=(J<<7|J>>>25)+X|0,M+=(J&X|~J&Y)+Z[13]-40341101|0,M=(M<<12|M>>>20)+J|0,Y+=(M&J|~M&X)+Z[14]-1502002290|0,Y=(Y<<17|Y>>>15)+M|0,X+=(Y&M|~Y&J)+Z[15]+1236535329|0,X=(X<<22|X>>>10)+Y|0,J+=(X&M|Y&~M)+Z[1]-165796510|0,J=(J<<5|J>>>27)+X|0,M+=(J&Y|X&~Y)+Z[6]-1069501632|0,M=(M<<9|M>>>23)+J|0,Y+=(M&X|J&~X)+Z[11]+643717713|0,Y=(Y<<14|Y>>>18)+M|0,X+=(Y&J|M&~J)+Z[0]-373897302|0,X=(X<<20|X>>>12)+Y|0,J+=(X&M|Y&~M)+Z[5]-701558691|0,J=(J<<5|J>>>27)+X|0,M+=(J&Y|X&~Y)+Z[10]+38016083|0,M=(M<<9|M>>>23)+J|0,Y+=(M&X|J&~X)+Z[15]-660478335|0,Y=(Y<<14|Y>>>18)+M|0,X+=(Y&J|M&~J)+Z[4]-405537848|0,X=(X<<20|X>>>12)+Y|0,J+=(X&M|Y&~M)+Z[9]+568446438|0,J=(J<<5|J>>>27)+X|0,M+=(J&Y|X&~Y)+Z[14]-1019803690|0,M=(M<<9|M>>>23)+J|0,Y+=(M&X|J&~X)+Z[3]-187363961|0,Y=(Y<<14|Y>>>18)+M|0,X+=(Y&J|M&~J)+Z[8]+1163531501|0,X=(X<<20|X>>>12)+Y|0,J+=(X&M|Y&~M)+Z[13]-1444681467|0,J=(J<<5|J>>>27)+X|0,M+=(J&Y|X&~Y)+Z[2]-51403784|0,M=(M<<9|M>>>23)+J|0,Y+=(M&X|J&~X)+Z[7]+1735328473|0,Y=(Y<<14|Y>>>18)+M|0,X+=(Y&J|M&~J)+Z[12]-1926607734|0,X=(X<<20|X>>>12)+Y|0,J+=(X^Y^M)+Z[5]-378558|0,J=(J<<4|J>>>28)+X|0,M+=(J^X^Y)+Z[8]-2022574463|0,M=(M<<11|M>>>21)+J|0,Y+=(M^J^X)+Z[11]+1839030562|0,Y=(Y<<16|Y>>>16)+M|0,X+=(Y^M^J)+Z[14]-35309556|0,X=(X<<23|X>>>9)+Y|0,J+=(X^Y^M)+Z[1]-1530992060|0,J=(J<<4|J>>>28)+X|0,M+=(J^X^Y)+Z[4]+1272893353|0,M=(M<<11|M>>>21)+J|0,Y+=(M^J^X)+Z[7]-155497632|0,Y=(Y<<16|Y>>>16)+M|0,X+=(Y^M^J)+Z[10]-1094730640|0,X=(X<<23|X>>>9)+Y|0,J+=(X^Y^M)+Z[13]+681279174|0,J=(J<<4|J>>>28)+X|0,M+=(J^X^Y)+Z[0]-358537222|0,M=(M<<11|M>>>21)+J|0,Y+=(M^J^X)+Z[3]-722521979|0,Y=(Y<<16|Y>>>16)+M|0,X+=(Y^M^J)+Z[6]+76029189|0,X=(X<<23|X>>>9)+Y|0,J+=(X^Y^M)+Z[9]-640364487|0,J=(J<<4|J>>>28)+X|0,M+=(J^X^Y)+Z[12]-421815835|0,M=(M<<11|M>>>21)+J|0,Y+=(M^J^X)+Z[15]+530742520|0,Y=(Y<<16|Y>>>16)+M|0,X+=(Y^M^J)+Z[2]-995338651|0,X=(X<<23|X>>>9)+Y|0,J+=(Y^(X|~M))+Z[0]-198630844|0,J=(J<<6|J>>>26)+X|0,M+=(X^(J|~Y))+Z[7]+1126891415|0,M=(M<<10|M>>>22)+J|0,Y+=(J^(M|~X))+Z[14]-1416354905|0,Y=(Y<<15|Y>>>17)+M|0,X+=(M^(Y|~J))+Z[5]-57434055|0,X=(X<<21|X>>>11)+Y|0,J+=(Y^(X|~M))+Z[12]+1700485571|0,J=(J<<6|J>>>26)+X|0,M+=(X^(J|~Y))+Z[3]-1894986606|0,M=(M<<10|M>>>22)+J|0,Y+=(J^(M|~X))+Z[10]-1051523|0,Y=(Y<<15|Y>>>17)+M|0,X+=(M^(Y|~J))+Z[1]-2054922799|0,X=(X<<21|X>>>11)+Y|0,J+=(Y^(X|~M))+Z[8]+1873313359|0,J=(J<<6|J>>>26)+X|0,M+=(X^(J|~Y))+Z[15]-30611744|0,M=(M<<10|M>>>22)+J|0,Y+=(J^(M|~X))+Z[6]-1560198380|0,Y=(Y<<15|Y>>>17)+M|0,X+=(M^(Y|~J))+Z[13]+1309151649|0,X=(X<<21|X>>>11)+Y|0,J+=(Y^(X|~M))+Z[4]-145523070|0,J=(J<<6|J>>>26)+X|0,M+=(X^(J|~Y))+Z[11]-1120210379|0,M=(M<<10|M>>>22)+J|0,Y+=(J^(M|~X))+Z[2]+718787259|0,Y=(Y<<15|Y>>>17)+M|0,X+=(M^(Y|~J))+Z[9]-343485551|0,X=(X<<21|X>>>11)+Y|0,$[0]=J+$[0]|0,$[1]=X+$[1]|0,$[2]=Y+$[2]|0,$[3]=M+$[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(W.stateIdentity),this}appendStr($){let Z=this._buffer8,J=this._buffer32,X=this._bufferLength,Y,M;for(M=0;M<$.length;M+=1){if(Y=$.charCodeAt(M),Y<128)Z[X++]=Y;else if(Y<2048)Z[X++]=(Y>>>6)+192,Z[X++]=Y&63|128;else if(Y<55296||Y>56319)Z[X++]=(Y>>>12)+224,Z[X++]=Y>>>6&63|128,Z[X++]=Y&63|128;else{if(Y=(Y-55296)*1024+($.charCodeAt(++M)-56320)+65536,Y>1114111)throw Error("Unicode standard supports code points up to U+10FFFF");Z[X++]=(Y>>>18)+240,Z[X++]=Y>>>12&63|128,Z[X++]=Y>>>6&63|128,Z[X++]=Y&63|128}X>=64&&(this._dataLength+=64,W._md5cycle(this._state,J),X-=64,J[0]=J[16])}return this._bufferLength=X,this}appendAsciiStr($){let Z=this._buffer8,J=this._buffer32,X=this._bufferLength,Y,M=0;for(;;){for(Y=Math.min($.length-M,64-X);Y--;)Z[X++]=$.charCodeAt(M++);if(X<64)break;this._dataLength+=64,W._md5cycle(this._state,J),X=0}return this._bufferLength=X,this}appendByteArray($){let Z=this._buffer8,J=this._buffer32,X=this._bufferLength,Y,M=0;for(;;){for(Y=Math.min($.length-M,64-X);Y--;)Z[X++]=$[M++];if(X<64)break;this._dataLength+=64,W._md5cycle(this._state,J),X=0}return this._bufferLength=X,this}getState(){let $=this._state;return{buffer:String.fromCharCode.apply(null,Array.from(this._buffer8)),buflen:this._bufferLength,length:this._dataLength,state:[$[0],$[1],$[2],$[3]]}}setState($){let{buffer:Z,state:J}=$,X=this._state,Y;for(this._dataLength=$.length,this._bufferLength=$.buflen,X[0]=J[0],X[1]=J[1],X[2]=J[2],X[3]=J[3],Y=0;Y<Z.length;Y+=1)this._buffer8[Y]=Z.charCodeAt(Y)}end($=!1){let Z=this._bufferLength,J=this._buffer8,X=this._buffer32,Y=(Z>>2)+1;this._dataLength+=Z;let M=this._dataLength*8;if(J[Z]=128,J[Z+1]=J[Z+2]=J[Z+3]=0,X.set(W.buffer32Identity.subarray(Y),Y),Z>55&&(W._md5cycle(this._state,X),X.set(W.buffer32Identity)),M<=4294967295)X[14]=M;else{let G=M.toString(16).match(/(.*?)(.{0,8})$/);if(G===null)return;let V=parseInt(G[2],16),R=parseInt(G[1],16)||0;X[14]=V,X[15]=R}return W._md5cycle(this._state,X),$?this._state:W._hex(this._state)}},U(a0,"Md5"),t(a0,"stateIdentity",new Int32Array([1732584193,-271733879,-1732584194,271733878])),t(a0,"buffer32Identity",new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])),t(a0,"hexChars","0123456789abcdef"),t(a0,"hexOut",[]),t(a0,"onePassHasher",new a0),H9=a0}),z9={};S0(z9,{createHash:()=>T7,createHmac:()=>f7,randomBytes:()=>h7});function h7(W){return crypto.getRandomValues(i.alloc(W))}function T7(W){if(W==="sha256")return{update:U(function($){return{digest:U(function(){return i.from(iW($))},"digest")}},"update")};if(W==="md5")return{update:U(function($){return{digest:U(function(){return typeof $=="string"?H9.hashStr($):H9.hashByteArray($)},"digest")}},"update")};throw Error(`Hash type '${W}' not supported`)}function f7(W,$){if(W!=="sha256")throw Error(`Only sha256 is supported (requested: '${W}')`);return{update:U(function(Z){return{digest:U(function(){typeof $=="string"&&($=new TextEncoder().encode($)),typeof Z=="string"&&(Z=new TextEncoder().encode(Z));let J=$.length;if(J>64)$=iW($);else if(J<64){let V=new Uint8Array(64);V.set($),$=V}let X=new Uint8Array(64),Y=new Uint8Array(64);for(let V=0;V<64;V++)X[V]=54^$[V],Y[V]=92^$[V];let M=new Uint8Array(Z.length+64);M.set(X,0),M.set(Z,64);let G=new Uint8Array(96);return G.set(Y,0),G.set(iW(M),64),i.from(iW(G))},"digest")}},"update")}}var j7=d1(()=>{u(),AZ(),NZ(),U(h7,"randomBytes"),U(T7,"createHash"),U(f7,"createHmac")}),b4=o((W,$)=>{u(),$.exports={host:"localhost",user:r.platform==="win32"?r.env.USERNAME:r.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:30000,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var Z=B4(),J=Z.getTypeParser(20,"text"),X=Z.getTypeParser(1016,"text");$.exports.__defineSetter__("parseInt8",function(Y){Z.setTypeParser(20,"text",Y?Z.getTypeParser(23,"text"):J),Z.setTypeParser(1016,"text",Y?Z.getTypeParser(1007,"text"):X)})}),I4=o((W,$)=>{u();var Z=(j7(),B1(z9)),J=b4();function X(F){var L=F.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");return'"'+L+'"'}U(X,"escapeElement");function Y(F){for(var L="{",Q=0;Q<F.length;Q++)Q>0&&(L=L+","),F[Q]===null||typeof F[Q]>"u"?L=L+"NULL":Array.isArray(F[Q])?L=L+Y(F[Q]):F[Q]instanceof i?L+="\\\\x"+F[Q].toString("hex"):L+=X(M(F[Q]));return L=L+"}",L}U(Y,"arrayString");var M=U(function(F,L){if(F==null)return null;if(F instanceof i)return F;if(ArrayBuffer.isView(F)){var Q=i.from(F.buffer,F.byteOffset,F.byteLength);return Q.length===F.byteLength?Q:Q.slice(F.byteOffset,F.byteOffset+F.byteLength)}return F instanceof Date?J.parseInputDatesAsUTC?P(F):R(F):Array.isArray(F)?Y(F):typeof F=="object"?G(F,L):F.toString()},"prepareValue");function G(F,L){if(F&&typeof F.toPostgres=="function"){if(L=L||[],L.indexOf(F)!==-1)throw Error('circular reference detected while preparing "'+F+'" for query');return L.push(F),M(F.toPostgres(M),L)}return JSON.stringify(F)}U(G,"prepareObject");function V(F,L){for(F=""+F;F.length<L;)F="0"+F;return F}U(V,"pad");function R(F){var L=-F.getTimezoneOffset(),Q=F.getFullYear(),_=Q<1;_&&(Q=Math.abs(Q)+1);var v=V(Q,4)+"-"+V(F.getMonth()+1,2)+"-"+V(F.getDate(),2)+"T"+V(F.getHours(),2)+":"+V(F.getMinutes(),2)+":"+V(F.getSeconds(),2)+"."+V(F.getMilliseconds(),3);return L<0?(v+="-",L*=-1):v+="+",v+=V(Math.floor(L/60),2)+":"+V(L%60,2),_&&(v+=" BC"),v}U(R,"dateToString");function P(F){var L=F.getUTCFullYear(),Q=L<1;Q&&(L=Math.abs(L)+1);var _=V(L,4)+"-"+V(F.getUTCMonth()+1,2)+"-"+V(F.getUTCDate(),2)+"T"+V(F.getUTCHours(),2)+":"+V(F.getUTCMinutes(),2)+":"+V(F.getUTCSeconds(),2)+"."+V(F.getUTCMilliseconds(),3);return _+="+00:00",Q&&(_+=" BC"),_}U(P,"dateToStringUTC");function w(F,L,Q){return F=typeof F=="string"?{text:F}:F,L&&(typeof L=="function"?F.callback=L:F.values=L),Q&&(F.callback=Q),F}U(w,"normalizeQueryConfig");var D=U(function(F){return Z.createHash("md5").update(F,"utf-8").digest("hex")},"md5"),S=U(function(F,L,Q){var _=D(L+F),v=D(i.concat([i.from(_),Q]));return"md5"+v},"postgresMd5PasswordHash");$.exports={prepareValue:U(function(F){return M(F)},"prepareValueWrapper"),normalizeQueryConfig:w,postgresMd5PasswordHash:S,md5:D}}),aW={};S0(aW,{default:()=>A7});var A7,y4=d1(()=>{u(),A7={}}),CZ=o((W,$)=>{u();var Z=(j7(),B1(z9));function J(L){if(L.indexOf("SCRAM-SHA-256")===-1)throw Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let Q=Z.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:Q,response:"n,,n=*,r="+Q,message:"SASLInitialResponse"}}U(J,"startSession");function X(L,Q,_){if(L.message!=="SASLInitialResponse")throw Error("SASL: Last message was not SASLInitialResponse");if(typeof Q!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(typeof _!="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let v=R(_);if(v.nonce.startsWith(L.clientNonce)){if(v.nonce.length===L.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var T=i.from(v.salt,"base64"),x=F(Q,T,v.iteration),q=S(x,"Client Key"),E=D(q),N="n=*,r="+L.clientNonce,A="r="+v.nonce+",s="+v.salt+",i="+v.iteration,f="c=biws,r="+v.nonce,B=N+","+A+","+f,C=S(E,B),c=w(q,C),m=c.toString("base64"),b=S(x,"Server Key"),g=S(b,B);L.message="SASLResponse",L.serverSignature=g.toString("base64"),L.response=f+",p="+m}U(X,"continueSession");function Y(L,Q){if(L.message!=="SASLResponse")throw Error("SASL: Last message was not SASLResponse");if(typeof Q!="string")throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:_}=P(Q);if(_!==L.serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}U(Y,"finalizeSession");function M(L){if(typeof L!="string")throw TypeError("SASL: text must be a string");return L.split("").map((Q,_)=>L.charCodeAt(_)).every((Q)=>Q>=33&&Q<=43||Q>=45&&Q<=126)}U(M,"isPrintableChars");function G(L){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(L)}U(G,"isBase64");function V(L){if(typeof L!="string")throw TypeError("SASL: attribute pairs text must be a string");return new Map(L.split(",").map((Q)=>{if(!/^.=/.test(Q))throw Error("SASL: Invalid attribute pair entry");let _=Q[0],v=Q.substring(2);return[_,v]}))}U(V,"parseAttributePairs");function R(L){let Q=V(L),_=Q.get("r");if(_){if(!M(_))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let v=Q.get("s");if(v){if(!G(v))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let T=Q.get("i");if(T){if(!/^[1-9][0-9]*$/.test(T))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let x=parseInt(T,10);return{nonce:_,salt:v,iteration:x}}U(R,"parseServerFirstMessage");function P(L){let Q=V(L).get("v");if(Q){if(!G(Q))throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:Q}}U(P,"parseServerFinalMessage");function w(L,Q){if(!i.isBuffer(L))throw TypeError("first argument must be a Buffer");if(!i.isBuffer(Q))throw TypeError("second argument must be a Buffer");if(L.length!==Q.length)throw Error("Buffer lengths must match");if(L.length===0)throw Error("Buffers cannot be empty");return i.from(L.map((_,v)=>L[v]^Q[v]))}U(w,"xorBuffers");function D(L){return Z.createHash("sha256").update(L).digest()}U(D,"sha256");function S(L,Q){return Z.createHmac("sha256",L).update(Q).digest()}U(S,"hmacSha256");function F(L,Q,_){for(var v=S(L,i.concat([Q,i.from([0,0,0,1])])),T=v,x=0;x<_-1;x++)v=S(L,v),T=w(T,v);return T}U(F,"Hi"),$.exports={startSession:J,continueSession:X,finalizeSession:Y}}),U9={};S0(U9,{join:()=>N7});function N7(...W){return W.join("/")}var C7=d1(()=>{u(),U(N7,"join")}),V9={};S0(V9,{stat:()=>q7});function q7(W,$){$(Error("No filesystem"))}var O7=d1(()=>{u(),U(q7,"stat")}),P9={};S0(P9,{default:()=>x7});var x7,B7=d1(()=>{u(),x7={}}),b7={};S0(b7,{StringDecoder:()=>I7});var Y9,I7,qZ=d1(()=>{u(),Y9=class{constructor($){t(this,"td"),this.td=new TextDecoder($)}write($){return this.td.decode($,{stream:!0})}end($){return this.td.decode($)}},U(Y9,"StringDecoder"),I7=Y9}),OZ=o((W,$)=>{u();var{Transform:Z}=(B7(),B1(P9)),{StringDecoder:J}=(qZ(),B1(b7)),X=Symbol("last"),Y=Symbol("decoder");function M(w,D,S){let F;if(this.overflow){if(F=this[Y].write(w).split(this.matcher),F.length===1)return S();F.shift(),this.overflow=!1}else this[X]+=this[Y].write(w),F=this[X].split(this.matcher);this[X]=F.pop();for(let L=0;L<F.length;L++)try{V(this,this.mapper(F[L]))}catch(Q){return S(Q)}if(this.overflow=this[X].length>this.maxLength,this.overflow&&!this.skipOverflow){S(Error("maximum buffer reached"));return}S()}U(M,"transform");function G(w){if(this[X]+=this[Y].end(),this[X])try{V(this,this.mapper(this[X]))}catch(D){return w(D)}w()}U(G,"flush");function V(w,D){D!==void 0&&w.push(D)}U(V,"push");function R(w){return w}U(R,"noop");function P(w,D,S){switch(w=w||/\r?\n/,D=D||R,S=S||{},arguments.length){case 1:typeof w=="function"?(D=w,w=/\r?\n/):typeof w=="object"&&!(w instanceof RegExp)&&!w[Symbol.split]&&(S=w,w=/\r?\n/);break;case 2:typeof w=="function"?(S=D,D=w,w=/\r?\n/):typeof D=="object"&&(S=D,D=R)}S=Object.assign({},S),S.autoDestroy=!0,S.transform=M,S.flush=G,S.readableObjectMode=!0;let F=new Z(S);return F[X]="",F[Y]=new J("utf8"),F.matcher=w,F.mapper=D,F.maxLength=S.maxLength,F.skipOverflow=S.skipOverflow||!1,F.overflow=!1,F._destroy=function(L,Q){this._writableState.errorEmitted=!1,Q(L)},F}U(P,"split"),$.exports=P}),xZ=o((W,$)=>{u();var Z=(C7(),B1(U9)),J=(B7(),B1(P9)).Stream,X=OZ(),Y=(y4(),B1(aW)),M=5432,G=r.platform==="win32",V=r.stderr,R=56,P=7,w=61440,D=32768;function S(q){return(q&w)==D}U(S,"isRegFile");var F=["host","port","database","user","password"],L=F.length,Q=F[L-1];function _(){var q=V instanceof J&&V.writable===!0;if(q){var E=Array.prototype.slice.call(arguments).concat(`
28
+ `);V.write(Y.format.apply(Y,E))}}U(_,"warn"),Object.defineProperty($.exports,"isWin",{get:U(function(){return G},"get"),set:U(function(q){G=q},"set")}),$.exports.warnTo=function(q){var E=V;return V=q,E},$.exports.getFileName=function(q){var E=q||r.env,N=E.PGPASSFILE||(G?Z.join(E.APPDATA||"./","postgresql","pgpass.conf"):Z.join(E.HOME||"./",".pgpass"));return N},$.exports.usePgPass=function(q,E){return Object.prototype.hasOwnProperty.call(r.env,"PGPASSWORD")?!1:G?!0:(E=E||"<unkn>",S(q.mode)?q.mode&(R|P)?(_('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',E),!1):!0:(_('WARNING: password file "%s" is not a plain file',E),!1))};var v=$.exports.match=function(q,E){return F.slice(0,-1).reduce(function(N,A,f){return f==1&&Number(q[A]||M)===Number(E[A])?N&&!0:N&&(E[A]==="*"||E[A]===q[A])},!0)};$.exports.getPassword=function(q,E,N){var A,f=E.pipe(X());function B(m){var b=T(m);b&&x(b)&&v(q,b)&&(A=b[Q],f.end())}U(B,"onLine");var C=U(function(){E.destroy(),N(A)},"onEnd"),c=U(function(m){E.destroy(),_("WARNING: error on reading file: %s",m),N(void 0)},"onErr");E.on("error",c),f.on("data",B).on("end",C).on("error",c)};var T=$.exports.parseLine=function(q){if(q.length<11||q.match(/^\s+#/))return null;for(var E="",N="",A=0,f=0,B=0,C={},c=!1,m=U(function(g,p,d){var J1=q.substring(p,d);Object.hasOwnProperty.call(r.env,"PGPASS_NO_DEESCAPE")||(J1=J1.replace(/\\([:\\])/g,"$1")),C[F[g]]=J1},"addToObj"),b=0;b<q.length-1;b+=1){if(E=q.charAt(b+1),N=q.charAt(b),c=A==L-1,c){m(A,f);break}b>=0&&E==":"&&N!=="\\"&&(m(A,f,b+1),f=b+2,A+=1)}return C=Object.keys(C).length===L?C:null,C},x=$.exports.isValidEntry=function(q){for(var E={0:function(C){return C.length>0},1:function(C){return C==="*"?!0:(C=Number(C),isFinite(C)&&C>0&&C<9007199254740992&&Math.floor(C)===C)},2:function(C){return C.length>0},3:function(C){return C.length>0},4:function(C){return C.length>0}},N=0;N<F.length;N+=1){var A=E[N],f=q[F[N]]||"",B=A(f);if(!B)return!1}return!0}}),BZ=o((W,$)=>{u();var Z=(C7(),B1(U9)),J=(O7(),B1(V9)),X=xZ();$.exports=function(Y,M){var G=X.getFileName();J.stat(G,function(V,R){if(V||!X.usePgPass(R,G))return M(void 0);var P=J.createReadStream(G);X.getPassword(Y,P,M)})},$.exports.warnTo=X.warnTo}),y7={};S0(y7,{default:()=>g7});var g7,bZ=d1(()=>{u(),g7={}}),IZ=o((W,$)=>{u();var Z=(_7(),B1(S7)),J=(O7(),B1(V9));function X(Y){if(Y.charAt(0)==="/"){var G=Y.split(" ");return{host:G[0],database:G[1]}}var M=Z.parse(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(Y)?encodeURI(Y).replace(/\%25(\d\d)/g,"%$1"):Y,!0),G=M.query;for(var V in G)Array.isArray(G[V])&&(G[V]=G[V][G[V].length-1]);var R=(M.auth||":").split(":");if(G.user=R[0],G.password=R.splice(1).join(":"),G.port=M.port,M.protocol=="socket:")return G.host=decodeURI(M.pathname),G.database=M.query.db,G.client_encoding=M.query.encoding,G;G.host||(G.host=M.hostname);var P=M.pathname;if(!G.host&&P&&/^%2f/i.test(P)){var w=P.split("/");G.host=decodeURIComponent(w[0]),P=w.splice(1).join("/")}switch(P&&P.charAt(0)==="/"&&(P=P.slice(1)||null),G.database=P&&decodeURI(P),(G.ssl==="true"||G.ssl==="1")&&(G.ssl=!0),G.ssl==="0"&&(G.ssl=!1),(G.sslcert||G.sslkey||G.sslrootcert||G.sslmode)&&(G.ssl={}),G.sslcert&&(G.ssl.cert=J.readFileSync(G.sslcert).toString()),G.sslkey&&(G.ssl.key=J.readFileSync(G.sslkey).toString()),G.sslrootcert&&(G.ssl.ca=J.readFileSync(G.sslrootcert).toString()),G.sslmode){case"disable":{G.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{G.ssl.rejectUnauthorized=!1;break}}return G}U(X,"parse"),$.exports=X,X.parse=X}),F9=o((W,$)=>{u();var Z=(bZ(),B1(y7)),J=b4(),X=IZ().parse,Y=U(function(w,D,S){return S===void 0?S=r.env["PG"+w.toUpperCase()]:S===!1||(S=r.env[S]),D[w]||S||J[w]},"val"),M=U(function(){switch(r.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return J.ssl},"readSSLConfigFromEnvironment"),G=U(function(w){return"'"+(""+w).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),V=U(function(w,D,S){var F=D[S];F!=null&&w.push(S+"="+G(F))},"add"),R=class{constructor(D){D=typeof D=="string"?X(D):D||{},D.connectionString&&(D=Object.assign({},D,X(D.connectionString))),this.user=Y("user",D),this.database=Y("database",D),this.database===void 0&&(this.database=this.user),this.port=parseInt(Y("port",D),10),this.host=Y("host",D),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:Y("password",D)}),this.binary=Y("binary",D),this.options=Y("options",D),this.ssl=typeof D.ssl>"u"?M():D.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=Y("client_encoding",D),this.replication=Y("replication",D),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=Y("application_name",D,"PGAPPNAME"),this.fallback_application_name=Y("fallback_application_name",D,!1),this.statement_timeout=Y("statement_timeout",D,!1),this.lock_timeout=Y("lock_timeout",D,!1),this.idle_in_transaction_session_timeout=Y("idle_in_transaction_session_timeout",D,!1),this.query_timeout=Y("query_timeout",D,!1),D.connectionTimeoutMillis===void 0?this.connect_timeout=r.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(D.connectionTimeoutMillis/1000),D.keepAlive===!1?this.keepalives=0:D.keepAlive===!0&&(this.keepalives=1),typeof D.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(D.keepAliveInitialDelayMillis/1000))}getLibpqConnectionString(D){var S=[];V(S,this,"user"),V(S,this,"password"),V(S,this,"port"),V(S,this,"application_name"),V(S,this,"fallback_application_name"),V(S,this,"connect_timeout"),V(S,this,"options");var F=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(V(S,F,"sslmode"),V(S,F,"sslca"),V(S,F,"sslkey"),V(S,F,"sslcert"),V(S,F,"sslrootcert"),this.database&&S.push("dbname="+G(this.database)),this.replication&&S.push("replication="+G(this.replication)),this.host&&S.push("host="+G(this.host)),this.isDomainSocket)return D(null,S.join(" "));this.client_encoding&&S.push("client_encoding="+G(this.client_encoding)),Z.lookup(this.host,function(L,Q){return L?D(L,null):(S.push("hostaddr="+G(Q)),D(null,S.join(" ")))})}};U(R,"ConnectionParameters");var P=R;$.exports=P}),yZ=o((W,$)=>{u();var Z=B4(),J=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,X=class{constructor(G,V){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=V,this.RowCtor=null,this.rowAsArray=G==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray)}addCommandComplete(G){var V;G.text?V=J.exec(G.text):V=J.exec(G.command),V&&(this.command=V[1],V[3]?(this.oid=parseInt(V[2],10),this.rowCount=parseInt(V[3],10)):V[2]&&(this.rowCount=parseInt(V[2],10)))}_parseRowAsArray(G){for(var V=Array(G.length),R=0,P=G.length;R<P;R++){var w=G[R];w!==null?V[R]=this._parsers[R](w):V[R]=null}return V}parseRow(G){for(var V={},R=0,P=G.length;R<P;R++){var w=G[R],D=this.fields[R].name;w!==null?V[D]=this._parsers[R](w):V[D]=null}return V}addRow(G){this.rows.push(G)}addFields(G){this.fields=G,this.fields.length&&(this._parsers=Array(G.length));for(var V=0;V<G.length;V++){var R=G[V];this._types?this._parsers[V]=this._types.getTypeParser(R.dataTypeID,R.format||"text"):this._parsers[V]=Z.getTypeParser(R.dataTypeID,R.format||"text")}}};U(X,"Result");var Y=X;$.exports=Y}),gZ=o((W,$)=>{u();var{EventEmitter:Z}=S8(),J=yZ(),X=I4(),Y=class extends Z{constructor(V,R,P){super(),V=X.normalizeQueryConfig(V,R,P),this.text=V.text,this.values=V.values,this.rows=V.rows,this.types=V.types,this.name=V.name,this.binary=V.binary,this.portal=V.portal||"",this.callback=V.callback,this._rowMode=V.rowMode,r.domain&&V.callback&&(this.callback=r.domain.bind(V.callback)),this._result=new J(this._rowMode,this.types),this._results=this._result,this.isPreparedStatement=!1,this._canceledDueToError=!1,this._promise=null}requiresPreparation(){return this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new J(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(V){this._checkForMultirow(),this._result.addFields(V.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(V){let R;if(!this._canceledDueToError){try{R=this._result.parseRow(V.fields)}catch(P){this._canceledDueToError=P;return}this.emit("row",R,this._result),this._accumulateRows&&this._result.addRow(R)}}handleCommandComplete(V,R){this._checkForMultirow(),this._result.addCommandComplete(V),this.rows&&R.sync()}handleEmptyQuery(V){this.rows&&V.sync()}handleError(V,R){if(this._canceledDueToError&&(V=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(V);this.emit("error",V)}handleReadyForQuery(V){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,V);if(this.callback)try{this.callback(null,this._results)}catch(R){r.nextTick(()=>{throw R})}this.emit("end",this._results)}submit(V){if(typeof this.text!="string"&&typeof this.name!="string")return Error("A query must have either text or a name. Supplying neither is unsupported.");let R=V.parsedStatements[this.name];return this.text&&R&&this.text!==R?Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`):this.values&&!Array.isArray(this.values)?Error("Query values must be an array"):(this.requiresPreparation()?this.prepare(V):V.query(this.text),null)}hasBeenParsed(V){return this.name&&V.parsedStatements[this.name]}handlePortalSuspended(V){this._getRows(V,this.rows)}_getRows(V,R){V.execute({portal:this.portal,rows:R}),R?V.flush():V.sync()}prepare(V){this.isPreparedStatement=!0,this.hasBeenParsed(V)||V.parse({text:this.text,name:this.name,types:this.types});try{V.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:X.prepareValue})}catch(R){this.handleError(R,V);return}V.describe({type:"P",name:this.portal||""}),this._getRows(V,this.rows)}handleCopyInResponse(V){V.sendCopyFail("No source stream defined")}handleCopyData(V,R){}};U(Y,"Query");var M=Y;$.exports=M}),m7=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.NoticeMessage=W.DataRowMessage=W.CommandCompleteMessage=W.ReadyForQueryMessage=W.NotificationResponseMessage=W.BackendKeyDataMessage=W.AuthenticationMD5Password=W.ParameterStatusMessage=W.ParameterDescriptionMessage=W.RowDescriptionMessage=W.Field=W.CopyResponse=W.CopyDataMessage=W.DatabaseError=W.copyDone=W.emptyQuery=W.replicationStart=W.portalSuspended=W.noData=W.closeComplete=W.bindComplete=W.parseComplete=void 0,W.parseComplete={name:"parseComplete",length:5},W.bindComplete={name:"bindComplete",length:5},W.closeComplete={name:"closeComplete",length:5},W.noData={name:"noData",length:5},W.portalSuspended={name:"portalSuspended",length:5},W.replicationStart={name:"replicationStart",length:4},W.emptyQuery={name:"emptyQuery",length:4},W.copyDone={name:"copyDone",length:4};var $=class extends Error{constructor(b,g,p){super(b),this.length=g,this.name=p}};U($,"DatabaseError");var Z=$;W.DatabaseError=Z;var J=class{constructor(b,g){this.length=b,this.chunk=g,this.name="copyData"}};U(J,"CopyDataMessage");var X=J;W.CopyDataMessage=X;var Y=class{constructor(b,g,p,d){this.length=b,this.name=g,this.binary=p,this.columnTypes=Array(d)}};U(Y,"CopyResponse");var M=Y;W.CopyResponse=M;var G=class{constructor(b,g,p,d,J1,s,s1){this.name=b,this.tableID=g,this.columnID=p,this.dataTypeID=d,this.dataTypeSize=J1,this.dataTypeModifier=s,this.format=s1}};U(G,"Field");var V=G;W.Field=V;var R=class{constructor(b,g){this.length=b,this.fieldCount=g,this.name="rowDescription",this.fields=Array(this.fieldCount)}};U(R,"RowDescriptionMessage");var P=R;W.RowDescriptionMessage=P;var w=class{constructor(b,g){this.length=b,this.parameterCount=g,this.name="parameterDescription",this.dataTypeIDs=Array(this.parameterCount)}};U(w,"ParameterDescriptionMessage");var D=w;W.ParameterDescriptionMessage=D;var S=class{constructor(b,g,p){this.length=b,this.parameterName=g,this.parameterValue=p,this.name="parameterStatus"}};U(S,"ParameterStatusMessage");var F=S;W.ParameterStatusMessage=F;var L=class{constructor(b,g){this.length=b,this.salt=g,this.name="authenticationMD5Password"}};U(L,"AuthenticationMD5Password");var Q=L;W.AuthenticationMD5Password=Q;var _=class{constructor(b,g,p){this.length=b,this.processID=g,this.secretKey=p,this.name="backendKeyData"}};U(_,"BackendKeyDataMessage");var v=_;W.BackendKeyDataMessage=v;var T=class{constructor(b,g,p,d){this.length=b,this.processId=g,this.channel=p,this.payload=d,this.name="notification"}};U(T,"NotificationResponseMessage");var x=T;W.NotificationResponseMessage=x;var q=class{constructor(b,g){this.length=b,this.status=g,this.name="readyForQuery"}};U(q,"ReadyForQueryMessage");var E=q;W.ReadyForQueryMessage=E;var N=class{constructor(b,g){this.length=b,this.text=g,this.name="commandComplete"}};U(N,"CommandCompleteMessage");var A=N;W.CommandCompleteMessage=A;var f=class{constructor(b,g){this.length=b,this.fields=g,this.name="dataRow",this.fieldCount=g.length}};U(f,"DataRowMessage");var B=f;W.DataRowMessage=B;var C=class{constructor(b,g){this.length=b,this.message=g,this.name="notice"}};U(C,"NoticeMessage");var c=C;W.NoticeMessage=c}),mZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.Writer=void 0;var $=class{constructor(X=256){this.size=X,this.offset=5,this.headerPosition=0,this.buffer=i.allocUnsafe(X)}ensure(X){if(this.buffer.length-this.offset<X){let Y=this.buffer,M=Y.length+(Y.length>>1)+X;this.buffer=i.allocUnsafe(M),Y.copy(this.buffer)}}addInt32(X){return this.ensure(4),this.buffer[this.offset++]=X>>>24&255,this.buffer[this.offset++]=X>>>16&255,this.buffer[this.offset++]=X>>>8&255,this.buffer[this.offset++]=X>>>0&255,this}addInt16(X){return this.ensure(2),this.buffer[this.offset++]=X>>>8&255,this.buffer[this.offset++]=X>>>0&255,this}addCString(X){if(!X)this.ensure(1);else{let Y=i.byteLength(X);this.ensure(Y+1),this.buffer.write(X,this.offset,"utf-8"),this.offset+=Y}return this.buffer[this.offset++]=0,this}addString(X=""){let Y=i.byteLength(X);return this.ensure(Y),this.buffer.write(X,this.offset),this.offset+=Y,this}add(X){return this.ensure(X.length),X.copy(this.buffer,this.offset),this.offset+=X.length,this}join(X){if(X){this.buffer[this.headerPosition]=X;let Y=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(Y,this.headerPosition+1)}return this.buffer.slice(X?0:5,this.offset)}flush(X){let Y=this.join(X);return this.offset=5,this.headerPosition=0,this.buffer=i.allocUnsafe(this.size),Y}};U($,"Writer");var Z=$;W.Writer=Z}),cZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.serialize=void 0;var $=mZ(),Z=new $.Writer,J=U((b)=>{Z.addInt16(3).addInt16(0);for(let d of Object.keys(b))Z.addCString(d).addCString(b[d]);Z.addCString("client_encoding").addCString("UTF8");let g=Z.addCString("").flush(),p=g.length+4;return new $.Writer().addInt32(p).add(g).flush()},"startup"),X=U(()=>{let b=i.allocUnsafe(8);return b.writeInt32BE(8,0),b.writeInt32BE(80877103,4),b},"requestSsl"),Y=U((b)=>Z.addCString(b).flush(112),"password"),M=U(function(b,g){return Z.addCString(b).addInt32(i.byteLength(g)).addString(g),Z.flush(112)},"sendSASLInitialResponseMessage"),G=U(function(b){return Z.addString(b).flush(112)},"sendSCRAMClientFinalMessage"),V=U((b)=>Z.addCString(b).flush(81),"query"),R=[],P=U((b)=>{let g=b.name||"";g.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",g,g.length),console.error("This can cause conflicts and silent errors executing queries"));let p=b.types||R,d=p.length,J1=Z.addCString(g).addCString(b.text).addInt16(d);for(let s=0;s<d;s++)J1.addInt32(p[s]);return Z.flush(80)},"parse"),w=new $.Writer,D=U(function(b,g){for(let p=0;p<b.length;p++){let d=g?g(b[p],p):b[p];d==null?(Z.addInt16(0),w.addInt32(-1)):d instanceof i?(Z.addInt16(1),w.addInt32(d.length),w.add(d)):(Z.addInt16(0),w.addInt32(i.byteLength(d)),w.addString(d))}},"writeValues"),S=U((b={})=>{let g=b.portal||"",p=b.statement||"",d=b.binary||!1,J1=b.values||R,s=J1.length;return Z.addCString(g).addCString(p),Z.addInt16(s),D(J1,b.valueMapper),Z.addInt16(s),Z.add(w.flush()),Z.addInt16(d?1:0),Z.flush(66)},"bind"),F=i.from([69,0,0,0,9,0,0,0,0,0]),L=U((b)=>{if(!b||!b.portal&&!b.rows)return F;let g=b.portal||"",p=b.rows||0,d=i.byteLength(g),J1=4+d+1+4,s=i.allocUnsafe(1+J1);return s[0]=69,s.writeInt32BE(J1,1),s.write(g,5,"utf-8"),s[d+5]=0,s.writeUInt32BE(p,s.length-4),s},"execute"),Q=U((b,g)=>{let p=i.allocUnsafe(16);return p.writeInt32BE(16,0),p.writeInt16BE(1234,4),p.writeInt16BE(5678,6),p.writeInt32BE(b,8),p.writeInt32BE(g,12),p},"cancel"),_=U((b,g)=>{let p=4+i.byteLength(g)+1,d=i.allocUnsafe(1+p);return d[0]=b,d.writeInt32BE(p,1),d.write(g,5,"utf-8"),d[p]=0,d},"cstringMessage"),v=Z.addCString("P").flush(68),T=Z.addCString("S").flush(68),x=U((b)=>b.name?_(68,`${b.type}${b.name||""}`):b.type==="P"?v:T,"describe"),q=U((b)=>{let g=`${b.type}${b.name||""}`;return _(67,g)},"close"),E=U((b)=>Z.add(b).flush(100),"copyData"),N=U((b)=>_(102,b),"copyFail"),A=U((b)=>i.from([b,0,0,0,4]),"codeOnlyBuffer"),f=A(72),B=A(83),C=A(88),c=A(99),m={startup:J,password:Y,requestSsl:X,sendSASLInitialResponseMessage:M,sendSCRAMClientFinalMessage:G,query:V,parse:P,bind:S,execute:L,describe:x,close:q,flush:U(()=>f,"flush"),sync:U(()=>B,"sync"),end:U(()=>C,"end"),copyData:E,copyDone:U(()=>c,"copyDone"),copyFail:N,cancel:Q};W.serialize=m}),uZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.BufferReader=void 0;var $=i.allocUnsafe(0),Z=class{constructor(Y=0){this.offset=Y,this.buffer=$,this.encoding="utf-8"}setBuffer(Y,M){this.offset=Y,this.buffer=M}int16(){let Y=this.buffer.readInt16BE(this.offset);return this.offset+=2,Y}byte(){let Y=this.buffer[this.offset];return this.offset++,Y}int32(){let Y=this.buffer.readInt32BE(this.offset);return this.offset+=4,Y}uint32(){let Y=this.buffer.readUInt32BE(this.offset);return this.offset+=4,Y}string(Y){let M=this.buffer.toString(this.encoding,this.offset,this.offset+Y);return this.offset+=Y,M}cstring(){let Y=this.offset,M=Y;for(;this.buffer[M++]!==0;);return this.offset=M,this.buffer.toString(this.encoding,Y,M-1)}bytes(Y){let M=this.buffer.slice(this.offset,this.offset+Y);return this.offset+=Y,M}};U(Z,"BufferReader");var J=Z;W.BufferReader=J}),lZ=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.Parser=void 0;var $=m7(),Z=uZ(),J=1,X=4,Y=J+X,M=i.allocUnsafe(0),G=class{constructor(P){if(this.buffer=M,this.bufferLength=0,this.bufferOffset=0,this.reader=new Z.BufferReader,P?.mode==="binary")throw Error("Binary mode not supported yet");this.mode=P?.mode||"text"}parse(P,w){this.mergeBuffer(P);let D=this.bufferOffset+this.bufferLength,S=this.bufferOffset;for(;S+Y<=D;){let F=this.buffer[S],L=this.buffer.readUInt32BE(S+J),Q=J+L;if(Q+S<=D){let _=this.handlePacket(S+Y,F,L,this.buffer);w(_),S+=Q}else break}S===D?(this.buffer=M,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=D-S,this.bufferOffset=S)}mergeBuffer(P){if(this.bufferLength>0){let w=this.bufferLength+P.byteLength;if(w+this.bufferOffset>this.buffer.byteLength){let D;if(w<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)D=this.buffer;else{let S=this.buffer.byteLength*2;for(;w>=S;)S*=2;D=i.allocUnsafe(S)}this.buffer.copy(D,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=D,this.bufferOffset=0}P.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=w}else this.buffer=P,this.bufferOffset=0,this.bufferLength=P.byteLength}handlePacket(P,w,D,S){switch(w){case 50:return $.bindComplete;case 49:return $.parseComplete;case 51:return $.closeComplete;case 110:return $.noData;case 115:return $.portalSuspended;case 99:return $.copyDone;case 87:return $.replicationStart;case 73:return $.emptyQuery;case 68:return this.parseDataRowMessage(P,D,S);case 67:return this.parseCommandCompleteMessage(P,D,S);case 90:return this.parseReadyForQueryMessage(P,D,S);case 65:return this.parseNotificationMessage(P,D,S);case 82:return this.parseAuthenticationResponse(P,D,S);case 83:return this.parseParameterStatusMessage(P,D,S);case 75:return this.parseBackendKeyData(P,D,S);case 69:return this.parseErrorMessage(P,D,S,"error");case 78:return this.parseErrorMessage(P,D,S,"notice");case 84:return this.parseRowDescriptionMessage(P,D,S);case 116:return this.parseParameterDescriptionMessage(P,D,S);case 71:return this.parseCopyInMessage(P,D,S);case 72:return this.parseCopyOutMessage(P,D,S);case 100:return this.parseCopyData(P,D,S);default:return new $.DatabaseError("received invalid response: "+w.toString(16),D,"error")}}parseReadyForQueryMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.string(1);return new $.ReadyForQueryMessage(w,S)}parseCommandCompleteMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.cstring();return new $.CommandCompleteMessage(w,S)}parseCopyData(P,w,D){let S=D.slice(P,P+(w-4));return new $.CopyDataMessage(w,S)}parseCopyInMessage(P,w,D){return this.parseCopyMessage(P,w,D,"copyInResponse")}parseCopyOutMessage(P,w,D){return this.parseCopyMessage(P,w,D,"copyOutResponse")}parseCopyMessage(P,w,D,S){this.reader.setBuffer(P,D);let F=this.reader.byte()!==0,L=this.reader.int16(),Q=new $.CopyResponse(w,S,F,L);for(let _=0;_<L;_++)Q.columnTypes[_]=this.reader.int16();return Q}parseNotificationMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int32(),F=this.reader.cstring(),L=this.reader.cstring();return new $.NotificationResponseMessage(w,S,F,L)}parseRowDescriptionMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int16(),F=new $.RowDescriptionMessage(w,S);for(let L=0;L<S;L++)F.fields[L]=this.parseField();return F}parseField(){let P=this.reader.cstring(),w=this.reader.uint32(),D=this.reader.int16(),S=this.reader.uint32(),F=this.reader.int16(),L=this.reader.int32(),Q=this.reader.int16()===0?"text":"binary";return new $.Field(P,w,D,S,F,L,Q)}parseParameterDescriptionMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int16(),F=new $.ParameterDescriptionMessage(w,S);for(let L=0;L<S;L++)F.dataTypeIDs[L]=this.reader.int32();return F}parseDataRowMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int16(),F=Array(S);for(let L=0;L<S;L++){let Q=this.reader.int32();F[L]=Q===-1?null:this.reader.string(Q)}return new $.DataRowMessage(w,F)}parseParameterStatusMessage(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.cstring(),F=this.reader.cstring();return new $.ParameterStatusMessage(w,S,F)}parseBackendKeyData(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int32(),F=this.reader.int32();return new $.BackendKeyDataMessage(w,S,F)}parseAuthenticationResponse(P,w,D){this.reader.setBuffer(P,D);let S=this.reader.int32(),F={name:"authenticationOk",length:w};switch(S){case 0:break;case 3:F.length===8&&(F.name="authenticationCleartextPassword");break;case 5:if(F.length===12){F.name="authenticationMD5Password";let L=this.reader.bytes(4);return new $.AuthenticationMD5Password(w,L)}break;case 10:{F.name="authenticationSASL",F.mechanisms=[];let L;do L=this.reader.cstring(),L&&F.mechanisms.push(L);while(L)}break;case 11:F.name="authenticationSASLContinue",F.data=this.reader.string(w-8);break;case 12:F.name="authenticationSASLFinal",F.data=this.reader.string(w-8);break;default:throw Error("Unknown authenticationOk message type "+S)}return F}parseErrorMessage(P,w,D,S){this.reader.setBuffer(P,D);let F={},L=this.reader.string(1);for(;L!=="\x00";)F[L]=this.reader.cstring(),L=this.reader.string(1);let Q=F.M,_=S==="notice"?new $.NoticeMessage(w,Q):new $.DatabaseError(Q,w,S);return _.severity=F.S,_.code=F.C,_.detail=F.D,_.hint=F.H,_.position=F.P,_.internalPosition=F.p,_.internalQuery=F.q,_.where=F.W,_.schema=F.s,_.table=F.t,_.column=F.c,_.dataType=F.d,_.constraint=F.n,_.file=F.F,_.line=F.L,_.routine=F.R,_}};U(G,"Parser");var V=G;W.Parser=V}),c7=o((W)=>{u(),Object.defineProperty(W,"__esModule",{value:!0}),W.DatabaseError=W.serialize=W.parse=void 0;var $=m7();Object.defineProperty(W,"DatabaseError",{enumerable:!0,get:U(function(){return $.DatabaseError},"get")});var Z=cZ();Object.defineProperty(W,"serialize",{enumerable:!0,get:U(function(){return Z.serialize},"get")});var J=lZ();function X(Y,M){let G=new J.Parser;return Y.on("data",(V)=>G.parse(V,M)),new Promise((V)=>Y.on("end",()=>V()))}U(X,"parse"),W.parse=X}),u7={};S0(u7,{connect:()=>l7});function l7({socket:W,servername:$}){return W.startTls($),W}var pZ=d1(()=>{u(),U(l7,"connect")}),p7=o((W,$)=>{u();var Z=(tW(),B1(w7)),J=S8().EventEmitter,{parse:X,serialize:Y}=c7(),M=Y.flush(),G=Y.sync(),V=Y.end(),R=class extends J{constructor(D){super(),D=D||{},this.stream=D.stream||new Z.Socket,this._keepAlive=D.keepAlive,this._keepAliveInitialDelayMillis=D.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=D.ssl||!1,this._ending=!1,this._emitMessage=!1;var S=this;this.on("newListener",function(F){F==="message"&&(S._emitMessage=!0)})}connect(D,S){var F=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(D,S),this.stream.once("connect",function(){F._keepAlive&&F.stream.setKeepAlive(!0,F._keepAliveInitialDelayMillis),F.emit("connect")});let L=U(function(Q){F._ending&&(Q.code==="ECONNRESET"||Q.code==="EPIPE")||F.emit("error",Q)},"reportStreamError");if(this.stream.on("error",L),this.stream.on("close",function(){F.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(Q){var _=Q.toString("utf8");switch(_){case"S":break;case"N":return F.stream.end(),F.emit("error",Error("The server does not support SSL connections"));default:return F.stream.end(),F.emit("error",Error("There was an error establishing an SSL connection"))}var v=(pZ(),B1(u7));let T={socket:F.stream};F.ssl!==!0&&(Object.assign(T,F.ssl),("key"in F.ssl)&&(T.key=F.ssl.key)),Z.isIP(S)===0&&(T.servername=S);try{F.stream=v.connect(T)}catch(x){return F.emit("error",x)}F.attachListeners(F.stream),F.stream.on("error",L),F.emit("sslconnect")})}attachListeners(D){D.on("end",()=>{this.emit("end")}),X(D,(S)=>{var F=S.name==="error"?"errorMessage":S.name;this._emitMessage&&this.emit("message",S),this.emit(F,S)})}requestSsl(){this.stream.write(Y.requestSsl())}startup(D){this.stream.write(Y.startup(D))}cancel(D,S){this._send(Y.cancel(D,S))}password(D){this._send(Y.password(D))}sendSASLInitialResponseMessage(D,S){this._send(Y.sendSASLInitialResponseMessage(D,S))}sendSCRAMClientFinalMessage(D){this._send(Y.sendSCRAMClientFinalMessage(D))}_send(D){return this.stream.writable?this.stream.write(D):!1}query(D){this._send(Y.query(D))}parse(D){this._send(Y.parse(D))}bind(D){this._send(Y.bind(D))}execute(D){this._send(Y.execute(D))}flush(){this.stream.writable&&this.stream.write(M)}sync(){this._ending=!0,this._send(M),this._send(G)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(V,()=>{this.stream.end()})}close(D){this._send(Y.close(D))}describe(D){this._send(Y.describe(D))}sendCopyFromChunk(D){this._send(Y.copyData(D))}endCopyFrom(){this._send(Y.copyDone())}sendCopyFail(D){this._send(Y.copyFail(D))}};U(R,"Connection");var P=R;$.exports=P}),iZ=o((W,$)=>{u();var Z=S8().EventEmitter,J=(y4(),B1(aW)),X=I4(),Y=CZ(),M=BZ(),G=K9(),V=F9(),R=gZ(),P=b4(),w=p7(),D=class extends Z{constructor(L){super(),this.connectionParameters=new V(L),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var Q=L||{};this._Promise=Q.Promise||x4.Promise,this._types=new G(Q.types),this._ending=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=Q.connection||new w({stream:Q.stream,ssl:this.connectionParameters.ssl,keepAlive:Q.keepAlive||!1,keepAliveInitialDelayMillis:Q.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=Q.binary||P.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=Q.connectionTimeoutMillis||0}_errorAllQueries(L){let Q=U((_)=>{r.nextTick(()=>{_.handleError(L,this.connection)})},"enqueueError");this.activeQuery&&(Q(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(Q),this.queryQueue.length=0}_connect(L){var Q=this,_=this.connection;if(this._connectionCallback=L,this._connecting||this._connected){let v=Error("Client has already been connected. You cannot reuse a client.");r.nextTick(()=>{L(v)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{_._ending=!0,_.stream.destroy(Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?_.connect(this.host+"/.s.PGSQL."+this.port):_.connect(this.port,this.host),_.on("connect",function(){Q.ssl?_.requestSsl():_.startup(Q.getStartupConf())}),_.on("sslconnect",function(){_.startup(Q.getStartupConf())}),this._attachListeners(_),_.once("end",()=>{let v=this._ending?Error("Connection terminated"):Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(v),this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(v):this._handleErrorEvent(v):this._connectionError||this._handleErrorEvent(v)),r.nextTick(()=>{this.emit("end")})})}connect(L){if(L){this._connect(L);return}return new this._Promise((Q,_)=>{this._connect((v)=>{v?_(v):Q()})})}_attachListeners(L){L.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),L.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),L.on("authenticationSASL",this._handleAuthSASL.bind(this)),L.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),L.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),L.on("backendKeyData",this._handleBackendKeyData.bind(this)),L.on("error",this._handleErrorEvent.bind(this)),L.on("errorMessage",this._handleErrorMessage.bind(this)),L.on("readyForQuery",this._handleReadyForQuery.bind(this)),L.on("notice",this._handleNotice.bind(this)),L.on("rowDescription",this._handleRowDescription.bind(this)),L.on("dataRow",this._handleDataRow.bind(this)),L.on("portalSuspended",this._handlePortalSuspended.bind(this)),L.on("emptyQuery",this._handleEmptyQuery.bind(this)),L.on("commandComplete",this._handleCommandComplete.bind(this)),L.on("parseComplete",this._handleParseComplete.bind(this)),L.on("copyInResponse",this._handleCopyInResponse.bind(this)),L.on("copyData",this._handleCopyData.bind(this)),L.on("notification",this._handleNotification.bind(this))}_checkPgPass(L){let Q=this.connection;typeof this.password=="function"?this._Promise.resolve().then(()=>this.password()).then((_)=>{if(_!==void 0){if(typeof _!="string"){Q.emit("error",TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=_}else this.connectionParameters.password=this.password=null;L()}).catch((_)=>{Q.emit("error",_)}):this.password!==null?L():M(this.connectionParameters,(_)=>{_!==void 0&&(this.connectionParameters.password=this.password=_),L()})}_handleAuthCleartextPassword(L){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(L){this._checkPgPass(()=>{let Q=X.postgresMd5PasswordHash(this.user,this.password,L.salt);this.connection.password(Q)})}_handleAuthSASL(L){this._checkPgPass(()=>{this.saslSession=Y.startSession(L.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)})}_handleAuthSASLContinue(L){Y.continueSession(this.saslSession,this.password,L.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}_handleAuthSASLFinal(L){Y.finalizeSession(this.saslSession,L.data),this.saslSession=null}_handleBackendKeyData(L){this.processID=L.processID,this.secretKey=L.secretKey}_handleReadyForQuery(L){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:Q}=this;this.activeQuery=null,this.readyForQuery=!0,Q&&Q.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(L){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(L);this.emit("error",L)}}_handleErrorEvent(L){if(this._connecting)return this._handleErrorWhileConnecting(L);this._queryable=!1,this._errorAllQueries(L),this.emit("error",L)}_handleErrorMessage(L){if(this._connecting)return this._handleErrorWhileConnecting(L);let Q=this.activeQuery;if(!Q){this._handleErrorEvent(L);return}this.activeQuery=null,Q.handleError(L,this.connection)}_handleRowDescription(L){this.activeQuery.handleRowDescription(L)}_handleDataRow(L){this.activeQuery.handleDataRow(L)}_handlePortalSuspended(L){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(L){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(L){this.activeQuery.handleCommandComplete(L,this.connection)}_handleParseComplete(L){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(L){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(L){this.activeQuery.handleCopyData(L,this.connection)}_handleNotification(L){this.emit("notification",L)}_handleNotice(L){this.emit("notice",L)}getStartupConf(){var L=this.connectionParameters,Q={user:L.user,database:L.database},_=L.application_name||L.fallback_application_name;return _&&(Q.application_name=_),L.replication&&(Q.replication=""+L.replication),L.statement_timeout&&(Q.statement_timeout=String(parseInt(L.statement_timeout,10))),L.lock_timeout&&(Q.lock_timeout=String(parseInt(L.lock_timeout,10))),L.idle_in_transaction_session_timeout&&(Q.idle_in_transaction_session_timeout=String(parseInt(L.idle_in_transaction_session_timeout,10))),L.options&&(Q.options=L.options),Q}cancel(L,Q){if(L.activeQuery===Q){var _=this.connection;this.host&&this.host.indexOf("/")===0?_.connect(this.host+"/.s.PGSQL."+this.port):_.connect(this.port,this.host),_.on("connect",function(){_.cancel(L.processID,L.secretKey)})}else L.queryQueue.indexOf(Q)!==-1&&L.queryQueue.splice(L.queryQueue.indexOf(Q),1)}setTypeParser(L,Q,_){return this._types.setTypeParser(L,Q,_)}getTypeParser(L,Q){return this._types.getTypeParser(L,Q)}escapeIdentifier(L){return'"'+L.replace(/"/g,'""')+'"'}escapeLiteral(L){for(var Q=!1,_="'",v=0;v<L.length;v++){var T=L[v];T==="'"?_+=T+T:T==="\\"?(_+=T+T,Q=!0):_+=T}return _+="'",Q===!0&&(_=" E"+_),_}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let L=this.activeQuery.submit(this.connection);L&&r.nextTick(()=>{this.activeQuery.handleError(L,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(L,Q,_){var v,T,x,q,E;if(L==null)throw TypeError("Client was passed a null or undefined query");return typeof L.submit=="function"?(x=L.query_timeout||this.connectionParameters.query_timeout,T=v=L,typeof Q=="function"&&(v.callback=v.callback||Q)):(x=this.connectionParameters.query_timeout,v=new R(L,Q,_),v.callback||(T=new this._Promise((N,A)=>{v.callback=(f,B)=>f?A(f):N(B)}))),x&&(E=v.callback,q=setTimeout(()=>{var N=Error("Query read timeout");r.nextTick(()=>{v.handleError(N,this.connection)}),E(N),v.callback=()=>{};var A=this.queryQueue.indexOf(v);A>-1&&this.queryQueue.splice(A,1),this._pulseQueryQueue()},x),v.callback=(N,A)=>{clearTimeout(q),E(N,A)}),this.binary&&!v.binary&&(v.binary=!0),v._result&&!v._result._types&&(v._result._types=this._types),this._queryable?this._ending?(r.nextTick(()=>{v.handleError(Error("Client was closed and is not queryable"),this.connection)}),T):(this.queryQueue.push(v),this._pulseQueryQueue(),T):(r.nextTick(()=>{v.handleError(Error("Client has encountered a connection error and is not queryable"),this.connection)}),T)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(L){if(this._ending=!0,!this.connection._connecting)if(L)L();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),L)this.connection.once("end",L);else return new this._Promise((Q)=>{this.connection.once("end",Q)})}};U(D,"Client");var S=D;S.Query=R,$.exports=S}),tZ=o((W,$)=>{u();var Z=S8().EventEmitter,J=U(function(){},"NOOP"),X=U((F,L)=>{let Q=F.findIndex(L);return Q===-1?void 0:F.splice(Q,1)[0]},"removeWhere"),Y=class{constructor(L,Q,_){this.client=L,this.idleListener=Q,this.timeoutId=_}};U(Y,"IdleItem");var M=Y,G=class{constructor(L){this.callback=L}};U(G,"PendingItem");var V=G;function R(){throw Error("Release called on client which has already been released to the pool.")}U(R,"throwOnDoubleRelease");function P(F,L){if(L)return{callback:L,result:void 0};let Q,_,v=U(function(x,q){x?Q(x):_(q)},"cb"),T=new F(function(x,q){_=x,Q=q}).catch((x)=>{throw Error.captureStackTrace(x),x});return{callback:v,result:T}}U(P,"promisify");function w(F,L){return U(function Q(_){_.client=L,L.removeListener("error",Q),L.on("error",()=>{F.log("additional client error after disconnection due to error",_)}),F._remove(L),F.emit("error",_,L)},"idleListener")}U(w,"makeIdleListener");var D=class extends Z{constructor(L,Q){super(),this.options=Object.assign({},L),L!=null&&"password"in L&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:L.password}),L!=null&&L.ssl&&L.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||Q||g4().Client,this.Promise=this.options.Promise||x4.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map((Q)=>{this._remove(Q.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let L=this._pendingQueue.shift();if(this._idle.length){let Q=this._idle.pop();clearTimeout(Q.timeoutId);let _=Q.client;_.ref&&_.ref();let v=Q.idleListener;return this._acquireClient(_,L,v,!1)}if(!this._isFull())return this.newClient(L);throw Error("unexpected condition")}_remove(L){let Q=X(this._idle,(_)=>_.client===L);Q!==void 0&&clearTimeout(Q.timeoutId),this._clients=this._clients.filter((_)=>_!==L),L.end(),this.emit("remove",L)}connect(L){if(this.ending){let v=Error("Cannot use a pool after calling end on the pool");return L?L(v):this.Promise.reject(v)}let Q=P(this.Promise,L),_=Q.result;if(this._isFull()||this._idle.length){if(this._idle.length&&r.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new V(Q.callback)),_;let v=U((q,E,N)=>{clearTimeout(x),Q.callback(q,E,N)},"queueCallback"),T=new V(v),x=setTimeout(()=>{X(this._pendingQueue,(q)=>q.callback===v),T.timedOut=!0,Q.callback(Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return x.unref&&x.unref(),this._pendingQueue.push(T),_}return this.newClient(new V(Q.callback)),_}newClient(L){let Q=new this.Client(this.options);this._clients.push(Q);let _=w(this,Q);this.log("checking client timeout");let v,T=!1;this.options.connectionTimeoutMillis&&(v=setTimeout(()=>{this.log("ending client due to timeout"),T=!0,Q.connection?Q.connection.stream.destroy():Q.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),Q.connect((x)=>{if(v&&clearTimeout(v),Q.on("error",_),x)this.log("client failed to connect",x),this._clients=this._clients.filter((q)=>q!==Q),T&&(x=Error("Connection terminated due to connection timeout",{cause:x})),this._pulseQueue(),L.timedOut||L.callback(x,void 0,J);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let q=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(Q),this._idle.findIndex((E)=>E.client===Q)!==-1&&this._acquireClient(Q,new V((E,N,A)=>A()),_,!1)},this.options.maxLifetimeSeconds*1000);q.unref(),Q.once("end",()=>clearTimeout(q))}return this._acquireClient(Q,L,_,!0)}})}_acquireClient(L,Q,_,v){v&&this.emit("connect",L),this.emit("acquire",L),L.release=this._releaseOnce(L,_),L.removeListener("error",_),Q.timedOut?v&&this.options.verify?this.options.verify(L,L.release):L.release():v&&this.options.verify?this.options.verify(L,(T)=>{if(T)return L.release(T),Q.callback(T,void 0,J);Q.callback(void 0,L,L.release)}):Q.callback(void 0,L,L.release)}_releaseOnce(L,Q){let _=!1;return(v)=>{_&&R(),_=!0,this._release(L,Q,v)}}_release(L,Q,_){if(L.on("error",Q),L._poolUseCount=(L._poolUseCount||0)+1,this.emit("release",_,L),_||this.ending||!L._queryable||L._ending||L._poolUseCount>=this.options.maxUses){L._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(L),this._pulseQueue();return}if(this._expired.has(L)){this.log("remove expired client"),this._expired.delete(L),this._remove(L),this._pulseQueue();return}let v;this.options.idleTimeoutMillis&&this._isAboveMin()&&(v=setTimeout(()=>{this.log("remove idle client"),this._remove(L)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&v.unref()),this.options.allowExitOnIdle&&L.unref(),this._idle.push(new M(L,Q,v)),this._pulseQueue()}query(L,Q,_){if(typeof L=="function"){let T=P(this.Promise,L);return M9(function(){return T.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),T.result}typeof Q=="function"&&(_=Q,Q=void 0);let v=P(this.Promise,_);return _=v.callback,this.connect((T,x)=>{if(T)return _(T);let q=!1,E=U((N)=>{q||(q=!0,x.release(N),_(N))},"onError");x.once("error",E),this.log("dispatching query");try{x.query(L,Q,(N,A)=>{if(this.log("query dispatched"),x.removeListener("error",E),!q)return q=!0,x.release(N),N?_(N):_(void 0,A)})}catch(N){return x.release(N),_(N)}}),v.result}end(L){if(this.log("ending"),this.ending){let _=Error("Called end on pool more than once");return L?L(_):this.Promise.reject(_)}this.ending=!0;let Q=P(this.Promise,L);return this._endCallback=Q.callback,this._pulseQueue(),Q.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((L,Q)=>L+(this._expired.has(Q)?1:0),0)}get totalCount(){return this._clients.length}};U(D,"Pool");var S=D;$.exports=S}),i7={};S0(i7,{default:()=>t7});var t7,aZ=d1(()=>{u(),t7={}}),dZ=o((W,$)=>{$.exports={name:"pg",version:"8.8.0",description:"PostgreSQL client - pure javascript & libpq with the same API",keywords:["database","libpq","pg","postgre","postgres","postgresql","rdbms"],homepage:"https://github.com/brianc/node-postgres",repository:{type:"git",url:"git://github.com/brianc/node-postgres.git",directory:"packages/pg"},author:"Brian Carlson <brian.m.carlson@gmail.com>",main:"./lib",dependencies:{"buffer-writer":"2.0.0","packet-reader":"1.0.0","pg-connection-string":"^2.5.0","pg-pool":"^3.5.2","pg-protocol":"^1.5.0","pg-types":"^2.1.0",pgpass:"1.x"},devDependencies:{async:"2.6.4",bluebird:"3.5.2",co:"4.6.0","pg-copy-streams":"0.3.0"},peerDependencies:{"pg-native":">=3.0.1"},peerDependenciesMeta:{"pg-native":{optional:!0}},scripts:{test:"make test-all"},files:["lib","SPONSORS.md"],license:"MIT",engines:{node:">= 8.0.0"},gitHead:"c99fb2c127ddf8d712500db2c7b9a5491a178655"}}),sZ=o((W,$)=>{u();var Z=S8().EventEmitter,J=(y4(),B1(aW)),X=I4(),Y=$.exports=function(G,V,R){Z.call(this),G=X.normalizeQueryConfig(G,V,R),this.text=G.text,this.values=G.values,this.name=G.name,this.callback=G.callback,this.state="new",this._arrayMode=G.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(P){P==="row"&&(this._emitRowEvents=!0)}.bind(this))};J.inherits(Y,Z);var M={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};Y.prototype.handleError=function(G){var V=this.native.pq.resultErrorFields();if(V)for(var R in V){var P=M[R]||R;G[P]=V[R]}this.callback?this.callback(G):this.emit("error",G),this.state="error"},Y.prototype.then=function(G,V){return this._getPromise().then(G,V)},Y.prototype.catch=function(G){return this._getPromise().catch(G)},Y.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(G,V){this._once("end",G),this._once("error",V)}.bind(this)),this._promise)},Y.prototype.submit=function(G){this.state="running";var V=this;this.native=G.native,G.native.arrayMode=this._arrayMode;var R=U(function(D,S,F){if(G.native.arrayMode=!1,M9(function(){V.emit("_done")}),D)return V.handleError(D);V._emitRowEvents&&(F.length>1?S.forEach((L,Q)=>{L.forEach((_)=>{V.emit("row",_,F[Q])})}):S.forEach(function(L){V.emit("row",L,F)})),V.state="end",V.emit("end",F),V.callback&&V.callback(null,F)},"after");if(r.domain&&(R=r.domain.bind(R)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var P=(this.values||[]).map(X.prepareValue);if(G.namedQueries[this.name]){if(this.text&&G.namedQueries[this.name]!==this.text){let D=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return R(D)}return G.native.execute(this.name,P,R)}return G.native.prepare(this.name,this.text,P.length,function(D){return D?R(D):(G.namedQueries[V.name]=V.text,V.native.execute(V.name,P,R))})}else if(this.values){if(!Array.isArray(this.values)){let D=Error("Query values must be an array");return R(D)}var w=this.values.map(X.prepareValue);G.native.query(this.text,w,R)}else G.native.query(this.text,R)}}),nZ=o((W,$)=>{u();var Z=(aZ(),B1(i7)),J=K9(),X=dZ(),Y=S8().EventEmitter,M=(y4(),B1(aW)),G=F9(),V=sZ(),R=$.exports=function(P){Y.call(this),P=P||{},this._Promise=P.Promise||x4.Promise,this._types=new J(P.types),this.native=new Z({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var w=this.connectionParameters=new G(P);this.user=w.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:w.password}),this.database=w.database,this.host=w.host,this.port=w.port,this.namedQueries={}};R.Query=V,M.inherits(R,Y),R.prototype._errorAllQueries=function(P){let w=U((D)=>{r.nextTick(()=>{D.native=this.native,D.handleError(P)})},"enqueueError");this._hasActiveQuery()&&(w(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(w),this._queryQueue.length=0},R.prototype._connect=function(P){var w=this;if(this._connecting){r.nextTick(()=>P(Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(D,S){if(D)return P(D);w.native.connect(S,function(F){if(F)return w.native.end(),P(F);w._connected=!0,w.native.on("error",function(L){w._queryable=!1,w._errorAllQueries(L),w.emit("error",L)}),w.native.on("notification",function(L){w.emit("notification",{channel:L.relname,payload:L.extra})}),w.emit("connect"),w._pulseQueryQueue(!0),P()})})},R.prototype.connect=function(P){if(P){this._connect(P);return}return new this._Promise((w,D)=>{this._connect((S)=>{S?D(S):w()})})},R.prototype.query=function(P,w,D){var S,F,L,Q,_;if(P==null)throw TypeError("Client was passed a null or undefined query");if(typeof P.submit=="function")L=P.query_timeout||this.connectionParameters.query_timeout,F=S=P,typeof w=="function"&&(P.callback=w);else if(L=this.connectionParameters.query_timeout,S=new V(P,w,D),!S.callback){let v,T;F=new this._Promise((x,q)=>{v=x,T=q}),S.callback=(x,q)=>x?T(x):v(q)}return L&&(_=S.callback,Q=setTimeout(()=>{var v=Error("Query read timeout");r.nextTick(()=>{S.handleError(v,this.connection)}),_(v),S.callback=()=>{};var T=this._queryQueue.indexOf(S);T>-1&&this._queryQueue.splice(T,1),this._pulseQueryQueue()},L),S.callback=(v,T)=>{clearTimeout(Q),_(v,T)}),this._queryable?this._ending?(S.native=this.native,r.nextTick(()=>{S.handleError(Error("Client was closed and is not queryable"))}),F):(this._queryQueue.push(S),this._pulseQueryQueue(),F):(S.native=this.native,r.nextTick(()=>{S.handleError(Error("Client has encountered a connection error and is not queryable"))}),F)},R.prototype.end=function(P){var w=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,P));var D;return P||(D=new this._Promise(function(S,F){P=U((L)=>L?F(L):S(),"cb")})),this.native.end(function(){w._errorAllQueries(Error("Connection terminated")),r.nextTick(()=>{w.emit("end"),P&&P()})}),D},R.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"},R.prototype._pulseQueryQueue=function(P){if(this._connected&&!this._hasActiveQuery()){var w=this._queryQueue.shift();if(!w){P||this.emit("drain");return}this._activeQuery=w,w.submit(this);var D=this;w.once("_done",function(){D._pulseQueryQueue()})}},R.prototype.cancel=function(P){this._activeQuery===P?this.native.cancel(function(){}):this._queryQueue.indexOf(P)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(P),1)},R.prototype.ref=function(){},R.prototype.unref=function(){},R.prototype.setTypeParser=function(P,w,D){return this._types.setTypeParser(P,w,D)},R.prototype.getTypeParser=function(P,w){return this._types.getTypeParser(P,w)}}),U7=o((W,$)=>{u(),$.exports=nZ()}),g4=o((W,$)=>{u();var Z=iZ(),J=b4(),X=p7(),Y=tZ(),{DatabaseError:M}=c7(),G=U((R)=>{var P;return P=class extends Y{constructor(w){super(w,R)}},U(P,"BoundPool"),P},"poolFactory"),V=U(function(R){this.defaults=J,this.Client=R,this.Query=this.Client.Query,this.Pool=G(this.Client),this._pools=[],this.Connection=X,this.types=B4(),this.DatabaseError=M},"PG");typeof r.env.NODE_PG_FORCE_NATIVE<"u"?$.exports=new V(U7()):($.exports=new V(Z),Object.defineProperty($.exports,"native",{configurable:!0,enumerable:!1,get(){var R=null;try{R=new V(U7())}catch(P){if(P.code!=="MODULE_NOT_FOUND")throw P}return Object.defineProperty($.exports,"native",{value:R}),R}}))});u();u();tW();_7();u();var{defineProperty:rZ,defineProperties:oZ,getOwnPropertyDescriptors:eZ,getOwnPropertySymbols:V7}=Object,WJ=Object.prototype.hasOwnProperty,$J=Object.prototype.propertyIsEnumerable,P7=U((W,$,Z)=>($ in W)?rZ(W,$,{enumerable:!0,configurable:!0,writable:!0,value:Z}):W[$]=Z,"__defNormalProp"),ZJ=U((W,$)=>{for(var Z in $||($={}))WJ.call($,Z)&&P7(W,Z,$[Z]);if(V7)for(var Z of V7($))$J.call($,Z)&&P7(W,Z,$[Z]);return W},"__spreadValues"),JJ=U((W,$)=>oZ(W,eZ($)),"__spreadProps"),XJ=1008000,F7=new Uint8Array(new Uint16Array([258]).buffer)[0]===2,YJ=new TextDecoder,R9=new TextEncoder,N4=R9.encode("0123456789abcdef"),C4=R9.encode("0123456789ABCDEF"),HJ=R9.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),a7=HJ.slice();a7[62]=45;a7[63]=95;var pW,q4;function d7(W,{alphabet:$,scratchArr:Z}={}){if(!pW)if(pW=new Uint16Array(256),q4=new Uint16Array(256),F7)for(let S=0;S<256;S++)pW[S]=N4[S&15]<<8|N4[S>>>4],q4[S]=C4[S&15]<<8|C4[S>>>4];else for(let S=0;S<256;S++)pW[S]=N4[S&15]|N4[S>>>4]<<8,q4[S]=C4[S&15]|C4[S>>>4]<<8;W.byteOffset%4!==0&&(W=new Uint8Array(W));let J=W.length,X=J>>>1,Y=J>>>2,M=Z||new Uint16Array(J),G=new Uint32Array(W.buffer,W.byteOffset,Y),V=new Uint32Array(M.buffer,M.byteOffset,X),R=$==="upper"?q4:pW,P=0,w=0,D;if(F7)for(;P<Y;)D=G[P++],V[w++]=R[D>>>8&255]<<16|R[D&255],V[w++]=R[D>>>24]<<16|R[D>>>16&255];else for(;P<Y;)D=G[P++],V[w++]=R[D>>>24]<<16|R[D>>>16&255],V[w++]=R[D>>>8&255]<<16|R[D&255];for(P<<=2;P<J;)M[P]=R[W[P++]];return YJ.decode(M.subarray(0,J))}U(d7,"_toHex");function s7(W,$={}){let Z="",J=W.length,X=XJ>>>1,Y=Math.ceil(J/X),M=new Uint16Array(Y>1?X:J);for(let G=0;G<Y;G++){let V=G*X,R=V+X;Z+=d7(W.subarray(V,R),JJ(ZJ({},$),{scratchArr:M}))}return Z}U(s7,"_toHexChunked");function n7(W,$={}){return $.alphabet!=="upper"&&typeof W.toHex=="function"?W.toHex():s7(W,$)}U(n7,"toHex");u();var r7=class W{constructor($,Z){this.strings=$,this.values=Z}toParameterizedQuery($={query:"",params:[]}){let{strings:Z,values:J}=this;for(let X=0,Y=Z.length;X<Y;X++)if($.query+=Z[X],X<J.length){let M=J[X];if(M instanceof W$)$.query+=M.sql;else if(M instanceof O4)if(M.queryData instanceof W)M.queryData.toParameterizedQuery($);else{if(M.queryData.params?.length)throw Error("This query is not composable");$.query+=M.queryData.query}else{let{params:G}=$;G.push(M),$.query+="$"+G.length,(M instanceof i||ArrayBuffer.isView(M))&&($.query+="::bytea")}}return $}};U(r7,"SqlTemplate");var o7=r7,e7=class{constructor($){this.sql=$}};U(e7,"UnsafeRawSql");var W$=e7;u();function D9(){typeof window<"u"&&typeof document<"u"&&typeof console<"u"&&typeof console.warn=="function"&&console.warn(`
29
29
  ************************************************************
30
30
  * *
31
31
  * WARNING: Running SQL directly from the browser can have *
@@ -40,7 +40,7 @@ Expecting one of '${k.join("', '")}'`);let J=`${W}Help`;return this.on(J,(Z)=>{l
40
40
  * using the disableWarningInBrowsers configuration *
41
41
  * parameter. *
42
42
  * *
43
- ************************************************************`)}U($9,"warnIfBrowser");Q8();var E2=R0(a6()),v2=R0(E4()),E7=class W extends Error{constructor($){super($);s(this,"name","NeonDbError"),s(this,"severity"),s(this,"code"),s(this,"detail"),s(this,"hint"),s(this,"position"),s(this,"internalPosition"),s(this,"internalQuery"),s(this,"where"),s(this,"schema"),s(this,"table"),s(this,"column"),s(this,"dataType"),s(this,"constraint"),s(this,"file"),s(this,"line"),s(this,"routine"),s(this,"sourceError"),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,W)}};U(E7,"NeonDbError");var a0=E7,m5="transaction() expects an array of queries, or a function returning an array of queries",S2=["severity","code","detail","hint","position","internalPosition","internalQuery","where","schema","table","column","dataType","constraint","file","line","routine"];function v7(W){return W instanceof t?"\\x"+h7(W):W}U(v7,"encodeBuffersAsBytea");function i6(W){let{query:$,params:k}=W instanceof D7?W.toParameterizedQuery():W;return{query:$,params:k.map((J)=>v7((0,v2.prepareValue)(J)))}}U(i6,"prepareQuery");function N4(W,{arrayMode:$,fullResults:k,fetchOptions:J,isolationLevel:Z,readOnly:X,deferrable:G,authToken:z,disableWarningInBrowsers:V}={}){if(!W)throw Error("No database connection string was provided to `neon()`. Perhaps an environment variable has not been set?");let w;try{w=s6(W)}catch{throw Error("Database connection string provided to `neon()` is not a valid URL. Connection string: "+String(W))}let{protocol:R,username:h,hostname:_,port:D,pathname:F}=w;if(R!=="postgres:"&&R!=="postgresql:"||!h||!_||!F)throw Error("Database connection string format for `neon()` should be: postgresql://user:password@host.tld/dbname?option=value");function M(f,...T){if(!(Array.isArray(f)&&Array.isArray(f.raw)&&Array.isArray(T)))throw Error('This function can now be called only as a tagged-template function: sql`SELECT ${value}`, not sql("SELECT $1", [value], options). For a conventional function call with value placeholders ($1, $2, etc.), use sql.query("SELECT $1", [value], options).');return new P4(P,new D7(f,T))}U(M,"templateFn"),M.query=(f,T,S)=>new P4(P,{query:f,params:T??[]},S),M.unsafe=(f)=>new T7(f),M.transaction=async(f,T)=>{if(typeof f=="function"&&(f=f(M)),!Array.isArray(f))throw Error(m5);f.forEach((Q)=>{if(!(Q instanceof P4))throw Error(m5)});let S=f.map((Q)=>Q.queryData),q=f.map((Q)=>Q.opts??{});return P(S,q,T)};async function P(f,T,S){let{fetchEndpoint:q,fetchFunction:Q}=V0,E=Array.isArray(f)?{queries:f.map((JW)=>i6(JW))}:i6(f),j=J??{},A=$??!1,N=k??!1,b=Z,C=X,u=G;S!==void 0&&(S.fetchOptions!==void 0&&(j={...j,...S.fetchOptions}),S.arrayMode!==void 0&&(A=S.arrayMode),S.fullResults!==void 0&&(N=S.fullResults),S.isolationLevel!==void 0&&(b=S.isolationLevel),S.readOnly!==void 0&&(C=S.readOnly),S.deferrable!==void 0&&(u=S.deferrable)),T!==void 0&&!Array.isArray(T)&&T.fetchOptions!==void 0&&(j={...j,...T.fetchOptions});let c=z;!Array.isArray(T)&&T?.authToken!==void 0&&(c=T.authToken);let B=typeof q=="function"?q(_,D,{jwtAuth:c!==void 0}):q,m={"Neon-Connection-String":W,"Neon-Raw-Text-Output":"true","Neon-Array-Mode":"true"},p=await N7(c);p&&(m.Authorization=`Bearer ${p}`),Array.isArray(f)&&(b!==void 0&&(m["Neon-Batch-Isolation-Level"]=b),C!==void 0&&(m["Neon-Batch-Read-Only"]=String(C)),u!==void 0&&(m["Neon-Batch-Deferrable"]=String(u))),V||V0.disableWarningInBrowsers||$9();let a;try{a=await(Q??fetch)(B,{method:"POST",body:JSON.stringify(E),headers:m,...j})}catch(JW){let n=new a0(`Error connecting to database: ${JW}`);throw n.sourceError=JW,n}if(a.ok){let JW=await a.json();if(Array.isArray(f)){let n=JW.results;if(!Array.isArray(n))throw new a0("Neon internal error: unexpected result format");return n.map((sW,RW)=>{let SW=T[RW]??{},r0=SW.arrayMode??A,e0=SW.fullResults??N;return p6(sW,{arrayMode:r0,fullResults:e0,types:SW.types})})}else{let n=T??{},sW=n.arrayMode??A,RW=n.fullResults??N;return p6(JW,{arrayMode:sW,fullResults:RW,types:n.types})}}else{let{status:JW}=a;if(JW===400){let n=await a.json(),sW=new a0(n.message);for(let RW of S2)sW[RW]=n[RW]??void 0;throw sW}else{let n=await a.text();throw new a0(`Server error (HTTP status ${JW}): ${n}`)}}}return U(P,"execute"),M}U(N4,"neon");var S7=class{constructor($,k,J){this.execute=$,this.queryData=k,this.opts=J}then($,k){return this.execute(this.queryData,this.opts).then($,k)}catch($){return this.execute(this.queryData,this.opts).catch($)}finally($){return this.execute(this.queryData,this.opts).finally($)}};U(S7,"NeonQueryPromise");var P4=S7;function p6(W,{arrayMode:$,fullResults:k,types:J}){let Z=new E2.default(J),X=W.fields.map((V)=>V.name),G=W.fields.map((V)=>Z.getTypeParser(V.dataTypeID)),z=$===!0?W.rows.map((V)=>V.map((w,R)=>w===null?null:G[R](w))):W.rows.map((V)=>Object.fromEntries(V.map((w,R)=>[X[R],w===null?null:G[R](w)])));return k?(W.viaNeonFetch=!0,W.rowAsArray=$,W.rows=z,W._parsers=G,W._types=Z,W):z}U(p6,"processQueryResult");async function N7(W){if(typeof W=="string")return W;if(typeof W=="function")try{return await Promise.resolve(W())}catch($){let k=new a0("Error getting auth token.");throw $ instanceof Error&&(k=new a0(`Error getting auth token: ${$.message}`)),k}}U(N7,"getAuthToken");l();var N2=R0(S4());l();var O2=R0(S4()),O7=class extends O2.Client{constructor($){super($);this.config=$}get neonConfig(){return this.connection.stream}connect($){let{neonConfig:k}=this;k.forceDisablePgSSL&&(this.ssl=this.connection.ssl=!1),this.ssl&&k.useSecureWebSocket&&console.warn("SSL is enabled for both Postgres (e.g. ?sslmode=require in the connection string + forceDisablePgSSL = false) and the WebSocket tunnel (useSecureWebSocket = true). Double encryption will increase latency and CPU usage. It may be appropriate to disable SSL in the Postgres connection parameters or set forceDisablePgSSL = true.");let J=typeof this.config!="string"&&this.config?.host!==void 0||typeof this.config!="string"&&this.config?.connectionString!==void 0||o.env.PGHOST!==void 0,Z=o.env.USER??o.env.USERNAME;if(!J&&this.host==="localhost"&&this.user===Z&&this.database===Z&&this.password===null)throw Error(`No database host or connection string was set, and key parameters have default values (host: localhost, user: ${Z}, db: ${Z}, password: null). Is an environment variable missing? Alternatively, if you intended to connect with these parameters, please set the host to 'localhost' explicitly.`);let X=super.connect($),G=k.pipelineTLS&&this.ssl,z=k.pipelineConnect==="password";if(!G&&!k.pipelineConnect)return X;let V=this.connection;if(G&&V.on("connect",()=>V.stream.emit("data","S")),z){V.removeAllListeners("authenticationCleartextPassword"),V.removeAllListeners("readyForQuery"),V.once("readyForQuery",()=>V.on("readyForQuery",this._handleReadyForQuery.bind(this)));let w=this.ssl?"sslconnect":"connect";V.on(w,()=>{this.neonConfig.disableWarningInBrowsers||$9(),this._handleAuthCleartextPassword(),this._handleReadyForQuery()})}return X}async _handleAuthSASLContinue($){if(typeof crypto>"u"||crypto.subtle===void 0||crypto.subtle.importKey===void 0)throw Error("Cannot use SASL auth when `crypto.subtle` is not defined");let k=crypto.subtle,J=this.saslSession,Z=this.password,X=$.data;if(J.message!=="SASLInitialResponse"||typeof Z!="string"||typeof X!="string")throw Error("SASL: protocol error");let G=Object.fromEntries(X.split(",").map((JW)=>{if(!/^.=/.test(JW))throw Error("SASL: Invalid attribute pair entry");let n=JW[0],sW=JW.substring(2);return[n,sW]})),z=G.r,V=G.s,w=G.i;if(!z||!/^[!-+--~]+$/.test(z))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing/unprintable");if(!V||!/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(V))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing/not base64");if(!w||!/^[1-9][0-9]*$/.test(w))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: missing/invalid iteration count");if(!z.startsWith(J.clientNonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");if(z.length===J.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");let R=parseInt(w,10),h=t.from(V,"base64"),_=new TextEncoder,D=_.encode(Z),F=await k.importKey("raw",D,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),M=new Uint8Array(await k.sign("HMAC",F,t.concat([h,t.from([0,0,0,1])]))),P=M;for(var f=0;f<R-1;f++)M=new Uint8Array(await k.sign("HMAC",F,M)),P=t.from(P.map((JW,n)=>P[n]^M[n]));let T=P,S=await k.importKey("raw",T,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),q=new Uint8Array(await k.sign("HMAC",S,_.encode("Client Key"))),Q=await k.digest("SHA-256",q),E="n=*,r="+J.clientNonce,j="r="+z+",s="+V+",i="+R,A="c=biws,r="+z,N=E+","+j+","+A,b=await k.importKey("raw",Q,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var C=new Uint8Array(await k.sign("HMAC",b,_.encode(N))),u=t.from(q.map((JW,n)=>q[n]^C[n])),c=u.toString("base64");let B=await k.importKey("raw",T,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),m=await k.sign("HMAC",B,_.encode("Server Key")),p=await k.importKey("raw",m,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var a=t.from(await k.sign("HMAC",p,_.encode(N)));J.message="SASLResponse",J.serverSignature=a.toString("base64"),J.response=A+",p="+c,this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}};U(O7,"NeonClient");var A2=O7;Q8();var j2=R0(e6());function A7(W,$){if($)return{callback:$,result:void 0};let k,J,Z=U(function(G,z){G?k(G):J(z)},"cb"),X=new W(function(G,z){J=G,k=z});return{callback:Z,result:X}}U(A7,"promisify");var j7=class extends N2.Pool{constructor(){super(...arguments);s(this,"Client",A2),s(this,"hasFetchUnsupportedListeners",!1),s(this,"addListener",this.on)}on($,k){return $!=="error"&&(this.hasFetchUnsupportedListeners=!0),super.on($,k)}query($,k,J){if(!V0.poolQueryViaFetch||this.hasFetchUnsupportedListeners||typeof $=="function")return super.query($,k,J);typeof k=="function"&&(J=k,k=void 0);let Z=A7(this.Promise,J);J=Z.callback;try{let X=new j2.default(this.options),G=encodeURIComponent,z=encodeURI,V=`postgresql://${G(X.user)}:${G(X.password)}@${G(X.host)}/${z(X.database)}`,w=typeof $=="string"?$:$.text,R=k??$.values??[];N4(V,{fullResults:!0,arrayMode:$.rowMode==="array"}).query(w,R,{types:$.types??this.options?.types}).then((h)=>J(void 0,h)).catch((h)=>J(h))}catch(X){J(X)}return Z.result}};U(j7,"NeonPool");var C7=j7;Q8();var q8=R0(S4());var{DatabaseError:t_,defaults:s_,escapeIdentifier:a_,escapeLiteral:d_,types:n_}=q8;/*! Bundled license information:
43
+ ************************************************************`)}U(D9,"warnIfBrowser");tW();var kJ=Q8(K9()),GJ=Q8(I4()),$$=class W extends Error{constructor($){super($);t(this,"name","NeonDbError"),t(this,"severity"),t(this,"code"),t(this,"detail"),t(this,"hint"),t(this,"position"),t(this,"internalPosition"),t(this,"internalQuery"),t(this,"where"),t(this,"schema"),t(this,"table"),t(this,"column"),t(this,"dataType"),t(this,"constraint"),t(this,"file"),t(this,"line"),t(this,"routine"),t(this,"sourceError"),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,W)}};U($$,"NeonDbError");var XW=$$,R7="transaction() expects an array of queries, or a function returning an array of queries",MJ=["severity","code","detail","hint","position","internalPosition","internalQuery","where","schema","table","column","dataType","constraint","file","line","routine"];function Z$(W){return W instanceof i?"\\x"+n7(W):W}U(Z$,"encodeBuffersAsBytea");function k9(W){let{query:$,params:Z}=W instanceof o7?W.toParameterizedQuery():W;return{query:$,params:Z.map((J)=>Z$((0,GJ.prepareValue)(J)))}}U(k9,"prepareQuery");function m4(W,{arrayMode:$,fullResults:Z,fetchOptions:J,isolationLevel:X,readOnly:Y,deferrable:M,authToken:G,disableWarningInBrowsers:V}={}){if(!W)throw Error("No database connection string was provided to `neon()`. Perhaps an environment variable has not been set?");let R;try{R=L9(W)}catch{throw Error("Database connection string provided to `neon()` is not a valid URL. Connection string: "+String(W))}let{protocol:P,username:w,hostname:D,port:S,pathname:F}=R;if(P!=="postgres:"&&P!=="postgresql:"||!w||!D||!F)throw Error("Database connection string format for `neon()` should be: postgresql://user:password@host.tld/dbname?option=value");function L(_,...v){if(!(Array.isArray(_)&&Array.isArray(_.raw)&&Array.isArray(v)))throw Error('This function can now be called only as a tagged-template function: sql`SELECT ${value}`, not sql("SELECT $1", [value], options). For a conventional function call with value placeholders ($1, $2, etc.), use sql.query("SELECT $1", [value], options).');return new O4(Q,new o7(_,v))}U(L,"templateFn"),L.query=(_,v,T)=>new O4(Q,{query:_,params:v??[]},T),L.unsafe=(_)=>new W$(_),L.transaction=async(_,v)=>{if(typeof _=="function"&&(_=_(L)),!Array.isArray(_))throw Error(R7);_.forEach((q)=>{if(!(q instanceof O4))throw Error(R7)});let T=_.map((q)=>q.queryData),x=_.map((q)=>q.opts??{});return Q(T,x,v)};async function Q(_,v,T){let{fetchEndpoint:x,fetchFunction:q}=w8,E=Array.isArray(_)?{queries:_.map((J1)=>k9(J1))}:k9(_),N=J??{},A=$??!1,f=Z??!1,B=X,C=Y,c=M;T!==void 0&&(T.fetchOptions!==void 0&&(N={...N,...T.fetchOptions}),T.arrayMode!==void 0&&(A=T.arrayMode),T.fullResults!==void 0&&(f=T.fullResults),T.isolationLevel!==void 0&&(B=T.isolationLevel),T.readOnly!==void 0&&(C=T.readOnly),T.deferrable!==void 0&&(c=T.deferrable)),v!==void 0&&!Array.isArray(v)&&v.fetchOptions!==void 0&&(N={...N,...v.fetchOptions});let m=G;!Array.isArray(v)&&v?.authToken!==void 0&&(m=v.authToken);let b=typeof x=="function"?x(D,S,{jwtAuth:m!==void 0}):x,g={"Neon-Connection-String":W,"Neon-Raw-Text-Output":"true","Neon-Array-Mode":"true"},p=await X$(m);p&&(g.Authorization=`Bearer ${p}`),Array.isArray(_)&&(B!==void 0&&(g["Neon-Batch-Isolation-Level"]=B),C!==void 0&&(g["Neon-Batch-Read-Only"]=String(C)),c!==void 0&&(g["Neon-Batch-Deferrable"]=String(c))),V||w8.disableWarningInBrowsers||D9();let d;try{d=await(q??fetch)(b,{method:"POST",body:JSON.stringify(E),headers:g,...N})}catch(J1){let s=new XW(`Error connecting to database: ${J1}`);throw s.sourceError=J1,s}if(d.ok){let J1=await d.json();if(Array.isArray(_)){let s=J1.results;if(!Array.isArray(s))throw new XW("Neon internal error: unexpected result format");return s.map((s1,V1)=>{let f1=v[V1]??{},kW=f1.arrayMode??A,GW=f1.fullResults??f;return G9(s1,{arrayMode:kW,fullResults:GW,types:f1.types})})}else{let s=v??{},s1=s.arrayMode??A,V1=s.fullResults??f;return G9(J1,{arrayMode:s1,fullResults:V1,types:s.types})}}else{let{status:J1}=d;if(J1===400){let s=await d.json(),s1=new XW(s.message);for(let V1 of MJ)s1[V1]=s[V1]??void 0;throw s1}else{let s=await d.text();throw new XW(`Server error (HTTP status ${J1}): ${s}`)}}}return U(Q,"execute"),L}U(m4,"neon");var J$=class{constructor($,Z,J){this.execute=$,this.queryData=Z,this.opts=J}then($,Z){return this.execute(this.queryData,this.opts).then($,Z)}catch($){return this.execute(this.queryData,this.opts).catch($)}finally($){return this.execute(this.queryData,this.opts).finally($)}};U(J$,"NeonQueryPromise");var O4=J$;function G9(W,{arrayMode:$,fullResults:Z,types:J}){let X=new kJ.default(J),Y=W.fields.map((V)=>V.name),M=W.fields.map((V)=>X.getTypeParser(V.dataTypeID)),G=$===!0?W.rows.map((V)=>V.map((R,P)=>R===null?null:M[P](R))):W.rows.map((V)=>Object.fromEntries(V.map((R,P)=>[Y[P],R===null?null:M[P](R)])));return Z?(W.viaNeonFetch=!0,W.rowAsArray=$,W.rows=G,W._parsers=M,W._types=X,W):G}U(G9,"processQueryResult");async function X$(W){if(typeof W=="string")return W;if(typeof W=="function")try{return await Promise.resolve(W())}catch($){let Z=new XW("Error getting auth token.");throw $ instanceof Error&&(Z=new XW(`Error getting auth token: ${$.message}`)),Z}}U(X$,"getAuthToken");u();var LJ=Q8(g4());u();var KJ=Q8(g4()),Y$=class extends KJ.Client{constructor($){super($);this.config=$}get neonConfig(){return this.connection.stream}connect($){let{neonConfig:Z}=this;Z.forceDisablePgSSL&&(this.ssl=this.connection.ssl=!1),this.ssl&&Z.useSecureWebSocket&&console.warn("SSL is enabled for both Postgres (e.g. ?sslmode=require in the connection string + forceDisablePgSSL = false) and the WebSocket tunnel (useSecureWebSocket = true). Double encryption will increase latency and CPU usage. It may be appropriate to disable SSL in the Postgres connection parameters or set forceDisablePgSSL = true.");let J=typeof this.config!="string"&&this.config?.host!==void 0||typeof this.config!="string"&&this.config?.connectionString!==void 0||r.env.PGHOST!==void 0,X=r.env.USER??r.env.USERNAME;if(!J&&this.host==="localhost"&&this.user===X&&this.database===X&&this.password===null)throw Error(`No database host or connection string was set, and key parameters have default values (host: localhost, user: ${X}, db: ${X}, password: null). Is an environment variable missing? Alternatively, if you intended to connect with these parameters, please set the host to 'localhost' explicitly.`);let Y=super.connect($),M=Z.pipelineTLS&&this.ssl,G=Z.pipelineConnect==="password";if(!M&&!Z.pipelineConnect)return Y;let V=this.connection;if(M&&V.on("connect",()=>V.stream.emit("data","S")),G){V.removeAllListeners("authenticationCleartextPassword"),V.removeAllListeners("readyForQuery"),V.once("readyForQuery",()=>V.on("readyForQuery",this._handleReadyForQuery.bind(this)));let R=this.ssl?"sslconnect":"connect";V.on(R,()=>{this.neonConfig.disableWarningInBrowsers||D9(),this._handleAuthCleartextPassword(),this._handleReadyForQuery()})}return Y}async _handleAuthSASLContinue($){if(typeof crypto>"u"||crypto.subtle===void 0||crypto.subtle.importKey===void 0)throw Error("Cannot use SASL auth when `crypto.subtle` is not defined");let Z=crypto.subtle,J=this.saslSession,X=this.password,Y=$.data;if(J.message!=="SASLInitialResponse"||typeof X!="string"||typeof Y!="string")throw Error("SASL: protocol error");let M=Object.fromEntries(Y.split(",").map((J1)=>{if(!/^.=/.test(J1))throw Error("SASL: Invalid attribute pair entry");let s=J1[0],s1=J1.substring(2);return[s,s1]})),G=M.r,V=M.s,R=M.i;if(!G||!/^[!-+--~]+$/.test(G))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing/unprintable");if(!V||!/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(V))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing/not base64");if(!R||!/^[1-9][0-9]*$/.test(R))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: missing/invalid iteration count");if(!G.startsWith(J.clientNonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");if(G.length===J.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");let P=parseInt(R,10),w=i.from(V,"base64"),D=new TextEncoder,S=D.encode(X),F=await Z.importKey("raw",S,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),L=new Uint8Array(await Z.sign("HMAC",F,i.concat([w,i.from([0,0,0,1])]))),Q=L;for(var _=0;_<P-1;_++)L=new Uint8Array(await Z.sign("HMAC",F,L)),Q=i.from(Q.map((J1,s)=>Q[s]^L[s]));let v=Q,T=await Z.importKey("raw",v,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),x=new Uint8Array(await Z.sign("HMAC",T,D.encode("Client Key"))),q=await Z.digest("SHA-256",x),E="n=*,r="+J.clientNonce,N="r="+G+",s="+V+",i="+P,A="c=biws,r="+G,f=E+","+N+","+A,B=await Z.importKey("raw",q,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var C=new Uint8Array(await Z.sign("HMAC",B,D.encode(f))),c=i.from(x.map((J1,s)=>x[s]^C[s])),m=c.toString("base64");let b=await Z.importKey("raw",v,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),g=await Z.sign("HMAC",b,D.encode("Server Key")),p=await Z.importKey("raw",g,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var d=i.from(await Z.sign("HMAC",p,D.encode(f)));J.message="SASLResponse",J.serverSignature=d.toString("base64"),J.response=A+",p="+m,this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}};U(Y$,"NeonClient");var zJ=Y$;tW();var UJ=Q8(F9());function H$(W,$){if($)return{callback:$,result:void 0};let Z,J,X=U(function(M,G){M?Z(M):J(G)},"cb"),Y=new W(function(M,G){J=M,Z=G});return{callback:X,result:Y}}U(H$,"promisify");var k$=class extends LJ.Pool{constructor(){super(...arguments);t(this,"Client",zJ),t(this,"hasFetchUnsupportedListeners",!1),t(this,"addListener",this.on)}on($,Z){return $!=="error"&&(this.hasFetchUnsupportedListeners=!0),super.on($,Z)}query($,Z,J){if(!w8.poolQueryViaFetch||this.hasFetchUnsupportedListeners||typeof $=="function")return super.query($,Z,J);typeof Z=="function"&&(J=Z,Z=void 0);let X=H$(this.Promise,J);J=X.callback;try{let Y=new UJ.default(this.options),M=encodeURIComponent,G=encodeURI,V=`postgresql://${M(Y.user)}:${M(Y.password)}@${M(Y.host)}/${G(Y.database)}`,R=typeof $=="string"?$:$.text,P=Z??$.values??[];m4(V,{fullResults:!0,arrayMode:$.rowMode==="array"}).query(R,P,{types:$.types??this.options?.types}).then((w)=>J(void 0,w)).catch((w)=>J(w))}catch(Y){J(Y)}return X.result}};U(k$,"NeonPool");var G$=k$;tW();var dW=Q8(g4());var{DatabaseError:wQ,defaults:QQ,escapeIdentifier:SQ,escapeLiteral:_Q,types:vQ}=dW;/*! Bundled license information:
44
44
 
45
45
  ieee754/index.js:
46
46
  (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
@@ -52,5 +52,5 @@ buffer/index.js:
52
52
  * @author Feross Aboukhadijeh <https://feross.org>
53
53
  * @license MIT
54
54
  *)
55
- */var Q7=Symbol("release"),x7=class{#W;constructor(W){this.#W=W}async executeQuery(W){let $=await this.#W.query(W.sql,[...W.parameters]);if($.command==="INSERT"||$.command==="UPDATE"||$.command==="DELETE"){let k=BigInt($.rowCount);return{numUpdatedOrDeletedRows:k,numAffectedRows:k,rows:$.rows??[]}}return{rows:$.rows??[]}}async*streamQuery(W,$){throw Error("Neon Driver does not support streaming")}[Q7](){this.#W.release?.()}},q7=class{#W;constructor(W){this.#W=W}createAdapter(){return new O8}createDriver(){return new C2(this.#W)}createQueryCompiler(){return new S8}createIntrospector(W){return new N8(W)}},C2=class{#W;#$=new WeakMap;#k;constructor(W){this.#W=W}async init(){Object.assign(V0,this.#W),this.#k=new C7(this.#W)}async acquireConnection(){let W=await this.#k.connect(),$=this.#$.get(W);if(!$)$=new x7(W),this.#$.set(W,$);return $}async beginTransaction(W,$){if($.isolationLevel)await W.executeQuery(v8.raw(`start transaction isolation level ${$.isolationLevel}`));else await W.executeQuery(v8.raw("begin"))}async commitTransaction(W){await W.executeQuery(v8.raw("commit"))}async rollbackTransaction(W){await W.executeQuery(v8.raw("rollback"))}async releaseConnection(W){W[Q7]()}async destroy(){if(this.#k){let W=this.#k;this.#k=void 0,await W.end()}}},Zh=class{#W;constructor(W){this.#W=W}createAdapter(){return new O8}createDriver(){return new Q2(this.#W)}createQueryCompiler(){return new S8}createIntrospector(W){return new N8(W)}},Q2=class{#W;#$;constructor(W){this.#W=W,this.#$=new x7({query:N4(this.#W.connectionString,{fullResults:!0})})}async init(){}async acquireConnection(){return this.#$}async beginTransaction(W,$){throw Error("Transactions are not supported with Neon HTTP connections")}async commitTransaction(W){throw Error("Transactions are not supported with Neon HTTP connections")}async rollbackTransaction(W){throw Error("Transactions are not supported with Neon HTTP connections")}async releaseConnection(W){}async destroy(){}};function O4(W){if(typeof W!=="string")return!1;if(W==="development"||W==="test"||W==="staging"||W==="production")return!0;return!1}function x2({pg_host:W,environment:$,...k}){let J=k.debug??!1;if(J)console.log(`[getPostgresNeonWsProxyUrl] Loading websocket proxy URL in environment "${$}" from base 'pg_host' url:`,W);let Z;if($==="production")Z=W;else if($==="development")if(W.includes("localhost"))Z="localhost";else Z="postgres-ws-proxy";else if($==="test"||$==="staging")Z="postgres-ws-proxy";else throw Error("Failed to build 'ws_host' url for Postgres Neon proxy!");console.assert(O4($),"Invalid app environment to determine postgres neon websocket proxy URL for!");let V=`${Z}${$!=="production"?":5433":""}/${$==="production"?"v2":"v1"}`;if(console.assert(!V.startsWith("ws://")&&!V.startsWith("wss://"),"Expected built postgres neon proxy websocket URL to not include protocol (ws:// or wss://)!"),J)console.log("[getPostgresNeonWsProxyUrl] Loaded websocket proxy URL: ",V);return V}var b7=x2;function q2(W){let $=process.env.SCHEMAVAULTS_DBH_DEBUG;if(typeof $==="string")if($.toLowerCase().includes("true"))return!0;else return!1;else if(W!=="production")return!0;else return!1}var B7=q2;function b2(W){if(!W)return W;let $=W.trim();if($.startsWith('"')&&$.endsWith('"'))return $.slice(1,-1);if($.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}var J0=b2;function B2(W){return`postgresql://${W.POSTGRES_USER}:${W.POSTGRES_PASSWORD}@${W.POSTGRES_HOST}:${W.POSTGRES_PORT}/${W.POSTGRES_DATABASE}`}var I7=B2;function I2(W,$=!1){if(typeof W!=="object")throw Error("Did not receive an object to parse database credentials from!");if(Object.values(W).some((w)=>typeof w!=="string"&&typeof w<"u"&&typeof w!=="number"&&typeof w!=="boolean")){let w=new Set(Object.values(W).map((R)=>typeof R));throw w.delete("undefined"),w.delete("string"),w.delete("number"),w.delete("boolean"),TypeError(`Received invalid database credentials; expected only strings or undefined in values object provided to parse credentials from. Received invalid types: ${Array.from(w).join(", ")}`)}let k=J0(typeof W.POSTGRES_URL_NON_POOLING==="string"?W.POSTGRES_URL_NON_POOLING:void 0);if(!k){if($)console.warn("POSTGRES_URL_NON_POOLING is not set in environment variables!")}else if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using postgres no-pooling connection url POSTGRES_URL_NON_POOLING: "${k}"`);let J=J0(typeof W.POSTGRES_HOST==="string"?W.POSTGRES_HOST:void 0);if(!J)throw Error("POSTGRES_HOST is not set in environment variables!");else if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using database POSTGRES_HOST: "${J}"`);let Z=5432;if(typeof W.POSTGRES_PORT==="string"&&W.POSTGRES_PORT.length>0)Z=Number.parseInt(J0(W.POSTGRES_PORT)??"NaN");if(typeof Z!=="number"||isNaN(Z))throw Error("Failed to load POSTGRES_PORT from environment variables! NaN error!");let X=J0(typeof W.POSTGRES_DATABASE==="string"?W.POSTGRES_DATABASE:void 0);if(!X)throw Error("Failed to load database name from POSTGRES_DATABASE environment variable!");let G=J0(typeof W.POSTGRES_USER==="string"?W.POSTGRES_USER:void 0);if(!G)throw Error("POSTGRES_USER is not defined in environment variables!");let z=J0(typeof W.POSTGRES_PASSWORD==="string"?W.POSTGRES_PASSWORD:void 0);if(!z)throw Error("POSTGRES_PASSWORD is not defined in environment variables!");let V="";if(typeof W.POSTGRES_URL==="string"&&W.POSTGRES_URL.length>0)V=J0(W.POSTGRES_URL)??"";else V=I7({POSTGRES_DATABASE:X,POSTGRES_HOST:J,POSTGRES_PORT:Z,POSTGRES_USER:G,POSTGRES_PASSWORD:z});if(!V)throw Error("Failed to load POSTGRES_URL from environment variables, or to construct it from other environment variables!");if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using postgres connection url POSTGRES_URL: "${V}"`);return{POSTGRES_USER:G,POSTGRES_PASSWORD:z,POSTGRES_URL:V,POSTGRES_URL_NON_POOLING:k,POSTGRES_HOST:J,POSTGRES_PORT:Z,POSTGRES_DATABASE:X}}var A4=I2;function y2(W,$=!1){return A4(W,$)}var y7=y2;class n0{kysely_db;env;debug;static getPostgresNeonWsProxyUrl(W){return b7(W)}static parsePort(W){let $=typeof W.POSTGRES_PORT==="number"?W.POSTGRES_PORT:Number.parseInt(W.POSTGRES_PORT);if(isNaN($))throw Error(`Invalid port number: ${W.POSTGRES_PORT}`);return $}constructor({environment:W,...$}){if(!O4(W))throw TypeError("Invalid SCHEMAVAULTS_APP_ENVIRONMENT!");this.env=W;let k=B7(this.env);this.debug=k;let J=void 0;if($.credentials){if(typeof $.credentials!=="object")throw TypeError("'credentials' is truthy but not an object!");J=A4($.credentials,this.debug)}else J=y7(process.env,this.debug);if(!J)throw Error("Failed to parse database credentials from options or environment variables!");let Z={connectionString:J.POSTGRES_URL,host:J.POSTGRES_HOST,user:J.POSTGRES_USER,password:J.POSTGRES_PASSWORD,database:J.POSTGRES_DATABASE,useSecureWebSocket:this.env==="production",port:n0.parsePort(J),wsProxy:(z)=>{if(k)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${z}")`);let V;try{let w={pg_host:z,environment:W,debug:this.debug};if(typeof $.wsProxyUrl>"u"||!$.wsProxyUrl)V=n0.getPostgresNeonWsProxyUrl(w);else if(typeof $.wsProxyUrl==="string"&&$.wsProxyUrl&&$.wsProxyUrl.length>0)V=$.wsProxyUrl;else if(typeof $.wsProxyUrl==="function"&&$.wsProxyUrl){let R=$.wsProxyUrl;V=R(w)}else throw Error(`Invalid wsProxy url for host: "${z}". Not a string, undefined, or function!`)}catch(w){throw console.error(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${z}") => Failure: `,w),Error(`Failed to calculate wsProxy url for host: "${z}"`)}if(this.debug)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${z}") => `,V);return V}};if(this.debug)Z.pipelineTLS=!1,Z.pipelineConnect=!1;if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Kysely Neon DB adapter configuration: ",Z);if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Initializing SchemaVaults x Kysely x Neon database adapter...");let G={dialect:new q7(Z),log:["query","error"]};if(this.kysely_db=new g1(G),this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Initialized SchemaVaults x Kysely x Neon database adapter in environment: ",this.env)}get db(){return this.kysely_db}async destroy(){await this.kysely_db.destroy();return}}import g2 from"fs/promises";import m2 from"path";import{existsSync as g7}from"fs";function m7({db:W,migrationFolder:$}){return new g6({db:W,provider:new m6({fs:g2,path:m2,migrationFolder:$})})}function c2(W){if(typeof W!=="object"||!W)throw TypeError("Expected migration result to be an object!");if(!("migrationName"in W)||typeof W.migrationName!=="string")throw TypeError("Expected migration result's 'migrationName' to be a string!");else if(!("direction"in W)||typeof W.direction!=="string")throw TypeError("Expected migration result's 'direction' to be a string!");else if(!("status"in W)||typeof W.status!=="string")throw TypeError("Expected migration result's 'status' to be a string!");else if(!["Up","Down"].includes(W.direction))throw TypeError("Expected migration result's 'direction' to be one of: 'Up' or 'Down'!");else if(!["Success","Error","NotExecuted"].includes(W.status))throw TypeError("Expected migration result's 'status' to be one of: 'Success', 'Error', or 'NotExecuted'!");return!0}function c7(W){if(!Array.isArray(W))throw TypeError("Expected 'results' to be an array!");for(let $ of W)c2($);return!0}async function u7({db:W,migrationFolder:$,...k}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!g7($))throw Error(`migrationFolder '${$}' does not exist`);let J=m7({db:W,migrationFolder:$}),Z;if(typeof k.version==="string")Z=await J.migrateTo(k.version);else Z=await J.migrateToLatest();let{error:X,results:G}=Z;if(X)throw console.error(X),X;if(!G)return[];if(!c7(G))throw TypeError("Migration appears to have succeeded but failed to parse received results!");return G}async function l7({db:W,migrationFolder:$,version:k}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!g7($))throw Error(`migrationFolder '${$}' does not exist`);let J=m7({db:W,migrationFolder:$}),{error:Z,results:X}=await J.migrateTo(k);if(Z)throw console.error(Z),Z;if(!X)return[];if(!c7(X))throw TypeError("Reverse migration appears to have succeeded but failed to parse received results!");return X}import i7 from"fs";import u2 from"path";function k9(W){let $=u2.resolve(W);if(!i7.existsSync($))throw Error(`Env file not found: ${$}`);let k=i7.readFileSync($,"utf-8");for(let J of k.split(`
56
- `)){let Z=J.trim();if(!Z||Z.startsWith("#"))continue;let X=Z.indexOf("=");if(X===-1)continue;let G=Z.slice(0,X).trim(),z=Z.slice(X+1).trim();if(z.startsWith('"')&&z.endsWith('"')||z.startsWith("'")&&z.endsWith("'"))z=z.slice(1,-1);if(process.env[G]===void 0)process.env[G]=z}}var s2=i2(import.meta.url),{version:p7}=s2("../package.json");if(typeof p7!=="string")throw TypeError("Failed to resolve 'version' from @schemavaults/dbh package.json file!");var o0=new S9;o0.name("dbh").description("@schemavaults/dbh CLI — database migration tools").version(p7);o0.command("migrate").description("Run database migrations forward (to latest or a specific version)").argument("<folder>","Path to the migration folder").argument("[version]","Target migration version (defaults to latest)").requiredOption("-e, --environment <environment>","App environment (development|test|staging|production)").option("--ws-proxy-url <url>","Custom WebSocket proxy URL").option("--env-file <path>","Path to env file to load (e.g. .env)").action(async(W,$,k)=>{if(k.envFile)k9(k.envFile);let J=j4.resolve(W),Z=new n0({environment:k.environment,wsProxyUrl:k.wsProxyUrl});try{let X=await u7({db:Z.db,migrationFolder:J,version:$});for(let G of X)console.log(`[${G.direction}] ${G.migrationName}: ${G.status}`);if(X.length===0)console.log("No migrations to run.")}catch(X){console.error("Migration failed:",X),process.exit(1)}finally{await Z.destroy()}});o0.command("reverse").description("Roll back database migrations to a specific version").argument("<folder>","Path to the migration folder").argument("<version>","Target version to roll back to").requiredOption("-e, --environment <environment>","App environment (development|test|staging|production)").option("--ws-proxy-url <url>","Custom WebSocket proxy URL").option("--env-file <path>","Path to env file to load (e.g. .env)").action(async(W,$,k)=>{if(k.envFile)k9(k.envFile);let J=j4.resolve(W),Z=new n0({environment:k.environment,wsProxyUrl:k.wsProxyUrl});try{let X=await l7({db:Z.db,migrationFolder:J,version:$});for(let G of X)console.log(`[${G.direction}] ${G.migrationName}: ${G.status}`);if(X.length===0)console.log("No migrations to reverse.")}catch(X){console.error("Reverse migration failed:",X),process.exit(1)}finally{await Z.destroy()}});o0.command("build-db-migrations").description("Build TypeScript Kysely migration files into JavaScript using Bun's bundler").argument("<migrations-src>","Directory containing .ts migration source files").requiredOption("--outdir <dir>","Output directory for compiled migration .js files").requiredOption("--sql-module <path>","Path to sql.ts source module to build alongside").option("--sql-outdir <dir>","Output directory for the built sql.js module (defaults to parent of --outdir)").option("--external <pkg...>","Packages to keep external in the bundle (default: @schemavaults/dbh, kysely)").option("--debug","Enable debug logging").action(async(W,$)=>{try{p2("bun --version",{stdio:"ignore"})}catch{console.error("Error: 'bun' is required for build-db-migrations but was not found in PATH."),process.exit(1)}let k=j4.dirname(l2(import.meta.url)),Z=["run",j4.resolve(k,"build-db-migrations.js"),W];if(Z.push("--outdir",$.outdir),Z.push("--sql-module",$.sqlModule),$.sqlOutdir)Z.push("--sql-outdir",$.sqlOutdir);if($.external&&$.external.length>0)Z.push("--external",...$.external);if($.debug)Z.push("--debug");t2("bun",Z,{stdio:"inherit",cwd:process.cwd()}).on("close",(G)=>{process.exit(G??1)})});var ah=o0;o0.parse();export{ah as default};
55
+ */var M$=Symbol("release"),L$=class{#W;constructor(W){this.#W=W}async executeQuery(W){let $=await this.#W.query(W.sql,[...W.parameters]);if($.command==="INSERT"||$.command==="UPDATE"||$.command==="DELETE"){let Z=BigInt($.rowCount);return{numUpdatedOrDeletedRows:Z,numAffectedRows:Z,rows:$.rows??[]}}return{rows:$.rows??[]}}async*streamQuery(W,$){throw Error("Neon Driver does not support streaming")}[M$](){this.#W.release?.()}},K$=class{#W;constructor(W){this.#W=W}createAdapter(){return new uW}createDriver(){return new VJ(this.#W)}createQueryCompiler(){return new cW}createIntrospector(W){return new mW(W)}},VJ=class{#W;#$=new WeakMap;#Z;constructor(W){this.#W=W}async init(){Object.assign(w8,this.#W),this.#Z=new G$(this.#W)}async acquireConnection(){let W=await this.#Z.connect(),$=this.#$.get(W);if(!$)$=new L$(W),this.#$.set(W,$);return $}async beginTransaction(W,$){if($.isolationLevel)await W.executeQuery(gW.raw(`start transaction isolation level ${$.isolationLevel}`));else await W.executeQuery(gW.raw("begin"))}async commitTransaction(W){await W.executeQuery(gW.raw("commit"))}async rollbackTransaction(W){await W.executeQuery(gW.raw("rollback"))}async releaseConnection(W){W[M$]()}async destroy(){if(this.#Z){let W=this.#Z;this.#Z=void 0,await W.end()}}},CQ=class{#W;constructor(W){this.#W=W}createAdapter(){return new uW}createDriver(){return new PJ(this.#W)}createQueryCompiler(){return new cW}createIntrospector(W){return new mW(W)}},PJ=class{#W;#$;constructor(W){this.#W=W,this.#$=new L$({query:m4(this.#W.connectionString,{fullResults:!0})})}async init(){}async acquireConnection(){return this.#$}async beginTransaction(W,$){throw Error("Transactions are not supported with Neon HTTP connections")}async commitTransaction(W){throw Error("Transactions are not supported with Neon HTTP connections")}async rollbackTransaction(W){throw Error("Transactions are not supported with Neon HTTP connections")}async releaseConnection(W){}async destroy(){}};function c4(W){if(typeof W!=="string")return!1;if(W==="development"||W==="test"||W==="staging"||W==="production")return!0;return!1}function FJ({pg_host:W,environment:$,...Z}){let J=Z.debug??!1;if(J)console.log(`[getPostgresNeonWsProxyUrl] Loading websocket proxy URL in environment "${$}" from base 'pg_host' url:`,W);let X;if($==="production")X=W;else if($==="development")if(W.includes("localhost"))X="localhost";else X="postgres-ws-proxy";else if($==="test"||$==="staging")X="postgres-ws-proxy";else throw Error("Failed to build 'ws_host' url for Postgres Neon proxy!");console.assert(c4($),"Invalid app environment to determine postgres neon websocket proxy URL for!");let V=`${X}${$!=="production"?":5433":""}/${$==="production"?"v2":"v1"}`;if(console.assert(!V.startsWith("ws://")&&!V.startsWith("wss://"),"Expected built postgres neon proxy websocket URL to not include protocol (ws:// or wss://)!"),J)console.log("[getPostgresNeonWsProxyUrl] Loaded websocket proxy URL: ",V);return V}var z$=FJ;function U$(W){return!isNaN(W)&&Number.isInteger(W)&&Number.isFinite(W)&&W>0}function w9(W){if(typeof W==="number"){if(U$(W))return W}else if(typeof W==="string"){let $=Number.parseInt(W);if(U$($))return $}else throw TypeError(`Unexpected type for value to parse port number from: '${typeof W}'`);throw TypeError("Failed to parse port number for database configuration!")}function RJ(W){let $=process.env.SCHEMAVAULTS_DBH_DEBUG;if(typeof $==="string")if($.toLowerCase().includes("true"))return!0;else return!1;else if(W!=="production")return!0;else return!1}var V$=RJ;function DJ(W){if(!W)return W;let $=W.trim();if($.startsWith('"')&&$.endsWith('"'))return $.slice(1,-1);if($.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}var G8=DJ;function wJ(W){return`postgresql://${W.POSTGRES_USER}:${W.POSTGRES_PASSWORD}@${W.POSTGRES_HOST}:${W.POSTGRES_PORT}/${W.POSTGRES_DATABASE}`}var P$=wJ;function QJ(W,$=!1){if(typeof W!=="object")throw Error("Did not receive an object to parse database credentials from!");if(Object.values(W).some((R)=>typeof R!=="string"&&typeof R<"u"&&typeof R!=="number"&&typeof R!=="boolean")){let R=new Set(Object.values(W).map((P)=>typeof P));throw R.delete("undefined"),R.delete("string"),R.delete("number"),R.delete("boolean"),TypeError(`Received invalid database credentials; expected only strings or undefined in values object provided to parse credentials from. Received invalid types: ${Array.from(R).join(", ")}`)}let Z=G8(typeof W.POSTGRES_URL_NON_POOLING==="string"?W.POSTGRES_URL_NON_POOLING:void 0);if(!Z){if($)console.warn("POSTGRES_URL_NON_POOLING is not set in environment variables!")}else if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using postgres no-pooling connection url POSTGRES_URL_NON_POOLING: "${Z}"`);let J=G8(typeof W.POSTGRES_HOST==="string"?W.POSTGRES_HOST:void 0);if(!J)throw Error("POSTGRES_HOST is not set in environment variables!");else if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using database POSTGRES_HOST: "${J}"`);let X=5432;if(typeof W.POSTGRES_PORT==="string"&&W.POSTGRES_PORT.length>0)X=Number.parseInt(G8(W.POSTGRES_PORT)??"NaN");if(typeof X!=="number"||isNaN(X))throw Error("Failed to load POSTGRES_PORT from environment variables! NaN error!");let Y=G8(typeof W.POSTGRES_DATABASE==="string"?W.POSTGRES_DATABASE:void 0);if(!Y)throw Error("Failed to load database name from POSTGRES_DATABASE environment variable!");let M=G8(typeof W.POSTGRES_USER==="string"?W.POSTGRES_USER:void 0);if(!M)throw Error("POSTGRES_USER is not defined in environment variables!");let G=G8(typeof W.POSTGRES_PASSWORD==="string"?W.POSTGRES_PASSWORD:void 0);if(!G)throw Error("POSTGRES_PASSWORD is not defined in environment variables!");let V="";if(typeof W.POSTGRES_URL==="string"&&W.POSTGRES_URL.length>0)V=G8(W.POSTGRES_URL)??"";else V=P$({POSTGRES_DATABASE:Y,POSTGRES_HOST:J,POSTGRES_PORT:X,POSTGRES_USER:M,POSTGRES_PASSWORD:G});if(!V)throw Error("Failed to load POSTGRES_URL from environment variables, or to construct it from other environment variables!");if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] Using postgres connection url POSTGRES_URL: "${V}"`);return{POSTGRES_USER:M,POSTGRES_PASSWORD:G,POSTGRES_URL:V,POSTGRES_URL_NON_POOLING:Z,POSTGRES_HOST:J,POSTGRES_PORT:X,POSTGRES_DATABASE:Y}}var u4=QJ;function SJ(W,$=!1){return u4(W,$)}var F$=SJ;class l4{credentials;kysely_db;env;debug;constructor(W){if(!c4(W.environment))throw TypeError("Invalid SCHEMAVAULTS_APP_ENVIRONMENT!");this.env=W.environment,this.debug=V$(this.env);let $=void 0;if(W.credentials){if(typeof W.credentials!=="object")throw TypeError("'credentials' is truthy but not an object!");$=u4(W.credentials,this.debug)}else $=F$(process.env,this.debug);if(!$)throw Error("Failed to parse database credentials from options or environment variables!");this.credentials=$;let J={dialect:this.initializeDbDialect(W),log:["query","error"]};this.kysely_db=new Q0(J)}get db(){return this.kysely_db}async destroy(){return await this.kysely_db.destroy()}async[Symbol.asyncDispose](){return await this.destroy()}}class p4 extends l4{initializeDbDialect(W){let $=this.debug,Z=this.env,J=this.credentials,X={connectionString:J.POSTGRES_URL,host:J.POSTGRES_HOST,user:J.POSTGRES_USER,password:J.POSTGRES_PASSWORD,database:J.POSTGRES_DATABASE,useSecureWebSocket:this.env==="production",port:w9(J.POSTGRES_PORT),wsProxy:(M)=>{if($)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${M}")`);let G;try{let V={pg_host:M,environment:Z,debug:this.debug};if(typeof W.wsProxyUrl>"u"||!W.wsProxyUrl)G=z$(V);else if(typeof W.wsProxyUrl==="string"&&W.wsProxyUrl&&W.wsProxyUrl.length>0)G=W.wsProxyUrl;else if(typeof W.wsProxyUrl==="function"&&W.wsProxyUrl){let R=W.wsProxyUrl;G=R(V)}else throw Error(`Invalid wsProxy url for host: "${M}". Not a string, undefined, or function!`)}catch(V){throw console.error(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${M}") => Failure: `,V),Error(`Failed to calculate wsProxy url for host: "${M}"`)}if(this.debug)console.log(`[SchemaVaultsPostgresNeonProxyAdapter] NeonDialectConfig.wsProxy("${M}") => `,G);return G}};if(this.debug)X.pipelineTLS=!1,X.pipelineConnect=!1;if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Kysely Neon DB adapter configuration: ",X);return new K$(X)}constructor(W){super(W);if(this.debug)console.log("[SchemaVaultsPostgresNeonProxyAdapter] Initialized SchemaVaults x Kysely x Neon database adapter in environment: ",this.env)}}class Q9{#W;constructor(W){this.#W=W}async getMigrations(){let W={},$=await this.#W.fs.readdir(this.#W.migrationFolder);for(let Z of $){if(!this.hasExpectedExtension(Z)){this.#W.onFileIgnored?.(Z,"Extension");continue}let J=this.#W.path.join(this.#W.migrationFolder,Z),X=this.#W.import?await this.#W.import(J):await import(J),Y=Z.substring(0,Z.lastIndexOf("."));if(R$(X?.default))W[Y]=X.default;else if(R$(X))W[Y]=X;else this.#W.onFileIgnored?.(Z,"NotMigration")}return W}hasExpectedExtension(W){return W.endsWith(".js")||W.endsWith(".ts")&&!W.endsWith(".d.ts")||W.endsWith(".mjs")||W.endsWith(".mts")&&!W.endsWith(".d.mts")||W.endsWith(".cjs")||W.endsWith(".cts")&&!W.endsWith(".d.cts")}}function R$(W){return Q1(W)&&R1(W.up)}import _J from"fs/promises";import vJ from"path";import{existsSync as D$}from"fs";function w$({db:W,migrationFolder:$}){return new J9({db:W,provider:new Q9({fs:_J,path:vJ,migrationFolder:$})})}function EJ(W){if(typeof W!=="object"||!W)throw TypeError("Expected migration result to be an object!");if(!("migrationName"in W)||typeof W.migrationName!=="string")throw TypeError("Expected migration result's 'migrationName' to be a string!");else if(!("direction"in W)||typeof W.direction!=="string")throw TypeError("Expected migration result's 'direction' to be a string!");else if(!("status"in W)||typeof W.status!=="string")throw TypeError("Expected migration result's 'status' to be a string!");else if(!["Up","Down"].includes(W.direction))throw TypeError("Expected migration result's 'direction' to be one of: 'Up' or 'Down'!");else if(!["Success","Error","NotExecuted"].includes(W.status))throw TypeError("Expected migration result's 'status' to be one of: 'Success', 'Error', or 'NotExecuted'!");return!0}function Q$(W){if(!Array.isArray(W))throw TypeError("Expected 'results' to be an array!");for(let $ of W)EJ($);return!0}async function S$({db:W,migrationFolder:$,...Z}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!D$($))throw Error(`migrationFolder '${$}' does not exist`);let J=w$({db:W,migrationFolder:$}),X;if(typeof Z.version==="string")X=await J.migrateTo(Z.version);else X=await J.migrateToLatest();let{error:Y,results:M}=X;if(Y)throw console.error(Y),Y;if(!M)return[];if(!Q$(M))throw TypeError("Migration appears to have succeeded but failed to parse received results!");return M}async function _$({db:W,migrationFolder:$,version:Z}){if(typeof $!=="string")throw Error("migrationFolder must be a string");if(!D$($))throw Error(`migrationFolder '${$}' does not exist`);let J=w$({db:W,migrationFolder:$}),{error:X,results:Y}=await J.migrateTo(Z);if(X)throw console.error(X),X;if(!Y)return[];if(!Q$(Y))throw TypeError("Reverse migration appears to have succeeded but failed to parse received results!");return Y}import v$ from"fs";import hJ from"path";function S9(W){let $=hJ.resolve(W);if(!v$.existsSync($))throw Error(`Env file not found: ${$}`);let Z=v$.readFileSync($,"utf-8");for(let J of Z.split(`
56
+ `)){let X=J.trim();if(!X||X.startsWith("#"))continue;let Y=X.indexOf("=");if(Y===-1)continue;let M=X.slice(0,Y).trim(),G=X.slice(Y+1).trim();if(G.startsWith('"')&&G.endsWith('"')||G.startsWith("'")&&G.endsWith("'"))G=G.slice(1,-1);if(process.env[M]===void 0)process.env[M]=G}}var NJ=fJ(import.meta.url),{version:E$}=NJ("../package.json");if(typeof E$!=="string")throw TypeError("Failed to resolve 'version' from @schemavaults/dbh package.json file!");var HW=new i9;HW.name("dbh").description("@schemavaults/dbh CLI — database migration tools").version(E$);HW.command("migrate").description("Run database migrations forward (to latest or a specific version)").argument("<folder>","Path to the migration folder").argument("[version]","Target migration version (defaults to latest)").requiredOption("-e, --environment <environment>","App environment (development|test|staging|production)").option("--ws-proxy-url <url>","Custom WebSocket proxy URL").option("--env-file <path>","Path to env file to load (e.g. .env)").action(async(W,$,Z)=>{if(Z.envFile)S9(Z.envFile);let J=i4.resolve(W),X=new p4({environment:Z.environment,wsProxyUrl:Z.wsProxyUrl});try{let Y=await S$({db:X.db,migrationFolder:J,version:$});for(let M of Y)console.log(`[${M.direction}] ${M.migrationName}: ${M.status}`);if(Y.length===0)console.log("No migrations to run.")}catch(Y){console.error("Migration failed:",Y),process.exit(1)}finally{await X.destroy()}});HW.command("reverse").description("Roll back database migrations to a specific version").argument("<folder>","Path to the migration folder").argument("<version>","Target version to roll back to").requiredOption("-e, --environment <environment>","App environment (development|test|staging|production)").option("--ws-proxy-url <url>","Custom WebSocket proxy URL").option("--env-file <path>","Path to env file to load (e.g. .env)").action(async(W,$,Z)=>{if(Z.envFile)S9(Z.envFile);let J=i4.resolve(W),X=new p4({environment:Z.environment,wsProxyUrl:Z.wsProxyUrl});try{let Y=await _$({db:X.db,migrationFolder:J,version:$});for(let M of Y)console.log(`[${M.direction}] ${M.migrationName}: ${M.status}`);if(Y.length===0)console.log("No migrations to reverse.")}catch(Y){console.error("Reverse migration failed:",Y),process.exit(1)}finally{await X.destroy()}});HW.command("build-db-migrations").description("Build TypeScript Kysely migration files into JavaScript using Bun's bundler").argument("<migrations-src>","Directory containing .ts migration source files").requiredOption("--outdir <dir>","Output directory for compiled migration .js files").requiredOption("--sql-module <path>","Path to sql.ts source module to build alongside").option("--sql-outdir <dir>","Output directory for the built sql.js module (defaults to parent of --outdir)").option("--external <pkg...>","Packages to keep external in the bundle (default: @schemavaults/dbh, kysely)").option("--debug","Enable debug logging").action(async(W,$)=>{try{jJ("bun --version",{stdio:"ignore"})}catch{console.error("Error: 'bun' is required for build-db-migrations but was not found in PATH."),process.exit(1)}let Z=i4.dirname(TJ(import.meta.url)),X=["run",i4.resolve(Z,"build-db-migrations.js"),W];if(X.push("--outdir",$.outdir),X.push("--sql-module",$.sqlModule),$.sqlOutdir)X.push("--sql-outdir",$.sqlOutdir);if($.external&&$.external.length>0)X.push("--external",...$.external);if($.debug)X.push("--debug");AJ("bun",X,{stdio:"inherit",cwd:process.cwd()}).on("close",(M)=>{process.exit(M??1)})});var TS=HW;HW.parse();export{TS as default};