@turbobase/cli 1.1.12 → 1.1.14

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.
@@ -1,46 +1,47 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __tbCreateRequire } from 'node:module';
3
3
  const require = __tbCreateRequire(import.meta.url);
4
- var rk=Object.create;var Pc=Object.defineProperty;var nk=Object.getOwnPropertyDescriptor;var ok=Object.getOwnPropertyNames;var sk=Object.getPrototypeOf,ik=Object.prototype.hasOwnProperty;var zo=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var O=(t,e)=>()=>(t&&(e=t(t=0)),e);var U=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),No=(t,e)=>{for(var r in e)Pc(t,r,{get:e[r],enumerable:!0})},ak=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ok(e))!ik.call(t,o)&&o!==r&&Pc(t,o,{get:()=>e[o],enumerable:!(n=nk(e,o))||n.enumerable});return t};var Ac=(t,e,r)=>(r=t!=null?rk(sk(t)):{},ak(e||!t||!t.__esModule?Pc(r,"default",{value:t,enumerable:!0}):r,t));var jo=U(Oc=>{var ai=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},Ic=class extends ai{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Oc.CommanderError=ai;Oc.InvalidArgumentError=Ic});var ci=U(zc=>{var{InvalidArgumentError:ck}=jo(),Cc=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new ck(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function lk(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}zc.Argument=Cc;zc.humanReadableArgName=lk});var jc=U(lm=>{var{humanReadableArgName:uk}=ci(),Nc=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden);if(e._hasImplicitHelpCommand()){let[,n,o]=e._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/),s=e.createCommand(n).helpOption(!1);s.description(e._helpCommandDescription),o&&s.arguments(o),r.push(s)}return this.sortSubcommands&&r.sort((n,o)=>n.name().localeCompare(o.name())),r}compareOptions(e,r){let n=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._hasHelpOption&&e._helpShortFlag&&!e._findOption(e._helpShortFlag),o=e._hasHelpOption&&!e._findOption(e._helpLongFlag);if(n||o){let s;n?o?s=e.createOption(e._helpFlags,e._helpDescription):s=e.createOption(e._helpShortFlag,e._helpDescription):s=e.createOption(e._helpLongFlag,e._helpDescription),r.push(s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let o=n.options.filter(s=>!s.hidden);r.push(...o)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>uk(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,o)=>Math.max(n,r.subcommandTerm(o).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,o)=>Math.max(n,r.argumentTerm(o).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let o=e.parent;o;o=o.parent)n=o.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),o=r.helpWidth||80,s=2,i=2;function a(f,g){if(g){let w=`${f.padEnd(n+i)}${g}`;return r.wrap(w,o-s,n+i)}return f}function c(f){return f.join(`
5
- `).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(l=l.concat([r.wrap(u,o,0),""]));let d=r.visibleArguments(e).map(f=>a(r.argumentTerm(f),r.argumentDescription(f)));d.length>0&&(l=l.concat(["Arguments:",c(d),""]));let y=r.visibleOptions(e).map(f=>a(r.optionTerm(f),r.optionDescription(f)));if(y.length>0&&(l=l.concat(["Options:",c(y),""])),this.showGlobalOptions){let f=r.visibleGlobalOptions(e).map(g=>a(r.optionTerm(g),r.optionDescription(g)));f.length>0&&(l=l.concat(["Global Options:",c(f),""]))}let h=r.visibleCommands(e).map(f=>a(r.subcommandTerm(f),r.subcommandDescription(f)));return h.length>0&&(l=l.concat(["Commands:",c(h),""])),l.join(`
4
+ var sk=Object.create;var Ac=Object.defineProperty;var ik=Object.getOwnPropertyDescriptor;var ak=Object.getOwnPropertyNames;var ck=Object.getPrototypeOf,lk=Object.prototype.hasOwnProperty;var No=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var O=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),jo=(t,e)=>{for(var r in e)Ac(t,r,{get:e[r],enumerable:!0})},uk=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ak(e))!lk.call(t,o)&&o!==r&&Ac(t,o,{get:()=>e[o],enumerable:!(n=ik(e,o))||n.enumerable});return t};var Ic=(t,e,r)=>(r=t!=null?sk(ck(t)):{},uk(e||!t||!t.__esModule?Ac(r,"default",{value:t,enumerable:!0}):r,t));var Lo=Z(Cc=>{var ai=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},Oc=class extends ai{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Cc.CommanderError=ai;Cc.InvalidArgumentError=Oc});var ci=Z(Nc=>{var{InvalidArgumentError:dk}=Lo(),zc=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new dk(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function pk(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Nc.Argument=zc;Nc.humanReadableArgName=pk});var Lc=Z(dm=>{var{humanReadableArgName:fk}=ci(),jc=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden);if(e._hasImplicitHelpCommand()){let[,n,o]=e._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/),s=e.createCommand(n).helpOption(!1);s.description(e._helpCommandDescription),o&&s.arguments(o),r.push(s)}return this.sortSubcommands&&r.sort((n,o)=>n.name().localeCompare(o.name())),r}compareOptions(e,r){let n=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._hasHelpOption&&e._helpShortFlag&&!e._findOption(e._helpShortFlag),o=e._hasHelpOption&&!e._findOption(e._helpLongFlag);if(n||o){let s;n?o?s=e.createOption(e._helpFlags,e._helpDescription):s=e.createOption(e._helpShortFlag,e._helpDescription):s=e.createOption(e._helpLongFlag,e._helpDescription),r.push(s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let o=n.options.filter(s=>!s.hidden);r.push(...o)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>fk(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,o)=>Math.max(n,r.subcommandTerm(o).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,o)=>Math.max(n,r.argumentTerm(o).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let o=e.parent;o;o=o.parent)n=o.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),o=r.helpWidth||80,s=2,i=2;function a(f,y){if(y){let v=`${f.padEnd(n+i)}${y}`;return r.wrap(v,o-s,n+i)}return f}function c(f){return f.join(`
5
+ `).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(l=l.concat([r.wrap(u,o,0),""]));let d=r.visibleArguments(e).map(f=>a(r.argumentTerm(f),r.argumentDescription(f)));d.length>0&&(l=l.concat(["Arguments:",c(d),""]));let b=r.visibleOptions(e).map(f=>a(r.optionTerm(f),r.optionDescription(f)));if(b.length>0&&(l=l.concat(["Options:",c(b),""])),this.showGlobalOptions){let f=r.visibleGlobalOptions(e).map(y=>a(r.optionTerm(y),r.optionDescription(y)));f.length>0&&(l=l.concat(["Global Options:",c(f),""]))}let h=r.visibleCommands(e).map(f=>a(r.subcommandTerm(f),r.subcommandDescription(f)));return h.length>0&&(l=l.concat(["Commands:",c(h),""])),l.join(`
6
6
  `)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,o=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",i=new RegExp(`[\\n][${s}]+`);if(e.match(i))return e;let a=r-n;if(a<o)return e;let c=e.slice(0,n),l=e.slice(n).replace(`\r
7
7
  `,`
8
- `),u=" ".repeat(n),y="\\s\u200B",h=new RegExp(`
9
- |.{1,${a-1}}([${y}]|$)|[^${y}]+?([${y}]|$)`,"g"),f=l.match(h)||[];return c+f.map((g,w)=>g===`
10
- `?"":(w>0?u:"")+g.trimEnd()).join(`
11
- `)}};lm.Help=Nc});var Dc=U(li=>{var{InvalidArgumentError:dk}=jo(),Lc=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=um(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new dk(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return pk(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Mc=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let o=this.negativeOptions.get(n).presetArg,s=o!==void 0?o:!1;return r.negate===(s===e)}};function pk(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function um(t){let e,r,n=t.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),r=n.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}li.Option=Lc;li.splitOptionFlags=um;li.DualOptions=Mc});var pm=U(dm=>{function fk(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let o=1;o<=t.length;o++){let s=1;t[o-1]===e[n-1]?s=0:s=1,r[o][n]=Math.min(r[o-1][n]+1,r[o][n-1]+1,r[o-1][n-1]+s),o>1&&n>1&&t[o-1]===e[n-2]&&t[o-2]===e[n-1]&&(r[o][n]=Math.min(r[o][n],r[o-2][n-2]+1))}return r[t.length][e.length]}function hk(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(i=>i.slice(2)));let n=[],o=3,s=.4;return e.forEach(i=>{if(i.length<=1)return;let a=fk(t,i),c=Math.max(t.length,i.length);(c-a)/c>s&&(a<o?(o=a,n=[i]):a===o&&n.push(i))}),n.sort((i,a)=>i.localeCompare(a)),r&&(n=n.map(i=>`--${i}`)),n.length>1?`
8
+ `),u=" ".repeat(n),b="\\s\u200B",h=new RegExp(`
9
+ |.{1,${a-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),f=l.match(h)||[];return c+f.map((y,v)=>y===`
10
+ `?"":(v>0?u:"")+y.trimEnd()).join(`
11
+ `)}};dm.Help=jc});var Uc=Z(li=>{var{InvalidArgumentError:hk}=Lo(),Mc=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=pm(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new hk(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return mk(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Dc=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let o=this.negativeOptions.get(n).presetArg,s=o!==void 0?o:!1;return r.negate===(s===e)}};function mk(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function pm(t){let e,r,n=t.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),r=n.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}li.Option=Mc;li.splitOptionFlags=pm;li.DualOptions=Dc});var hm=Z(fm=>{function gk(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let o=1;o<=t.length;o++){let s=1;t[o-1]===e[n-1]?s=0:s=1,r[o][n]=Math.min(r[o-1][n]+1,r[o][n-1]+1,r[o-1][n-1]+s),o>1&&n>1&&t[o-1]===e[n-2]&&t[o-2]===e[n-1]&&(r[o][n]=Math.min(r[o][n],r[o-2][n-2]+1))}return r[t.length][e.length]}function yk(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(i=>i.slice(2)));let n=[],o=3,s=.4;return e.forEach(i=>{if(i.length<=1)return;let a=gk(t,i),c=Math.max(t.length,i.length);(c-a)/c>s&&(a<o?(o=a,n=[i]):a===o&&n.push(i))}),n.sort((i,a)=>i.localeCompare(a)),r&&(n=n.map(i=>`--${i}`)),n.length>1?`
12
12
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
13
- (Did you mean ${n[0]}?)`:""}dm.suggestSimilar=hk});var bm=U(ym=>{var mk=zo("events").EventEmitter,Uc=zo("child_process"),fr=zo("path"),Zc=zo("fs"),Le=zo("process"),{Argument:gk,humanReadableArgName:yk}=ci(),{CommanderError:qc}=jo(),{Help:bk}=jc(),{Option:fm,splitOptionFlags:_k,DualOptions:wk}=Dc(),{suggestSimilar:hm}=pm(),Fc=class t extends mk{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>Le.stdout.write(r),writeErr:r=>Le.stderr.write(r),getOutHelpWidth:()=>Le.stdout.isTTY?Le.stdout.columns:void 0,getErrHelpWidth:()=>Le.stderr.isTTY?Le.stderr.columns:void 0,outputError:(r,n)=>n(r)},this._hidden=!1,this._hasHelpOption=!0,this._helpFlags="-h, --help",this._helpDescription="display help for command",this._helpShortFlag="-h",this._helpLongFlag="--help",this._addImplicitHelpCommand=void 0,this._helpCommandName="help",this._helpCommandnameAndArgs="help [command]",this._helpCommandDescription="display help for command",this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._hasHelpOption=e._hasHelpOption,this._helpFlags=e._helpFlags,this._helpDescription=e._helpDescription,this._helpShortFlag=e._helpShortFlag,this._helpLongFlag=e._helpLongFlag,this._helpCommandName=e._helpCommandName,this._helpCommandnameAndArgs=e._helpCommandnameAndArgs,this._helpCommandDescription=e._helpCommandDescription,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let o=r,s=n;typeof o=="object"&&o!==null&&(s=o,o=null),s=s||{};let[,i,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(i);return o&&(c.description(o),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this.commands.push(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new bk,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
14
- - specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this.commands.push(e),e.parent=this,this}createArgument(e,r){return new gk(e,r)}argument(e,r,n,o){let s=this.createArgument(e,r);return typeof n=="function"?s.default(o).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}addHelpCommand(e,r){return e===!1?this._addImplicitHelpCommand=!1:(this._addImplicitHelpCommand=!0,typeof e=="string"&&(this._helpCommandName=e.split(" ")[0],this._helpCommandnameAndArgs=e),this._helpCommandDescription=r||this._helpCommandDescription),this}_hasImplicitHelpCommand(){return this._addImplicitHelpCommand===void 0?this.commands.length&&!this._actionHandler&&!this._findCommand("help"):this._addImplicitHelpCommand}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
15
- Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new qc(e,r,n)),Le.exit(e)}action(e){let r=n=>{let o=this.registeredArguments.length,s=n.slice(0,o);return this._storeOptionsAsProperties?s[o]=this:s[o]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=r,this}createOption(e,r){return new fm(e,r)}_callParseArg(e,r,n,o){try{return e.parseArg(r,n)}catch(s){if(s.code==="commander.invalidArgument"){let i=`${o} ${s.message}`;this.error(i,{exitCode:s.exitCode,code:s.code})}throw s}}addOption(e){let r=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");this.options.push(e);let o=(s,i,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,i):s!==null&&e.variadic&&(s=e._concatValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+r,s=>{let i=`error: option '${e.flags}' argument '${s}' is invalid.`;o(s,i,"cli")}),e.envVar&&this.on("optionEnv:"+r,s=>{let i=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;o(s,i,"env")}),this}_optionEx(e,r,n,o,s){if(typeof r=="object"&&r instanceof fm)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(r,n);if(i.makeOptionMandatory(!!e.mandatory),typeof o=="function")i.default(s).argParser(o);else if(o instanceof RegExp){let a=o;o=(c,l)=>{let u=a.exec(c);return u?u[0]:l},i.default(s).argParser(o)}else i.default(o);return this.addOption(i)}option(e,r,n,o){return this._optionEx({},e,r,n,o)}requiredOption(e,r,n,o){return this._optionEx({mandatory:!0},e,r,n,o)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){if(this._passThroughOptions=!!e,this.parent&&e&&!this.parent._enablePositionalOptions)throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");return this}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");r=r||{},e===void 0&&(e=Le.argv,Le.versions&&Le.versions.electron&&(r.from="electron")),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":Le.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,d){let y=fr.resolve(u,d);if(Zc.existsSync(y))return y;if(o.includes(fr.extname(d)))return;let h=o.find(f=>Zc.existsSync(`${y}${f}`));if(h)return`${y}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Zc.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=fr.resolve(fr.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let d=fr.basename(this._scriptPath,fr.extname(this._scriptPath));d!==this._name&&(u=s(a,`${d}-${e._name}`))}i=u||i}n=o.includes(fr.extname(i));let c;Le.platform!=="win32"?n?(r.unshift(i),r=gm(Le.execArgv).concat(r),c=Uc.spawn(Le.argv[0],r,{stdio:"inherit"})):c=Uc.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=gm(Le.execArgv).concat(r),c=Uc.spawn(Le.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{Le.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let l=this._exitCallback;l?c.on("close",()=>{l(new qc(Le.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",Le.exit.bind(Le)),c.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",y=`'${i}' does not exist
13
+ (Did you mean ${n[0]}?)`:""}fm.suggestSimilar=yk});var _m=Z(wm=>{var bk=No("events").EventEmitter,Zc=No("child_process"),hr=No("path"),qc=No("fs"),Me=No("process"),{Argument:wk,humanReadableArgName:_k}=ci(),{CommanderError:Fc}=Lo(),{Help:vk}=Lc(),{Option:mm,splitOptionFlags:xk,DualOptions:$k}=Uc(),{suggestSimilar:gm}=hm(),Bc=class t extends bk{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>Me.stdout.write(r),writeErr:r=>Me.stderr.write(r),getOutHelpWidth:()=>Me.stdout.isTTY?Me.stdout.columns:void 0,getErrHelpWidth:()=>Me.stderr.isTTY?Me.stderr.columns:void 0,outputError:(r,n)=>n(r)},this._hidden=!1,this._hasHelpOption=!0,this._helpFlags="-h, --help",this._helpDescription="display help for command",this._helpShortFlag="-h",this._helpLongFlag="--help",this._addImplicitHelpCommand=void 0,this._helpCommandName="help",this._helpCommandnameAndArgs="help [command]",this._helpCommandDescription="display help for command",this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._hasHelpOption=e._hasHelpOption,this._helpFlags=e._helpFlags,this._helpDescription=e._helpDescription,this._helpShortFlag=e._helpShortFlag,this._helpLongFlag=e._helpLongFlag,this._helpCommandName=e._helpCommandName,this._helpCommandnameAndArgs=e._helpCommandnameAndArgs,this._helpCommandDescription=e._helpCommandDescription,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let o=r,s=n;typeof o=="object"&&o!==null&&(s=o,o=null),s=s||{};let[,i,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(i);return o&&(c.description(o),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this.commands.push(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new vk,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
14
+ - specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this.commands.push(e),e.parent=this,this}createArgument(e,r){return new wk(e,r)}argument(e,r,n,o){let s=this.createArgument(e,r);return typeof n=="function"?s.default(o).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}addHelpCommand(e,r){return e===!1?this._addImplicitHelpCommand=!1:(this._addImplicitHelpCommand=!0,typeof e=="string"&&(this._helpCommandName=e.split(" ")[0],this._helpCommandnameAndArgs=e),this._helpCommandDescription=r||this._helpCommandDescription),this}_hasImplicitHelpCommand(){return this._addImplicitHelpCommand===void 0?this.commands.length&&!this._actionHandler&&!this._findCommand("help"):this._addImplicitHelpCommand}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
15
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new Fc(e,r,n)),Me.exit(e)}action(e){let r=n=>{let o=this.registeredArguments.length,s=n.slice(0,o);return this._storeOptionsAsProperties?s[o]=this:s[o]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=r,this}createOption(e,r){return new mm(e,r)}_callParseArg(e,r,n,o){try{return e.parseArg(r,n)}catch(s){if(s.code==="commander.invalidArgument"){let i=`${o} ${s.message}`;this.error(i,{exitCode:s.exitCode,code:s.code})}throw s}}addOption(e){let r=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");this.options.push(e);let o=(s,i,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,i):s!==null&&e.variadic&&(s=e._concatValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+r,s=>{let i=`error: option '${e.flags}' argument '${s}' is invalid.`;o(s,i,"cli")}),e.envVar&&this.on("optionEnv:"+r,s=>{let i=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;o(s,i,"env")}),this}_optionEx(e,r,n,o,s){if(typeof r=="object"&&r instanceof mm)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(r,n);if(i.makeOptionMandatory(!!e.mandatory),typeof o=="function")i.default(s).argParser(o);else if(o instanceof RegExp){let a=o;o=(c,l)=>{let u=a.exec(c);return u?u[0]:l},i.default(s).argParser(o)}else i.default(o);return this.addOption(i)}option(e,r,n,o){return this._optionEx({},e,r,n,o)}requiredOption(e,r,n,o){return this._optionEx({mandatory:!0},e,r,n,o)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){if(this._passThroughOptions=!!e,this.parent&&e&&!this.parent._enablePositionalOptions)throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");return this}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");r=r||{},e===void 0&&(e=Me.argv,Me.versions&&Me.versions.electron&&(r.from="electron")),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":Me.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,d){let b=hr.resolve(u,d);if(qc.existsSync(b))return b;if(o.includes(hr.extname(d)))return;let h=o.find(f=>qc.existsSync(`${b}${f}`));if(h)return`${b}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=qc.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=hr.resolve(hr.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let d=hr.basename(this._scriptPath,hr.extname(this._scriptPath));d!==this._name&&(u=s(a,`${d}-${e._name}`))}i=u||i}n=o.includes(hr.extname(i));let c;Me.platform!=="win32"?n?(r.unshift(i),r=bm(Me.execArgv).concat(r),c=Zc.spawn(Me.argv[0],r,{stdio:"inherit"})):c=Zc.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=bm(Me.execArgv).concat(r),c=Zc.spawn(Me.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{Me.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let l=this._exitCallback;l?c.on("close",()=>{l(new Fc(Me.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",Me.exit.bind(Me)),c.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",b=`'${i}' does not exist
16
16
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
- - ${d}`;throw new Error(y)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Le.exit(1);else{let d=new qc(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,r,n){let o=this._findCommand(e);o||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,o,"preSubcommand"),s=this._chainOrCall(s,()=>{if(o._executableHandler)this._executeSubCommand(o,r.concat(n));else return o._parseCommand(r,n)}),s}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._helpLongFlag||this._helpShortFlag])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,o,s)=>{let i=o;if(o!==null&&n.parseArg){let a=`error: command-argument value '${o}' is invalid for argument '${n.name()}'.`;i=this._callParseArg(n,o,s,a)}return i};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,o)=>{let s=n.defaultValue;n.variadic?o<this.args.length?(s=this.args.slice(o),n.parseArg&&(s=s.reduce((i,a)=>e(n,a,i),n.defaultValue))):s===void 0&&(s=[]):o<this.args.length&&(s=this.args[o],n.parseArg&&(s=e(n,s,n.defaultValue))),r[o]=s}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,o=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[r]!==void 0).forEach(s=>{s._lifeCycleHooks[r].forEach(i=>{o.push({hookedCommand:s,callback:i})})}),r==="postAction"&&o.reverse(),o.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let o=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{o=this._chainOrCall(o,()=>s(this,r))}),o}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._hasImplicitHelpCommand()&&e[0]===this._helpCommandName)return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return mm(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),mm(this,n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(s,e,r)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let o=n.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let o=e.find(s=>n.conflictsWith.includes(s.attributeName()));o&&this._conflictingOption(n,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],o=r,s=e.slice();function i(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){o===n&&o.push(c),o.push(...s);break}if(a&&!i(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,i(c)){let l=this._findOption(c);if(l){if(l.required){let u=s.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;s.length>0&&!i(s[0])&&(u=s.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(i(c)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(c)){r.push(c),s.length>0&&n.push(...s);break}else if(c===this._helpCommandName&&this._hasImplicitHelpCommand()){r.push(c),s.length>0&&r.push(...s);break}else if(this._defaultCommandName){n.push(c),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){o.push(c),s.length>0&&o.push(...s);break}o.push(c)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let o=this.options[n].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
18
+ - ${d}`;throw new Error(b)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Me.exit(1);else{let d=new Fc(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,r,n){let o=this._findCommand(e);o||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,o,"preSubcommand"),s=this._chainOrCall(s,()=>{if(o._executableHandler)this._executeSubCommand(o,r.concat(n));else return o._parseCommand(r,n)}),s}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._helpLongFlag||this._helpShortFlag])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,o,s)=>{let i=o;if(o!==null&&n.parseArg){let a=`error: command-argument value '${o}' is invalid for argument '${n.name()}'.`;i=this._callParseArg(n,o,s,a)}return i};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,o)=>{let s=n.defaultValue;n.variadic?o<this.args.length?(s=this.args.slice(o),n.parseArg&&(s=s.reduce((i,a)=>e(n,a,i),n.defaultValue))):s===void 0&&(s=[]):o<this.args.length&&(s=this.args[o],n.parseArg&&(s=e(n,s,n.defaultValue))),r[o]=s}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,o=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[r]!==void 0).forEach(s=>{s._lifeCycleHooks[r].forEach(i=>{o.push({hookedCommand:s,callback:i})})}),r==="postAction"&&o.reverse(),o.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let o=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{o=this._chainOrCall(o,()=>s(this,r))}),o}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._hasImplicitHelpCommand()&&e[0]===this._helpCommandName)return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return ym(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),ym(this,n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(s,e,r)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let o=n.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let o=e.find(s=>n.conflictsWith.includes(s.attributeName()));o&&this._conflictingOption(n,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],o=r,s=e.slice();function i(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){o===n&&o.push(c),o.push(...s);break}if(a&&!i(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,i(c)){let l=this._findOption(c);if(l){if(l.required){let u=s.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;s.length>0&&!i(s[0])&&(u=s.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(i(c)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(c)){r.push(c),s.length>0&&n.push(...s);break}else if(c===this._helpCommandName&&this._hasImplicitHelpCommand()){r.push(c),s.length>0&&r.push(...s);break}else if(this._defaultCommandName){n.push(c),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){o.push(c),s.length>0&&o.push(...s);break}o.push(c)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let o=this.options[n].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
19
19
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
20
20
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
21
- `),this.outputHelp({error:!0}));let n=r||{},o=n.exitCode||1,s=n.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in Le.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,Le.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new wk(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(o=>!r(o)).forEach(o=>{this.setOptionValueWithSource(o,n.implied[o],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=i=>{let a=i.attributeName(),c=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||i},o=i=>{let a=n(i),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${o(e)} cannot be used with ${o(r)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],s=this;do{let i=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);o=o.concat(i),s=s.parent}while(s&&!s._enablePositionalOptions);r=hm(e,o)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(s=>{o.push(s.name()),s.alias()&&o.push(s.alias())}),r=hm(e,o)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let o=this.createOption(r,n);return this._versionOptionName=o.attributeName(),this.options.push(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
22
- `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>yk(n));return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=fr.basename(e,fr.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=o=>this._outputConfiguration.writeErr(o):n=o=>this._outputConfiguration.writeOut(o),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let o=this.helpInformation(n);if(r&&(o=r(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._helpLongFlag&&this.emit(this._helpLongFlag),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(e,r){if(typeof e=="boolean")return this._hasHelpOption=e,this;this._helpFlags=e||this._helpFlags,this._helpDescription=r||this._helpDescription;let n=_k(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let r=Le.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
21
+ `),this.outputHelp({error:!0}));let n=r||{},o=n.exitCode||1,s=n.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in Me.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,Me.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new $k(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(o=>!r(o)).forEach(o=>{this.setOptionValueWithSource(o,n.implied[o],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=i=>{let a=i.attributeName(),c=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||i},o=i=>{let a=n(i),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${o(e)} cannot be used with ${o(r)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],s=this;do{let i=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);o=o.concat(i),s=s.parent}while(s&&!s._enablePositionalOptions);r=gm(e,o)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(s=>{o.push(s.name()),s.alias()&&o.push(s.alias())}),r=gm(e,o)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let o=this.createOption(r,n);return this._versionOptionName=o.attributeName(),this.options.push(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
22
+ `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>_k(n));return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=hr.basename(e,hr.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=o=>this._outputConfiguration.writeErr(o):n=o=>this._outputConfiguration.writeOut(o),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let o=this.helpInformation(n);if(r&&(o=r(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._helpLongFlag&&this.emit(this._helpLongFlag),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(e,r){if(typeof e=="boolean")return this._hasHelpOption=e,this;this._helpFlags=e||this._helpFlags,this._helpDescription=r||this._helpDescription;let n=xk(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let r=Me.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
23
23
  Expecting one of '${n.join("', '")}'`);let o=`${e}Help`;return this.on(o,s=>{let i;typeof r=="function"?i=r({error:s.error,command:s.command}):i=r,i&&s.write(`${i}
24
- `)}),this}};function mm(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function gm(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",o="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?r=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=s[1],/^\d+$/.test(s[3])?o=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=s[1],n=s[3],o=s[4]),r&&o!=="0"?`${r}=${n}:${parseInt(o)+1}`:e})}ym.Command=Fc});var xm=U((Vt,vm)=>{var{Argument:vk}=ci(),{Command:_m}=bm(),{CommanderError:xk,InvalidArgumentError:wm}=jo(),{Help:$k}=jc(),{Option:kk}=Dc();Vt=vm.exports=new _m;Vt.program=Vt;Vt.Command=_m;Vt.Option=kk;Vt.Argument=vk;Vt.Help=$k;Vt.CommanderError=xk;Vt.InvalidArgumentError=wm;Vt.InvalidOptionArgumentError=wm});function Lo(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var ui=O(()=>{});var pe,Bc,q,tr,Mo=O(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(pe||(pe={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Bc||(Bc={}));q=pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tr=t=>{switch(typeof t){case"undefined":return q.undefined;case"string":return q.string;case"number":return Number.isNaN(t)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(t)?q.array:t===null?q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?q.promise:typeof Map<"u"&&t instanceof Map?q.map:typeof Set<"u"&&t instanceof Set?q.set:typeof Date<"u"&&t instanceof Date?q.date:q.object;default:return q.unknown}}});var N,Sk,mt,di=O(()=>{Mo();N=pe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Sk=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),mt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};mt.create=t=>new mt(t)});var Tk,hr,Vc=O(()=>{di();Mo();Tk=(t,e)=>{let r;switch(t.code){case N.invalid_type:t.received===q.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,pe.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:r=`Unrecognized key(s) in object: ${pe.joinValues(t.keys,", ")}`;break;case N.invalid_union:r="Invalid input";break;case N.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${pe.joinValues(t.options)}`;break;case N.invalid_enum_value:r=`Invalid enum value. Expected ${pe.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:r="Invalid function arguments";break;case N.invalid_return_type:r="Invalid function return type";break;case N.invalid_date:r="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:pe.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case N.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case N.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case N.custom:r="Invalid input";break;case N.invalid_intersection_types:r="Intersection results could not be merged";break;case N.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:r="Number must be finite";break;default:r=e.defaultError,pe.assertNever(t)}return{message:r}},hr=Tk});function Ek(t){Sm=t}function Dn(){return Sm}var Sm,pi=O(()=>{Vc();Sm=hr});function Z(t,e){let r=Dn(),n=Do({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===hr?void 0:hr].filter(o=>!!o)});t.common.issues.push(n)}var Do,Rk,Qe,Y,tn,st,fi,hi,Rr,Un,Hc=O(()=>{pi();Vc();Do=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},Rk=[];Qe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return Y;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return Y;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},Y=Object.freeze({status:"aborted"}),tn=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),fi=t=>t.status==="aborted",hi=t=>t.status==="dirty",Rr=t=>t.status==="valid",Un=t=>typeof Promise<"u"&&t instanceof Promise});var Tm=O(()=>{});var V,Em=O(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(V||(V={}))});function ne(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function Im(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Vk(t){return new RegExp(`^${Im(t)}$`)}function Om(t){let e=`${Am}T${Im(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Hk(t,e){return!!((e==="v4"||!e)&&Mk.test(t)||(e==="v6"||!e)&&Uk.test(t))}function Kk(t,e){if(!zk.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Gk(t,e){return!!((e==="v4"||!e)&&Dk.test(t)||(e==="v6"||!e)&&Zk.test(t))}function Wk(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Zn(t){if(t instanceof yt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=gt.create(Zn(n))}return new yt({...t._def,shape:()=>e})}else return t instanceof yr?new yr({...t._def,type:Zn(t.element)}):t instanceof gt?gt.create(Zn(t.unwrap())):t instanceof nr?nr.create(Zn(t.unwrap())):t instanceof rr?rr.create(t.items.map(e=>Zn(e))):t}function Gc(t,e){let r=tr(t),n=tr(e);if(t===e)return{valid:!0,data:t};if(r===q.object&&n===q.object){let o=pe.objectKeys(e),s=pe.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Gc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===q.array&&n===q.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Gc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===q.date&&n===q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Cm(t,e){return new fn({values:t,typeName:L.ZodEnum,...ne(e)})}function Pm(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function zm(t,e={},r){return t?Ar.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Pm(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Pm(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Ar.create()}var At,Rm,ie,Pk,Ak,Ik,Ok,Ck,zk,Nk,jk,Lk,Kc,Mk,Dk,Uk,Zk,qk,Fk,Am,Bk,Pr,rn,nn,on,sn,qn,an,cn,Ar,gr,Ht,Fn,yr,yt,ln,mr,mi,un,rr,gi,Bn,Vn,yi,dn,pn,fn,hn,Ir,It,gt,nr,mn,gn,Hn,Jk,Uo,Zo,yn,Yk,L,Xk,Nm,jm,Qk,eS,Lm,tS,rS,nS,oS,sS,iS,aS,cS,lS,Wc,uS,dS,pS,fS,hS,mS,gS,yS,bS,_S,wS,vS,xS,$S,kS,SS,TS,ES,RS,PS,AS,IS,OS,CS,Mm=O(()=>{di();pi();Em();Hc();Mo();At=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Rm=(t,e)=>{if(Rr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new mt(t.common.issues);return this._error=r,this._error}}};ie=class{get description(){return this._def.description}_getType(e){return tr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:tr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Qe,ctx:{common:e.parent.common,data:e.data,parsedType:tr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Un(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Rm(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Rr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Rr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Un(o)?o:Promise.resolve(o));return Rm(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:N.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new It({schema:this,typeName:L.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return gt.create(this,this._def)}nullable(){return nr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return yr.create(this)}promise(){return Ir.create(this,this._def)}or(e){return ln.create([this,e],this._def)}and(e){return un.create(this,e,this._def)}transform(e){return new It({...ne(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new mn({...ne(this._def),innerType:this,defaultValue:r,typeName:L.ZodDefault})}brand(){return new Uo({typeName:L.ZodBranded,type:this,...ne(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new gn({...ne(this._def),innerType:this,catchValue:r,typeName:L.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Zo.create(this,e)}readonly(){return yn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Pk=/^c[^\s-]{8,}$/i,Ak=/^[0-9a-z]+$/,Ik=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ok=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ck=/^[a-z0-9_-]{21}$/i,zk=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Nk=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,jk=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Lk="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Mk=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Dk=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Uk=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Zk=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,qk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Am="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Bk=new RegExp(`^${Am}$`);Pr=class t extends ie{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){let s=this._getOrReturnCtx(e);return Z(s,{code:N.invalid_type,expected:q.string,received:s.parsedType}),Y}let n=new Qe,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?Z(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Z(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")jk.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"email",code:N.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Kc||(Kc=new RegExp(Lk,"u")),Kc.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"emoji",code:N.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Ok.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"uuid",code:N.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Ck.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"nanoid",code:N.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Pk.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid",code:N.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Ak.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid2",code:N.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Ik.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ulid",code:N.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),Z(o,{validation:"url",code:N.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"regex",code:N.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),Z(o,{code:N.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:N.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:N.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Om(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:N.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Bk.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:N.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Vk(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:N.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Nk.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"duration",code:N.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Hk(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ip",code:N.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Kk(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"jwt",code:N.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Gk(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cidr",code:N.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?qk.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64",code:N.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Fk.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64url",code:N.invalid_string,message:s.message}),n.dirty()):pe.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:N.invalid_string,...V.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...V.errToObj(e)})}url(e){return this._addCheck({kind:"url",...V.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...V.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...V.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...V.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...V.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...V.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...V.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...V.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...V.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...V.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...V.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...V.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...V.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...V.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...V.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...V.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...V.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...V.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...V.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...V.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...V.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...V.errToObj(r)})}nonempty(e){return this.min(1,V.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Pr.create=t=>new Pr({checks:[],typeName:L.ZodString,coerce:t?.coerce??!1,...ne(t)});rn=class t extends ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==q.number){let s=this._getOrReturnCtx(e);return Z(s,{code:N.invalid_type,expected:q.number,received:s.parsedType}),Y}let n,o=new Qe;for(let s of this._def.checks)s.kind==="int"?pe.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:N.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:N.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:N.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Wk(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Z(n,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:N.not_finite,message:s.message}),o.dirty()):pe.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:V.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:V.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:V.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&pe.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};rn.create=t=>new rn({checks:[],typeName:L.ZodNumber,coerce:t?.coerce||!1,...ne(t)});nn=class t extends ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==q.bigint)return this._getInvalidInput(e);let n,o=new Qe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:N.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:N.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):pe.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Z(r,{code:N.invalid_type,expected:q.bigint,received:r.parsedType}),Y}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:V.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};nn.create=t=>new nn({checks:[],typeName:L.ZodBigInt,coerce:t?.coerce??!1,...ne(t)});on=class extends ie{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){let n=this._getOrReturnCtx(e);return Z(n,{code:N.invalid_type,expected:q.boolean,received:n.parsedType}),Y}return st(e.data)}};on.create=t=>new on({typeName:L.ZodBoolean,coerce:t?.coerce||!1,...ne(t)});sn=class t extends ie{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){let s=this._getOrReturnCtx(e);return Z(s,{code:N.invalid_type,expected:q.date,received:s.parsedType}),Y}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Z(s,{code:N.invalid_date}),Y}let n=new Qe,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:N.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:N.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):pe.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:V.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:V.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};sn.create=t=>new sn({checks:[],coerce:t?.coerce||!1,typeName:L.ZodDate,...ne(t)});qn=class extends ie{_parse(e){if(this._getType(e)!==q.symbol){let n=this._getOrReturnCtx(e);return Z(n,{code:N.invalid_type,expected:q.symbol,received:n.parsedType}),Y}return st(e.data)}};qn.create=t=>new qn({typeName:L.ZodSymbol,...ne(t)});an=class extends ie{_parse(e){if(this._getType(e)!==q.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:N.invalid_type,expected:q.undefined,received:n.parsedType}),Y}return st(e.data)}};an.create=t=>new an({typeName:L.ZodUndefined,...ne(t)});cn=class extends ie{_parse(e){if(this._getType(e)!==q.null){let n=this._getOrReturnCtx(e);return Z(n,{code:N.invalid_type,expected:q.null,received:n.parsedType}),Y}return st(e.data)}};cn.create=t=>new cn({typeName:L.ZodNull,...ne(t)});Ar=class extends ie{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}};Ar.create=t=>new Ar({typeName:L.ZodAny,...ne(t)});gr=class extends ie{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}};gr.create=t=>new gr({typeName:L.ZodUnknown,...ne(t)});Ht=class extends ie{_parse(e){let r=this._getOrReturnCtx(e);return Z(r,{code:N.invalid_type,expected:q.never,received:r.parsedType}),Y}};Ht.create=t=>new Ht({typeName:L.ZodNever,...ne(t)});Fn=class extends ie{_parse(e){if(this._getType(e)!==q.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:N.invalid_type,expected:q.void,received:n.parsedType}),Y}return st(e.data)}};Fn.create=t=>new Fn({typeName:L.ZodVoid,...ne(t)});yr=class t extends ie{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==q.array)return Z(r,{code:N.invalid_type,expected:q.array,received:r.parsedType}),Y;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(Z(r,{code:i?N.too_big:N.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(Z(r,{code:N.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(Z(r,{code:N.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new At(r,i,r.path,a)))).then(i=>Qe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new At(r,i,r.path,a)));return Qe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:V.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:V.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:V.toString(r)}})}nonempty(e){return this.min(1,e)}};yr.create=(t,e)=>new yr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...ne(e)});yt=class t extends ie{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=pe.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==q.object){let l=this._getOrReturnCtx(e);return Z(l,{code:N.invalid_type,expected:q.object,received:l.parsedType}),Y}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ht&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new At(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Ht){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(Z(o,{code:N.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new At(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,y=await u.value;l.push({key:d,value:y,alwaysSet:u.alwaysSet})}return l}).then(l=>Qe.mergeObjectSync(n,l)):Qe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return V.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:V.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:L.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of pe.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of pe.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Zn(this)}partial(e){let r={};for(let n of pe.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of pe.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof gt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Cm(pe.objectKeys(this.shape))}};yt.create=(t,e)=>new yt({shape:()=>t,unknownKeys:"strip",catchall:Ht.create(),typeName:L.ZodObject,...ne(e)});yt.strictCreate=(t,e)=>new yt({shape:()=>t,unknownKeys:"strict",catchall:Ht.create(),typeName:L.ZodObject,...ne(e)});yt.lazycreate=(t,e)=>new yt({shape:t,unknownKeys:"strip",catchall:Ht.create(),typeName:L.ZodObject,...ne(e)});ln=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new mt(a.ctx.common.issues));return Z(r,{code:N.invalid_union,unionErrors:i}),Y}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new mt(c));return Z(r,{code:N.invalid_union,unionErrors:a}),Y}}get options(){return this._def.options}};ln.create=(t,e)=>new ln({options:t,typeName:L.ZodUnion,...ne(e)});mr=t=>t instanceof dn?mr(t.schema):t instanceof It?mr(t.innerType()):t instanceof pn?[t.value]:t instanceof fn?t.options:t instanceof hn?pe.objectValues(t.enum):t instanceof mn?mr(t._def.innerType):t instanceof an?[void 0]:t instanceof cn?[null]:t instanceof gt?[void 0,...mr(t.unwrap())]:t instanceof nr?[null,...mr(t.unwrap())]:t instanceof Uo||t instanceof yn?mr(t.unwrap()):t instanceof gn?mr(t._def.innerType):[],mi=class t extends ie{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.object)return Z(r,{code:N.invalid_type,expected:q.object,received:r.parsedType}),Y;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Z(r,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=mr(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:L.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ne(n)})}};un=class extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(fi(s)||fi(i))return Y;let a=Gc(s.value,i.value);return a.valid?((hi(s)||hi(i))&&r.dirty(),{status:r.value,value:a.data}):(Z(n,{code:N.invalid_intersection_types}),Y)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};un.create=(t,e,r)=>new un({left:t,right:e,typeName:L.ZodIntersection,...ne(r)});rr=class t extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.array)return Z(n,{code:N.invalid_type,expected:q.array,received:n.parsedType}),Y;if(n.data.length<this._def.items.length)return Z(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y;!this._def.rest&&n.data.length>this._def.items.length&&(Z(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new At(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Qe.mergeArray(r,i)):Qe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};rr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rr({items:t,typeName:L.ZodTuple,rest:null,...ne(e)})};gi=class t extends ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.object)return Z(n,{code:N.invalid_type,expected:q.object,received:n.parsedType}),Y;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new At(n,a,n.path,a)),value:i._parse(new At(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Qe.mergeObjectAsync(r,o):Qe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ie?new t({keyType:e,valueType:r,typeName:L.ZodRecord,...ne(n)}):new t({keyType:Pr.create(),valueType:e,typeName:L.ZodRecord,...ne(r)})}},Bn=class extends ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.map)return Z(n,{code:N.invalid_type,expected:q.map,received:n.parsedType}),Y;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new At(n,a,n.path,[l,"key"])),value:s._parse(new At(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return Y;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return Y;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};Bn.create=(t,e,r)=>new Bn({valueType:e,keyType:t,typeName:L.ZodMap,...ne(r)});Vn=class t extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.set)return Z(n,{code:N.invalid_type,expected:q.set,received:n.parsedType}),Y;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(Z(n,{code:N.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(Z(n,{code:N.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return Y;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>s._parse(new At(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:V.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:V.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Vn.create=(t,e)=>new Vn({valueType:t,minSize:null,maxSize:null,typeName:L.ZodSet,...ne(e)});yi=class t extends ie{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.function)return Z(r,{code:N.invalid_type,expected:q.function,received:r.parsedType}),Y;function n(a,c){return Do({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Dn(),hr].filter(l=>!!l),issueData:{code:N.invalid_arguments,argumentsError:c}})}function o(a,c){return Do({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Dn(),hr].filter(l=>!!l),issueData:{code:N.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Ir){let a=this;return st(async function(...c){let l=new mt([]),u=await a._def.args.parseAsync(c,s).catch(h=>{throw l.addIssue(n(c,h)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw l.addIssue(o(d,h)),l})})}else{let a=this;return st(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new mt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new mt([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:rr.create(e).rest(gr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||rr.create([]).rest(gr.create()),returns:r||gr.create(),typeName:L.ZodFunction,...ne(n)})}},dn=class extends ie{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};dn.create=(t,e)=>new dn({getter:t,typeName:L.ZodLazy,...ne(e)});pn=class extends ie{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Z(r,{received:r.data,code:N.invalid_literal,expected:this._def.value}),Y}return{status:"valid",value:e.data}}get value(){return this._def.value}};pn.create=(t,e)=>new pn({value:t,typeName:L.ZodLiteral,...ne(e)});fn=class t extends ie{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{expected:pe.joinValues(n),received:r.parsedType,code:N.invalid_type}),Y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{received:r.data,code:N.invalid_enum_value,options:n}),Y}return st(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};fn.create=Cm;hn=class extends ie{_parse(e){let r=pe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==q.string&&n.parsedType!==q.number){let o=pe.objectValues(r);return Z(n,{expected:pe.joinValues(o),received:n.parsedType,code:N.invalid_type}),Y}if(this._cache||(this._cache=new Set(pe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=pe.objectValues(r);return Z(n,{received:n.data,code:N.invalid_enum_value,options:o}),Y}return st(e.data)}get enum(){return this._def.values}};hn.create=(t,e)=>new hn({values:t,typeName:L.ZodNativeEnum,...ne(e)});Ir=class extends ie{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.promise&&r.common.async===!1)return Z(r,{code:N.invalid_type,expected:q.promise,received:r.parsedType}),Y;let n=r.parsedType===q.promise?r.data:Promise.resolve(r.data);return st(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ir.create=(t,e)=>new Ir({type:t,typeName:L.ZodPromise,...ne(e)});It=class extends ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{Z(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return Y;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?Y:c.status==="dirty"?tn(c.value):r.value==="dirty"?tn(c.value):c});{if(r.value==="aborted")return Y;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?Y:a.status==="dirty"?tn(a.value):r.value==="dirty"?tn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Y:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?Y:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Rr(i))return Y;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Rr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):Y);pe.assertNever(o)}};It.create=(t,e,r)=>new It({schema:t,typeName:L.ZodEffects,effect:e,...ne(r)});It.createWithPreprocess=(t,e,r)=>new It({schema:e,effect:{type:"preprocess",transform:t},typeName:L.ZodEffects,...ne(r)});gt=class extends ie{_parse(e){return this._getType(e)===q.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(t,e)=>new gt({innerType:t,typeName:L.ZodOptional,...ne(e)});nr=class extends ie{_parse(e){return this._getType(e)===q.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};nr.create=(t,e)=>new nr({innerType:t,typeName:L.ZodNullable,...ne(e)});mn=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===q.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};mn.create=(t,e)=>new mn({innerType:t,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ne(e)});gn=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Un(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new mt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new mt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};gn.create=(t,e)=>new gn({innerType:t,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ne(e)});Hn=class extends ie{_parse(e){if(this._getType(e)!==q.nan){let n=this._getOrReturnCtx(e);return Z(n,{code:N.invalid_type,expected:q.nan,received:n.parsedType}),Y}return{status:"valid",value:e.data}}};Hn.create=t=>new Hn({typeName:L.ZodNaN,...ne(t)});Jk=Symbol("zod_brand"),Uo=class extends ie{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Zo=class t extends ie{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Y:s.status==="dirty"?(r.dirty(),tn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Y:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:L.ZodPipeline})}},yn=class extends ie{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Rr(o)&&(o.value=Object.freeze(o.value)),o);return Un(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};yn.create=(t,e)=>new yn({innerType:t,typeName:L.ZodReadonly,...ne(e)});Yk={object:yt.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(L||(L={}));Xk=(t,e={message:`Input not instance of ${t.name}`})=>zm(r=>r instanceof t,e),Nm=Pr.create,jm=rn.create,Qk=Hn.create,eS=nn.create,Lm=on.create,tS=sn.create,rS=qn.create,nS=an.create,oS=cn.create,sS=Ar.create,iS=gr.create,aS=Ht.create,cS=Fn.create,lS=yr.create,Wc=yt.create,uS=yt.strictCreate,dS=ln.create,pS=mi.create,fS=un.create,hS=rr.create,mS=gi.create,gS=Bn.create,yS=Vn.create,bS=yi.create,_S=dn.create,wS=pn.create,vS=fn.create,xS=hn.create,$S=Ir.create,kS=It.create,SS=gt.create,TS=nr.create,ES=It.createWithPreprocess,RS=Zo.create,PS=()=>Nm().optional(),AS=()=>jm().optional(),IS=()=>Lm().optional(),OS={string:(t=>Pr.create({...t,coerce:!0})),number:(t=>rn.create({...t,coerce:!0})),boolean:(t=>on.create({...t,coerce:!0})),bigint:(t=>nn.create({...t,coerce:!0})),date:(t=>sn.create({...t,coerce:!0}))},CS=Y});var z={};No(z,{BRAND:()=>Jk,DIRTY:()=>tn,EMPTY_PATH:()=>Rk,INVALID:()=>Y,NEVER:()=>CS,OK:()=>st,ParseStatus:()=>Qe,Schema:()=>ie,ZodAny:()=>Ar,ZodArray:()=>yr,ZodBigInt:()=>nn,ZodBoolean:()=>on,ZodBranded:()=>Uo,ZodCatch:()=>gn,ZodDate:()=>sn,ZodDefault:()=>mn,ZodDiscriminatedUnion:()=>mi,ZodEffects:()=>It,ZodEnum:()=>fn,ZodError:()=>mt,ZodFirstPartyTypeKind:()=>L,ZodFunction:()=>yi,ZodIntersection:()=>un,ZodIssueCode:()=>N,ZodLazy:()=>dn,ZodLiteral:()=>pn,ZodMap:()=>Bn,ZodNaN:()=>Hn,ZodNativeEnum:()=>hn,ZodNever:()=>Ht,ZodNull:()=>cn,ZodNullable:()=>nr,ZodNumber:()=>rn,ZodObject:()=>yt,ZodOptional:()=>gt,ZodParsedType:()=>q,ZodPipeline:()=>Zo,ZodPromise:()=>Ir,ZodReadonly:()=>yn,ZodRecord:()=>gi,ZodSchema:()=>ie,ZodSet:()=>Vn,ZodString:()=>Pr,ZodSymbol:()=>qn,ZodTransformer:()=>It,ZodTuple:()=>rr,ZodType:()=>ie,ZodUndefined:()=>an,ZodUnion:()=>ln,ZodUnknown:()=>gr,ZodVoid:()=>Fn,addIssueToContext:()=>Z,any:()=>sS,array:()=>lS,bigint:()=>eS,boolean:()=>Lm,coerce:()=>OS,custom:()=>zm,date:()=>tS,datetimeRegex:()=>Om,defaultErrorMap:()=>hr,discriminatedUnion:()=>pS,effect:()=>kS,enum:()=>vS,function:()=>bS,getErrorMap:()=>Dn,getParsedType:()=>tr,instanceof:()=>Xk,intersection:()=>fS,isAborted:()=>fi,isAsync:()=>Un,isDirty:()=>hi,isValid:()=>Rr,late:()=>Yk,lazy:()=>_S,literal:()=>wS,makeIssue:()=>Do,map:()=>gS,nan:()=>Qk,nativeEnum:()=>xS,never:()=>aS,null:()=>oS,nullable:()=>TS,number:()=>jm,object:()=>Wc,objectUtil:()=>Bc,oboolean:()=>IS,onumber:()=>AS,optional:()=>SS,ostring:()=>PS,pipeline:()=>RS,preprocess:()=>ES,promise:()=>$S,quotelessJson:()=>Sk,record:()=>mS,set:()=>yS,setErrorMap:()=>Ek,strictObject:()=>uS,string:()=>Nm,symbol:()=>rS,transformer:()=>kS,tuple:()=>hS,undefined:()=>nS,union:()=>dS,unknown:()=>iS,util:()=>pe,void:()=>cS});var bi=O(()=>{pi();Hc();Tm();Mo();Mm();di()});var Kn=O(()=>{bi();bi()});function _i(t){let e=Jc.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Yc(t,e){let r=Jc.safeParse(t);if(!r.success)throw new Or(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Dm.test(e))throw new Or('a literal connection_id is baked into the bundle source \u2014 connection binding is an install-time input, not a published value. Declare an inputs[] entry { type: "connection", source_system } instead.');let n=JSON.stringify(r.data);if(Dm.test(n))throw new Or("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Um,Zm,Jc,Or,Dm,qm=O(()=>{Kn();Um=z.object({type:z.literal("connection"),source_system:z.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:z.string().min(1).max(200).optional()}),Zm=z.discriminatedUnion("type",[Um]),Jc=z.object({inputs:z.array(Zm).optional()}).passthrough(),Or=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Dm=/\bconnection[_-]?id\b["']?\s*[:=]/i});var wi,Xc=O(()=>{wi=["before_read","before_save","after_save","before_sync","after_sync","on_sync_failure"]});var Qc,Fm,Bm=O(()=>{Kn();ui();Xc();Qc=z.object({id:z.string().min(1,"hook id must be non-empty"),recordType:z.union([z.string().min(1),z.array(z.string().min(1)).min(1),z.literal("*")]),event:z.enum(wi),source:z.string().min(1).optional(),when:z.unknown().optional(),run:z.unknown(),failClosed:z.boolean().optional(),timeoutMs:z.number().int().positive().optional(),description:z.string().optional(),systemReserved:z.boolean().optional()}).superRefine((t,e)=>{typeof t.run!="function"&&e.addIssue({code:"custom",path:["run"],message:"run must be a function"}),"when"in t&&t.when!==void 0&&typeof t.when!="function"&&e.addIssue({code:"custom",path:["when"],message:"when, when present, must be a function"})}),Fm=Lo({kind:"hook",schema:Qc,factoryName:"defineHook"})});var Vm=O(()=>{Bm();Xc()});var vi,el=O(()=>{vi=["after_canonicalize_inbound","after_sync_success_outbound"]});var tl,Hm,Km=O(()=>{Kn();ui();el();tl=z.object({id:z.string().min(1,"conduit id must be non-empty"),on:z.enum(vi),from:z.object({source:z.string().min(1,"from.source must be non-empty"),recordType:z.string().min(1,"from.recordType must be non-empty"),when:z.unknown().optional()}),to:z.object({source:z.string().min(1,"to.source must be non-empty"),recordType:z.string().min(1,"to.recordType must be non-empty")}),mode:z.enum(["dual-bind","one-shot"]).optional(),transform:z.unknown(),idempotencyKey:z.unknown().optional(),cycleBudget:z.number().int().positive().optional(),conflictStrategy:z.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:z.number().int().positive().optional(),description:z.string().optional(),systemReserved:z.boolean().optional()}).superRefine((t,e)=>{typeof t.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"});let r=t.from?.when;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let n=t.idempotencyKey;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let o=t.from,s=t.to;o?.source&&s?.source&&o.source===s.source&&e.addIssue({code:"custom",path:["to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})}),Hm=Lo({kind:"conduit",schema:tl,factoryName:"defineConduit"})});var Gm=O(()=>{Km();el()});async function MS(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let r=await e.default(t,{defaultNonNullable:!1});return e.astToString(r)}async function xi(t,e={}){return(e.transform??MS)(t)}var rl=O(()=>{});function nl(t){switch(t.toLowerCase().trim()){case"boolean":return"boolean";case"smallint":case"integer":case"bigint":case"numeric":case"decimal":case"real":case"double precision":return"number";case"text":case"character varying":case"character":case"varchar":case"char":case"uuid":case"name":case"citext":return"string";case"timestamp with time zone":case"timestamp without time zone":case"timestamp":case"date":case"time":case"time with time zone":case"time without time zone":return"string";case"json":case"jsonb":return"unknown";case"array":return"unknown[]";default:return"unknown"}}function Wm(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function ol(t){return`${Wm(t.source)}${Wm(t.recordType)}`}function DS(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function US(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function sl(t){let e=ol(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
24
+ `)}),this}};function ym(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function bm(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",o="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?r=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=s[1],/^\d+$/.test(s[3])?o=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=s[1],n=s[3],o=s[4]),r&&o!=="0"?`${r}=${n}:${parseInt(o)+1}`:e})}wm.Command=Bc});var km=Z((Bt,$m)=>{var{Argument:kk}=ci(),{Command:vm}=_m(),{CommanderError:Sk,InvalidArgumentError:xm}=Lo(),{Help:Tk}=Lc(),{Option:Ek}=Uc();Bt=$m.exports=new vm;Bt.program=Bt;Bt.Command=vm;Bt.Option=Ek;Bt.Argument=kk;Bt.Help=Tk;Bt.CommanderError=Sk;Bt.InvalidArgumentError=xm;Bt.InvalidOptionArgumentError=xm});function Mo(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var ui=O(()=>{});var he,Vc,F,tr,Do=O(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(he||(he={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Vc||(Vc={}));F=he.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tr=t=>{switch(typeof t){case"undefined":return F.undefined;case"string":return F.string;case"number":return Number.isNaN(t)?F.nan:F.number;case"boolean":return F.boolean;case"function":return F.function;case"bigint":return F.bigint;case"symbol":return F.symbol;case"object":return Array.isArray(t)?F.array:t===null?F.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?F.promise:typeof Map<"u"&&t instanceof Map?F.map:typeof Set<"u"&&t instanceof Set?F.set:typeof Date<"u"&&t instanceof Date?F.date:F.object;default:return F.unknown}}});var j,Rk,mt,di=O(()=>{Do();j=he.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Rk=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),mt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,he.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};mt.create=t=>new mt(t)});var Pk,mr,Hc=O(()=>{di();Do();Pk=(t,e)=>{let r;switch(t.code){case j.invalid_type:t.received===F.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case j.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,he.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:r=`Unrecognized key(s) in object: ${he.joinValues(t.keys,", ")}`;break;case j.invalid_union:r="Invalid input";break;case j.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${he.joinValues(t.options)}`;break;case j.invalid_enum_value:r=`Invalid enum value. Expected ${he.joinValues(t.options)}, received '${t.received}'`;break;case j.invalid_arguments:r="Invalid function arguments";break;case j.invalid_return_type:r="Invalid function return type";break;case j.invalid_date:r="Invalid date";break;case j.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:he.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case j.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case j.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case j.custom:r="Invalid input";break;case j.invalid_intersection_types:r="Intersection results could not be merged";break;case j.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case j.not_finite:r="Number must be finite";break;default:r=e.defaultError,he.assertNever(t)}return{message:r}},mr=Pk});function Ak(t){Em=t}function qn(){return Em}var Em,pi=O(()=>{Hc();Em=mr});function q(t,e){let r=qn(),n=Uo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===mr?void 0:mr].filter(o=>!!o)});t.common.issues.push(n)}var Uo,Ik,Qe,X,rn,st,fi,hi,Pr,Fn,Kc=O(()=>{pi();Hc();Uo=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},Ik=[];Qe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return X;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return X;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},X=Object.freeze({status:"aborted"}),rn=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),fi=t=>t.status==="aborted",hi=t=>t.status==="dirty",Pr=t=>t.status==="valid",Fn=t=>typeof Promise<"u"&&t instanceof Promise});var Rm=O(()=>{});var H,Pm=O(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(H||(H={}))});function ie(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function Cm(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Gk(t){return new RegExp(`^${Cm(t)}$`)}function zm(t){let e=`${Om}T${Cm(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Wk(t,e){return!!((e==="v4"||!e)&&Zk.test(t)||(e==="v6"||!e)&&Fk.test(t))}function Jk(t,e){if(!Lk.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Yk(t,e){return!!((e==="v4"||!e)&&qk.test(t)||(e==="v6"||!e)&&Bk.test(t))}function Xk(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Bn(t){if(t instanceof yt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=gt.create(Bn(n))}return new yt({...t._def,shape:()=>e})}else return t instanceof br?new br({...t._def,type:Bn(t.element)}):t instanceof gt?gt.create(Bn(t.unwrap())):t instanceof nr?nr.create(Bn(t.unwrap())):t instanceof rr?rr.create(t.items.map(e=>Bn(e))):t}function Wc(t,e){let r=tr(t),n=tr(e);if(t===e)return{valid:!0,data:t};if(r===F.object&&n===F.object){let o=he.objectKeys(e),s=he.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Wc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===F.array&&n===F.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Wc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===F.date&&n===F.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Nm(t,e){return new hn({values:t,typeName:M.ZodEnum,...ie(e)})}function Im(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function jm(t,e={},r){return t?Ir.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Im(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Im(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Ir.create()}var At,Am,ce,Ok,Ck,zk,Nk,jk,Lk,Mk,Dk,Uk,Gc,Zk,qk,Fk,Bk,Vk,Hk,Om,Kk,Ar,nn,on,sn,an,Vn,cn,ln,Ir,yr,Vt,Hn,br,yt,un,gr,mi,dn,rr,gi,Kn,Gn,yi,pn,fn,hn,mn,Or,It,gt,nr,gn,yn,Wn,Qk,Zo,qo,bn,eS,M,tS,Lm,Mm,rS,nS,Dm,oS,sS,iS,aS,cS,lS,uS,dS,pS,Jc,fS,hS,mS,gS,yS,bS,wS,_S,vS,xS,$S,kS,SS,TS,ES,RS,PS,AS,IS,OS,CS,zS,NS,jS,Um=O(()=>{di();pi();Pm();Kc();Do();At=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Am=(t,e)=>{if(Pr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new mt(t.common.issues);return this._error=r,this._error}}};ce=class{get description(){return this._def.description}_getType(e){return tr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:tr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Qe,ctx:{common:e.parent.common,data:e.data,parsedType:tr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Fn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Am(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Pr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Pr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Fn(o)?o:Promise.resolve(o));return Am(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:j.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new It({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return gt.create(this,this._def)}nullable(){return nr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return br.create(this)}promise(){return Or.create(this,this._def)}or(e){return un.create([this,e],this._def)}and(e){return dn.create(this,e,this._def)}transform(e){return new It({...ie(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new gn({...ie(this._def),innerType:this,defaultValue:r,typeName:M.ZodDefault})}brand(){return new Zo({typeName:M.ZodBranded,type:this,...ie(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new yn({...ie(this._def),innerType:this,catchValue:r,typeName:M.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return qo.create(this,e)}readonly(){return bn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ok=/^c[^\s-]{8,}$/i,Ck=/^[0-9a-z]+$/,zk=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Nk=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,jk=/^[a-z0-9_-]{21}$/i,Lk=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Mk=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Dk=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Uk="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zk=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qk=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Fk=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Bk=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Vk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Om="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Kk=new RegExp(`^${Om}$`);Ar=class t extends ce{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==F.string){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_type,expected:F.string,received:s.parsedType}),X}let n=new Qe,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?q(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&q(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Dk.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"email",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Gc||(Gc=new RegExp(Uk,"u")),Gc.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"emoji",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Nk.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"uuid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")jk.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"nanoid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Ok.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Ck.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cuid2",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")zk.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ulid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),q(o,{validation:"url",code:j.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"regex",code:j.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?zm(s).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Kk.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Gk(s).test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{code:j.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Mk.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"duration",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Wk(e.data,s.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"ip",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Jk(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"jwt",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Yk(e.data,s.version)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"cidr",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Vk.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Hk.test(e.data)||(o=this._getOrReturnCtx(e,o),q(o,{validation:"base64url",code:j.invalid_string,message:s.message}),n.dirty()):he.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:j.invalid_string,...H.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...H.errToObj(e)})}url(e){return this._addCheck({kind:"url",...H.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...H.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...H.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...H.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...H.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...H.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...H.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...H.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...H.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...H.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...H.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...H.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...H.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...H.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...H.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...H.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...H.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...H.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...H.errToObj(r)})}nonempty(e){return this.min(1,H.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ar.create=t=>new Ar({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...ie(t)});nn=class t extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==F.number){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_type,expected:F.number,received:s.parsedType}),X}let n,o=new Qe;for(let s of this._def.checks)s.kind==="int"?he.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),q(n,{code:j.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Xk(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),q(n,{code:j.not_finite,message:s.message}),o.dirty()):he.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,H.toString(r))}gt(e,r){return this.setLimit("min",e,!1,H.toString(r))}lte(e,r){return this.setLimit("max",e,!0,H.toString(r))}lt(e,r){return this.setLimit("max",e,!1,H.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:H.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:H.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:H.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:H.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:H.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:H.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&he.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};nn.create=t=>new nn({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...ie(t)});on=class t extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==F.bigint)return this._getInvalidInput(e);let n,o=new Qe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),q(n,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):he.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return q(r,{code:j.invalid_type,expected:F.bigint,received:r.parsedType}),X}gte(e,r){return this.setLimit("min",e,!0,H.toString(r))}gt(e,r){return this.setLimit("min",e,!1,H.toString(r))}lte(e,r){return this.setLimit("max",e,!0,H.toString(r))}lt(e,r){return this.setLimit("max",e,!1,H.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:H.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:H.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};on.create=t=>new on({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...ie(t)});sn=class extends ce{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==F.boolean){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.boolean,received:n.parsedType}),X}return st(e.data)}};sn.create=t=>new sn({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...ie(t)});an=class t extends ce{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==F.date){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_type,expected:F.date,received:s.parsedType}),X}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return q(s,{code:j.invalid_date}),X}let n=new Qe,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),q(o,{code:j.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):he.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:H.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:H.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};an.create=t=>new an({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...ie(t)});Vn=class extends ce{_parse(e){if(this._getType(e)!==F.symbol){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.symbol,received:n.parsedType}),X}return st(e.data)}};Vn.create=t=>new Vn({typeName:M.ZodSymbol,...ie(t)});cn=class extends ce{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.undefined,received:n.parsedType}),X}return st(e.data)}};cn.create=t=>new cn({typeName:M.ZodUndefined,...ie(t)});ln=class extends ce{_parse(e){if(this._getType(e)!==F.null){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.null,received:n.parsedType}),X}return st(e.data)}};ln.create=t=>new ln({typeName:M.ZodNull,...ie(t)});Ir=class extends ce{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}};Ir.create=t=>new Ir({typeName:M.ZodAny,...ie(t)});yr=class extends ce{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}};yr.create=t=>new yr({typeName:M.ZodUnknown,...ie(t)});Vt=class extends ce{_parse(e){let r=this._getOrReturnCtx(e);return q(r,{code:j.invalid_type,expected:F.never,received:r.parsedType}),X}};Vt.create=t=>new Vt({typeName:M.ZodNever,...ie(t)});Hn=class extends ce{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.void,received:n.parsedType}),X}return st(e.data)}};Hn.create=t=>new Hn({typeName:M.ZodVoid,...ie(t)});br=class t extends ce{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==F.array)return q(r,{code:j.invalid_type,expected:F.array,received:r.parsedType}),X;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(q(r,{code:i?j.too_big:j.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(q(r,{code:j.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(q(r,{code:j.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new At(r,i,r.path,a)))).then(i=>Qe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new At(r,i,r.path,a)));return Qe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:H.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:H.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:H.toString(r)}})}nonempty(e){return this.min(1,e)}};br.create=(t,e)=>new br({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...ie(e)});yt=class t extends ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=he.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==F.object){let l=this._getOrReturnCtx(e);return q(l,{code:j.invalid_type,expected:F.object,received:l.parsedType}),X}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Vt&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new At(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Vt){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(q(o,{code:j.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new At(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,b=await u.value;l.push({key:d,value:b,alwaysSet:u.alwaysSet})}return l}).then(l=>Qe.mergeObjectSync(n,l)):Qe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return H.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:H.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:M.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of he.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of he.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Bn(this)}partial(e){let r={};for(let n of he.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of he.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof gt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Nm(he.objectKeys(this.shape))}};yt.create=(t,e)=>new yt({shape:()=>t,unknownKeys:"strip",catchall:Vt.create(),typeName:M.ZodObject,...ie(e)});yt.strictCreate=(t,e)=>new yt({shape:()=>t,unknownKeys:"strict",catchall:Vt.create(),typeName:M.ZodObject,...ie(e)});yt.lazycreate=(t,e)=>new yt({shape:t,unknownKeys:"strip",catchall:Vt.create(),typeName:M.ZodObject,...ie(e)});un=class extends ce{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new mt(a.ctx.common.issues));return q(r,{code:j.invalid_union,unionErrors:i}),X}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new mt(c));return q(r,{code:j.invalid_union,unionErrors:a}),X}}get options(){return this._def.options}};un.create=(t,e)=>new un({options:t,typeName:M.ZodUnion,...ie(e)});gr=t=>t instanceof pn?gr(t.schema):t instanceof It?gr(t.innerType()):t instanceof fn?[t.value]:t instanceof hn?t.options:t instanceof mn?he.objectValues(t.enum):t instanceof gn?gr(t._def.innerType):t instanceof cn?[void 0]:t instanceof ln?[null]:t instanceof gt?[void 0,...gr(t.unwrap())]:t instanceof nr?[null,...gr(t.unwrap())]:t instanceof Zo||t instanceof bn?gr(t.unwrap()):t instanceof yn?gr(t._def.innerType):[],mi=class t extends ce{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.object)return q(r,{code:j.invalid_type,expected:F.object,received:r.parsedType}),X;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(q(r,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),X)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=gr(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:M.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ie(n)})}};dn=class extends ce{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(fi(s)||fi(i))return X;let a=Wc(s.value,i.value);return a.valid?((hi(s)||hi(i))&&r.dirty(),{status:r.value,value:a.data}):(q(n,{code:j.invalid_intersection_types}),X)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};dn.create=(t,e,r)=>new dn({left:t,right:e,typeName:M.ZodIntersection,...ie(r)});rr=class t extends ce{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.array)return q(n,{code:j.invalid_type,expected:F.array,received:n.parsedType}),X;if(n.data.length<this._def.items.length)return q(n,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X;!this._def.rest&&n.data.length>this._def.items.length&&(q(n,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new At(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Qe.mergeArray(r,i)):Qe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};rr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rr({items:t,typeName:M.ZodTuple,rest:null,...ie(e)})};gi=class t extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.object)return q(n,{code:j.invalid_type,expected:F.object,received:n.parsedType}),X;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new At(n,a,n.path,a)),value:i._parse(new At(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Qe.mergeObjectAsync(r,o):Qe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ce?new t({keyType:e,valueType:r,typeName:M.ZodRecord,...ie(n)}):new t({keyType:Ar.create(),valueType:e,typeName:M.ZodRecord,...ie(r)})}},Kn=class extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.map)return q(n,{code:j.invalid_type,expected:F.map,received:n.parsedType}),X;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new At(n,a,n.path,[l,"key"])),value:s._parse(new At(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return X;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return X;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};Kn.create=(t,e,r)=>new Kn({valueType:e,keyType:t,typeName:M.ZodMap,...ie(r)});Gn=class t extends ce{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.set)return q(n,{code:j.invalid_type,expected:F.set,received:n.parsedType}),X;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(q(n,{code:j.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(q(n,{code:j.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return X;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>s._parse(new At(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:H.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:H.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Gn.create=(t,e)=>new Gn({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...ie(e)});yi=class t extends ce{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.function)return q(r,{code:j.invalid_type,expected:F.function,received:r.parsedType}),X;function n(a,c){return Uo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qn(),mr].filter(l=>!!l),issueData:{code:j.invalid_arguments,argumentsError:c}})}function o(a,c){return Uo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qn(),mr].filter(l=>!!l),issueData:{code:j.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Or){let a=this;return st(async function(...c){let l=new mt([]),u=await a._def.args.parseAsync(c,s).catch(h=>{throw l.addIssue(n(c,h)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw l.addIssue(o(d,h)),l})})}else{let a=this;return st(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new mt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new mt([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:rr.create(e).rest(yr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||rr.create([]).rest(yr.create()),returns:r||yr.create(),typeName:M.ZodFunction,...ie(n)})}},pn=class extends ce{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};pn.create=(t,e)=>new pn({getter:t,typeName:M.ZodLazy,...ie(e)});fn=class extends ce{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return q(r,{received:r.data,code:j.invalid_literal,expected:this._def.value}),X}return{status:"valid",value:e.data}}get value(){return this._def.value}};fn.create=(t,e)=>new fn({value:t,typeName:M.ZodLiteral,...ie(e)});hn=class t extends ce{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return q(r,{expected:he.joinValues(n),received:r.parsedType,code:j.invalid_type}),X}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return q(r,{received:r.data,code:j.invalid_enum_value,options:n}),X}return st(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};hn.create=Nm;mn=class extends ce{_parse(e){let r=he.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==F.string&&n.parsedType!==F.number){let o=he.objectValues(r);return q(n,{expected:he.joinValues(o),received:n.parsedType,code:j.invalid_type}),X}if(this._cache||(this._cache=new Set(he.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=he.objectValues(r);return q(n,{received:n.data,code:j.invalid_enum_value,options:o}),X}return st(e.data)}get enum(){return this._def.values}};mn.create=(t,e)=>new mn({values:t,typeName:M.ZodNativeEnum,...ie(e)});Or=class extends ce{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.promise&&r.common.async===!1)return q(r,{code:j.invalid_type,expected:F.promise,received:r.parsedType}),X;let n=r.parsedType===F.promise?r.data:Promise.resolve(r.data);return st(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Or.create=(t,e)=>new Or({type:t,typeName:M.ZodPromise,...ie(e)});It=class extends ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{q(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return X;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?X:c.status==="dirty"?rn(c.value):r.value==="dirty"?rn(c.value):c});{if(r.value==="aborted")return X;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?X:a.status==="dirty"?rn(a.value):r.value==="dirty"?rn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?X:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?X:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Pr(i))return X;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Pr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):X);he.assertNever(o)}};It.create=(t,e,r)=>new It({schema:t,typeName:M.ZodEffects,effect:e,...ie(r)});It.createWithPreprocess=(t,e,r)=>new It({schema:e,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...ie(r)});gt=class extends ce{_parse(e){return this._getType(e)===F.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(t,e)=>new gt({innerType:t,typeName:M.ZodOptional,...ie(e)});nr=class extends ce{_parse(e){return this._getType(e)===F.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};nr.create=(t,e)=>new nr({innerType:t,typeName:M.ZodNullable,...ie(e)});gn=class extends ce{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===F.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};gn.create=(t,e)=>new gn({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ie(e)});yn=class extends ce{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Fn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new mt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new mt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};yn.create=(t,e)=>new yn({innerType:t,typeName:M.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ie(e)});Wn=class extends ce{_parse(e){if(this._getType(e)!==F.nan){let n=this._getOrReturnCtx(e);return q(n,{code:j.invalid_type,expected:F.nan,received:n.parsedType}),X}return{status:"valid",value:e.data}}};Wn.create=t=>new Wn({typeName:M.ZodNaN,...ie(t)});Qk=Symbol("zod_brand"),Zo=class extends ce{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},qo=class t extends ce{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?X:s.status==="dirty"?(r.dirty(),rn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?X:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:M.ZodPipeline})}},bn=class extends ce{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Pr(o)&&(o.value=Object.freeze(o.value)),o);return Fn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};bn.create=(t,e)=>new bn({innerType:t,typeName:M.ZodReadonly,...ie(e)});eS={object:yt.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(M||(M={}));tS=(t,e={message:`Input not instance of ${t.name}`})=>jm(r=>r instanceof t,e),Lm=Ar.create,Mm=nn.create,rS=Wn.create,nS=on.create,Dm=sn.create,oS=an.create,sS=Vn.create,iS=cn.create,aS=ln.create,cS=Ir.create,lS=yr.create,uS=Vt.create,dS=Hn.create,pS=br.create,Jc=yt.create,fS=yt.strictCreate,hS=un.create,mS=mi.create,gS=dn.create,yS=rr.create,bS=gi.create,wS=Kn.create,_S=Gn.create,vS=yi.create,xS=pn.create,$S=fn.create,kS=hn.create,SS=mn.create,TS=Or.create,ES=It.create,RS=gt.create,PS=nr.create,AS=It.createWithPreprocess,IS=qo.create,OS=()=>Lm().optional(),CS=()=>Mm().optional(),zS=()=>Dm().optional(),NS={string:(t=>Ar.create({...t,coerce:!0})),number:(t=>nn.create({...t,coerce:!0})),boolean:(t=>sn.create({...t,coerce:!0})),bigint:(t=>on.create({...t,coerce:!0})),date:(t=>an.create({...t,coerce:!0}))},jS=X});var N={};jo(N,{BRAND:()=>Qk,DIRTY:()=>rn,EMPTY_PATH:()=>Ik,INVALID:()=>X,NEVER:()=>jS,OK:()=>st,ParseStatus:()=>Qe,Schema:()=>ce,ZodAny:()=>Ir,ZodArray:()=>br,ZodBigInt:()=>on,ZodBoolean:()=>sn,ZodBranded:()=>Zo,ZodCatch:()=>yn,ZodDate:()=>an,ZodDefault:()=>gn,ZodDiscriminatedUnion:()=>mi,ZodEffects:()=>It,ZodEnum:()=>hn,ZodError:()=>mt,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>yi,ZodIntersection:()=>dn,ZodIssueCode:()=>j,ZodLazy:()=>pn,ZodLiteral:()=>fn,ZodMap:()=>Kn,ZodNaN:()=>Wn,ZodNativeEnum:()=>mn,ZodNever:()=>Vt,ZodNull:()=>ln,ZodNullable:()=>nr,ZodNumber:()=>nn,ZodObject:()=>yt,ZodOptional:()=>gt,ZodParsedType:()=>F,ZodPipeline:()=>qo,ZodPromise:()=>Or,ZodReadonly:()=>bn,ZodRecord:()=>gi,ZodSchema:()=>ce,ZodSet:()=>Gn,ZodString:()=>Ar,ZodSymbol:()=>Vn,ZodTransformer:()=>It,ZodTuple:()=>rr,ZodType:()=>ce,ZodUndefined:()=>cn,ZodUnion:()=>un,ZodUnknown:()=>yr,ZodVoid:()=>Hn,addIssueToContext:()=>q,any:()=>cS,array:()=>pS,bigint:()=>nS,boolean:()=>Dm,coerce:()=>NS,custom:()=>jm,date:()=>oS,datetimeRegex:()=>zm,defaultErrorMap:()=>mr,discriminatedUnion:()=>mS,effect:()=>ES,enum:()=>kS,function:()=>vS,getErrorMap:()=>qn,getParsedType:()=>tr,instanceof:()=>tS,intersection:()=>gS,isAborted:()=>fi,isAsync:()=>Fn,isDirty:()=>hi,isValid:()=>Pr,late:()=>eS,lazy:()=>xS,literal:()=>$S,makeIssue:()=>Uo,map:()=>wS,nan:()=>rS,nativeEnum:()=>SS,never:()=>uS,null:()=>aS,nullable:()=>PS,number:()=>Mm,object:()=>Jc,objectUtil:()=>Vc,oboolean:()=>zS,onumber:()=>CS,optional:()=>RS,ostring:()=>OS,pipeline:()=>IS,preprocess:()=>AS,promise:()=>TS,quotelessJson:()=>Rk,record:()=>bS,set:()=>_S,setErrorMap:()=>Ak,strictObject:()=>fS,string:()=>Lm,symbol:()=>sS,transformer:()=>ES,tuple:()=>yS,undefined:()=>iS,union:()=>hS,unknown:()=>lS,util:()=>he,void:()=>dS});var bi=O(()=>{pi();Kc();Rm();Do();Um();di()});var Jn=O(()=>{bi();bi()});function wi(t){let e=Yc.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Xc(t,e){let r=Yc.safeParse(t);if(!r.success)throw new Cr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Zm.test(e))throw new Cr('a literal connection_id is baked into the bundle source \u2014 connection binding is an install-time input, not a published value. Declare an inputs[] entry { type: "connection", source_system } instead.');let n=JSON.stringify(r.data);if(Zm.test(n))throw new Cr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var qm,Fm,Yc,Cr,Zm,Bm=O(()=>{Jn();qm=N.object({type:N.literal("connection"),source_system:N.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:N.string().min(1).max(200).optional()}),Fm=N.discriminatedUnion("type",[qm]),Yc=N.object({inputs:N.array(Fm).optional()}).passthrough(),Cr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Zm=/\bconnection[_-]?id\b["']?\s*[:=]/i});var _i,Qc=O(()=>{_i=["before_read","before_save","after_save","before_sync","after_sync","on_sync_failure"]});var el,Vm,Hm=O(()=>{Jn();ui();Qc();el=N.object({id:N.string().min(1,"hook id must be non-empty"),recordType:N.union([N.string().min(1),N.array(N.string().min(1)).min(1),N.literal("*")]),event:N.enum(_i),source:N.string().min(1).optional(),when:N.unknown().optional(),run:N.unknown(),failClosed:N.boolean().optional(),timeoutMs:N.number().int().positive().optional(),description:N.string().optional(),systemReserved:N.boolean().optional()}).superRefine((t,e)=>{typeof t.run!="function"&&e.addIssue({code:"custom",path:["run"],message:"run must be a function"}),"when"in t&&t.when!==void 0&&typeof t.when!="function"&&e.addIssue({code:"custom",path:["when"],message:"when, when present, must be a function"})}),Vm=Mo({kind:"hook",schema:el,factoryName:"defineHook"})});var Km=O(()=>{Hm();Qc()});var vi,tl=O(()=>{vi=["after_canonicalize_inbound","after_sync_success_outbound"]});var rl,Gm,Wm=O(()=>{Jn();ui();tl();rl=N.object({id:N.string().min(1,"conduit id must be non-empty"),on:N.enum(vi),from:N.object({source:N.string().min(1,"from.source must be non-empty"),recordType:N.string().min(1,"from.recordType must be non-empty"),when:N.unknown().optional()}),to:N.object({source:N.string().min(1,"to.source must be non-empty"),recordType:N.string().min(1,"to.recordType must be non-empty")}),mode:N.enum(["dual-bind","one-shot"]).optional(),transform:N.unknown(),idempotencyKey:N.unknown().optional(),cycleBudget:N.number().int().positive().optional(),conflictStrategy:N.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:N.number().int().positive().optional(),description:N.string().optional(),systemReserved:N.boolean().optional()}).superRefine((t,e)=>{typeof t.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"});let r=t.from?.when;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let n=t.idempotencyKey;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let o=t.from,s=t.to;o?.source&&s?.source&&o.source===s.source&&e.addIssue({code:"custom",path:["to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})}),Gm=Mo({kind:"conduit",schema:rl,factoryName:"defineConduit"})});var Jm=O(()=>{Wm();tl()});async function ZS(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let r=await e.default(t,{defaultNonNullable:!1});return e.astToString(r)}async function xi(t,e={}){return(e.transform??ZS)(t)}var nl=O(()=>{});function ol(t){switch(t.toLowerCase().trim()){case"boolean":return"boolean";case"smallint":case"integer":case"bigint":case"numeric":case"decimal":case"real":case"double precision":return"number";case"text":case"character varying":case"character":case"varchar":case"char":case"uuid":case"name":case"citext":return"string";case"timestamp with time zone":case"timestamp without time zone":case"timestamp":case"date":case"time":case"time with time zone":case"time without time zone":return"string";case"json":case"jsonb":return"unknown";case"array":return"unknown[]";default:return"unknown"}}function Ym(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function sl(t){return`${Ym(t.source)}${Ym(t.recordType)}`}function qS(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function FS(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function il(t){let e=sl(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
25
25
  * ${r.join(`
26
26
  * `)}
27
27
  */`;if(t.columns.length===0)return`${n}
28
28
  export interface ${e} {
29
29
  // no columns introspected
30
30
  [key: string]: unknown;
31
- }`;let o=t.columns.map(s=>{let i=nl(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${US(s)} */
32
- ${DS(s.name)}${a}: ${i}${c};`});return`${n}
31
+ }`;let o=t.columns.map(s=>{let i=ol(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${FS(s)} */
32
+ ${qS(s.name)}${a}: ${i}${c};`});return`${n}
33
33
  export interface ${e} {
34
34
  ${o.join(`
35
35
  `)}
36
- }`}function $i(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(sl).join(`
36
+ }`}function $i(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(il).join(`
37
37
 
38
- `)}var il=O(()=>{});function ZS(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function Jm(t,e,r){let n=await r(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!n.ok)throw new Error(`types-gen: GET ${t} failed (${n.status} ${n.statusText})`);return n.json()}async function Cr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=ZS(t.baseUrl),n=await Jm(r.records,t.token,e);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let o=$i(n),s=[qS,"// ----- Record shapes (from /v1/catalog/records) -----",o];if(!t.recordsOnly){let i=await Jm(r.openapi,t.token,e),a=await xi(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
38
+ `)}function Xm(t){let e=new Map;for(let n of t.records){if(!n.table)continue;let o=e.get(n.table);o||e.set(n.table,o=new Map);for(let s of n.columns)o.set(s.name,(o.get(s.name)??!0)&&s.nullable)}let r={};for(let[n,o]of[...e].sort(([s],[i])=>s.localeCompare(i)))o.get("pg_row_id")===!1?r[n]="pg_row_id":o.get("external_id")===!1&&(r[n]="external_id");return r}function BS(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function al(t){let e=Xm(t);return["/**"," * The column each table can be keyset-seeked on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * A table with no entry has no safe single-column key (line tables: their key"," * is the composite `(parent_pg_row_id, line_index)`). Page those by filtering"," * to one parent rather than seeking across all of them."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,o])=>` ${BS(n)}: '${o}',`),"} as const satisfies Record<string, string>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
39
+ `)}var cl=O(()=>{});function VS(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function Qm(t,e,r){let n=await r(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!n.ok)throw new Error(`types-gen: GET ${t} failed (${n.status} ${n.statusText})`);return n.json()}async function zr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=VS(t.baseUrl),n=await Qm(r.records,t.token,e);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let o=$i(n),s=[HS,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",al(n)];if(!t.recordsOnly){let i=await Qm(r.openapi,t.token,e),a=await xi(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
39
40
 
40
41
  `)+`
41
- `}var qS,Ym=O(()=>{rl();il();il();rl();qS=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
42
- `)});var al=O(()=>{ui();qm();Vm();Gm();Ym()});import{homedir as FS}from"node:os";import{join as Xm}from"node:path";import{promises as cl}from"node:fs";function Ot(t){return t.trim().replace(/\/+$/,"")}function eg(){let t=process.env.TURBOBASE_HOME??Xm(FS(),".turbobase");return{dir:t,file:Xm(t,"credentials")}}function Qm(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function qo(){let{file:t}=eg(),e;try{let s=await cl.readFile(t,"utf8");e=JSON.parse(s)}catch(s){if(s.code==="ENOENT")return{tenants:{}};throw s}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let s={};for(let[a,c]of Object.entries(r.tenants))Qm(c)&&(s[a]={token:c.token,updatedAt:c.updatedAt});return{active:typeof r.active=="string"&&s[r.active]?r.active:void 0,tenants:s}}let n={};for(let[s,i]of Object.entries(r))Qm(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:BS(n),tenants:n}}function BS(t){let e,r="";for(let[n,o]of Object.entries(t))(!e||String(o.updatedAt)>r)&&(e=n,r=String(o.updatedAt));return e}async function ll(t){let{dir:e,file:r}=eg();await cl.mkdir(e,{recursive:!0,mode:448}),await cl.writeFile(r,JSON.stringify(t,null,2)+`
43
- `,{mode:384})}async function tg(t){let e=Ot(t.baseUrl),r=await qo(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await ll(r),{baseUrl:e,token:t.token,updatedAt:n}}async function or(t){let e=await qo();if(t){let s=Ot(t),i=e.tenants[s];return i?{baseUrl:s,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(e.tenants),n=e.active&&e.tenants[e.active]?e.active:r.length===1?r[0]:void 0;if(!n)return null;let o=e.tenants[n];return{baseUrl:n,token:o.token,updatedAt:o.updatedAt}}async function ki(t){let e=Ot(t),r=await qo(),n=r.tenants[e];return n?(r.active=e,await ll(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function ul(t){let e=await qo(),r=t?Ot(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!r||!e.tenants[r])return null;if(delete e.tenants[r],e.active===r){let n=Object.keys(e.tenants);e.active=n.length===1?n[0]:void 0}return await ll(e),r}async function zr(){let t=await qo();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var Si=O(()=>{});function rg(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim().slice(0,200):""}function ng(t){return t.replace(/\/+$/,"")}function dl(t=process.env){let e=(t[Gn]??"").trim(),r=(t[Ti]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function pl(t){let e;try{e=new URL(t)}catch{return`${Gn} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&r?null:`${Gn} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var Te,re,Gn,Ti,Fo,Wn=O(()=>{Te=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};re=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=ng(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let c=rg(a);throw new Te(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit));let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{}})}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e){return this.request("POST","/v1/config/apply",{bundle:e})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Gn="TURBOBASE_REGISTRY_URL",Ti="TURBOBASE_REGISTRY_TOKEN";Fo=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=ng(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let c=rg(a);throw new Te(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function HS(t){if(VS.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function GS(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:HS(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||JS(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:KS,loader:"js"}))}}}function JS(t){let e=t.startsWith("node:")?t.slice(5):t;return WS.has(e.split("/")[0])}function og(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function YS(){try{return(await import("esbuild")).build}catch(t){throw og("esbuild",t)}}async function XS(){try{return(await import("isolated-vm")).default}catch(t){throw og("isolated-vm",t)}}async function Ei(t){let e=await YS(),r;try{r=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[GS()]})}catch(n){let s=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new fl(s||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function Bo(t,e,r={}){let n=r.timeoutMs??200,o=r.memoryLimitMb??16,s=r.member??"run",i={patches:[],logs:[]},a=await XS(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,d=new a.Callback(R=>{let C=JSON.parse(String(R));i.rejection||(i.rejection=C)}),y=new a.Callback(R=>{i.patches.push(JSON.parse(String(R)))}),h=new a.Callback(R=>{let C=JSON.parse(String(R));i.logs.push(C)}),f=new a.Callback(R=>{i.result=JSON.parse(String(R))});await u.set("__tb_reject",d),await u.set("__tb_patch",y),await u.set("__tb_log",h),await u.set("__tb_result",f),await u.set("__tb_ctx_json",JSON.stringify(QS(e)));let g=e0(t,s),E=await(await c.compileScript(g)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!E}:{effects:i}}finally{c.isDisposed||c.dispose()}}function QS(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null}}function e0(t,e){return`
42
+ `}var HS,eg=O(()=>{nl();cl();cl();nl();HS=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
43
+ `)});var ll=O(()=>{ui();Bm();Km();Jm();eg()});import{homedir as KS}from"node:os";import{join as tg}from"node:path";import{promises as ul}from"node:fs";function Ot(t){return t.trim().replace(/\/+$/,"")}function ng(){let t=process.env.TURBOBASE_HOME??tg(KS(),".turbobase");return{dir:t,file:tg(t,"credentials")}}function rg(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function Fo(){let{file:t}=ng(),e;try{let s=await ul.readFile(t,"utf8");e=JSON.parse(s)}catch(s){if(s.code==="ENOENT")return{tenants:{}};throw s}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let s={};for(let[a,c]of Object.entries(r.tenants))rg(c)&&(s[a]={token:c.token,updatedAt:c.updatedAt});return{active:typeof r.active=="string"&&s[r.active]?r.active:void 0,tenants:s}}let n={};for(let[s,i]of Object.entries(r))rg(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:GS(n),tenants:n}}function GS(t){let e,r="";for(let[n,o]of Object.entries(t))(!e||String(o.updatedAt)>r)&&(e=n,r=String(o.updatedAt));return e}async function dl(t){let{dir:e,file:r}=ng();await ul.mkdir(e,{recursive:!0,mode:448}),await ul.writeFile(r,JSON.stringify(t,null,2)+`
44
+ `,{mode:384})}async function og(t){let e=Ot(t.baseUrl),r=await Fo(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await dl(r),{baseUrl:e,token:t.token,updatedAt:n}}async function or(t){let e=await Fo();if(t){let s=Ot(t),i=e.tenants[s];return i?{baseUrl:s,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(e.tenants),n=e.active&&e.tenants[e.active]?e.active:r.length===1?r[0]:void 0;if(!n)return null;let o=e.tenants[n];return{baseUrl:n,token:o.token,updatedAt:o.updatedAt}}async function ki(t){let e=Ot(t),r=await Fo(),n=r.tenants[e];return n?(r.active=e,await dl(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function pl(t){let e=await Fo(),r=t?Ot(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!r||!e.tenants[r])return null;if(delete e.tenants[r],e.active===r){let n=Object.keys(e.tenants);e.active=n.length===1?n[0]:void 0}return await dl(e),r}async function Nr(){let t=await Fo();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var Si=O(()=>{});function sg(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim().slice(0,200):""}function ig(t){return t.replace(/\/+$/,"")}function fl(t=process.env){let e=(t[Yn]??"").trim(),r=(t[Ti]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function hl(t){let e;try{e=new URL(t)}catch{return`${Yn} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&r?null:`${Yn} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var _e,te,Yn,Ti,Bo,Xn=O(()=>{_e=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};te=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=ig(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let c=sg(a);throw new _e(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit));let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{}})}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e){return this.request("POST","/v1/config/apply",{bundle:e})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Yn="TURBOBASE_REGISTRY_URL",Ti="TURBOBASE_REGISTRY_TOKEN";Bo=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=ig(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let c=sg(a);throw new _e(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function JS(t){if(WS.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function XS(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:JS(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||eT(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:YS,loader:"js"}))}}}function eT(t){let e=t.startsWith("node:")?t.slice(5):t;return QS.has(e.split("/")[0])}function ag(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function tT(){try{return(await import("esbuild")).build}catch(t){throw ag("esbuild",t)}}async function rT(){try{return(await import("isolated-vm")).default}catch(t){throw ag("isolated-vm",t)}}async function Ei(t){let e=await tT(),r;try{r=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[XS()]})}catch(n){let s=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new ml(s||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function Vo(t,e,r={}){let n=r.timeoutMs??200,o=r.memoryLimitMb??16,s=r.member??"run",i={patches:[],logs:[]},a=await rT(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,d=new a.Callback(R=>{let z=JSON.parse(String(R));i.rejection||(i.rejection=z)}),b=new a.Callback(R=>{i.patches.push(JSON.parse(String(R)))}),h=new a.Callback(R=>{let z=JSON.parse(String(R));i.logs.push(z)}),f=new a.Callback(R=>{i.result=JSON.parse(String(R))});await u.set("__tb_reject",d),await u.set("__tb_patch",b),await u.set("__tb_log",h),await u.set("__tb_result",f),await u.set("__tb_ctx_json",JSON.stringify(nT(e)));let y=oT(t,s),E=await(await c.compileScript(y)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!E}:{effects:i}}finally{c.isDisposed||c.dispose()}}function nT(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null}}function oT(t,e){return`
44
45
  "use strict";
45
46
  (async () => {
46
47
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -109,36 +110,36 @@ ${o.join(`
109
110
  ${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
110
111
  return ${e==="when"?"out":"undefined"};
111
112
  })()
112
- `}var VS,KS,fl,WS,hl=O(()=>{VS=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);KS=`
113
+ `}var WS,YS,ml,QS,gl=O(()=>{WS=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);YS=`
113
114
  export const defineHook = (def) => def;
114
115
  export const defineConduit = (def) => def;
115
116
  export default defineHook;
116
- `,fl=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};WS=new Set(["assert","buffer","child_process","cluster","crypto","dns","events","fs","http","http2","https","net","os","path","process","querystring","readline","stream","string_decoder","timers","tls","tty","url","util","v8","vm","worker_threads","zlib"])});import{promises as ml}from"node:fs";import{join as t0}from"node:path";function r0(t){return{recordType:t.recordType??"unknown",event:t.event??"before_save",direction:t.direction??"standalone",origin:t.origin??"user",source:t.source??null,payload:t.payload??{},prior:t.prior,user:t.user,tenantConfig:t.tenantConfig??{},metadata:t.metadata}}async function n0(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await Bo(t,r0(e.context)),i=s.rejection?"reject":"pass";return{name:n,expected:o,observed:i,pass:i===o,rejection:s.rejection,patchCount:s.patches.length}}catch(s){return{name:n,expected:o,observed:"pass",pass:!1,patchCount:0,error:s instanceof Error?s.message:String(s)}}}async function Ri(t,e){let r=await Ei(t),n=[];for(let o=0;o<e.length;o+=1)n.push(await n0(r,e[o],`sample[${o}]`));return n}async function Vo(t){let e;try{e=await ml.readdir(t)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of e.sort()){if(!n.endsWith(".json"))continue;let o=await ml.readFile(t0(t,n),"utf8"),s=JSON.parse(o),i=Array.isArray(s)?s:[s];for(let a=0;a<i.length;a+=1){let c=i[a];r.push({file:n,fixture:{...c,name:c.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function Ho(t){return ml.readFile(t,"utf8")}var gl=O(()=>{hl()});function Lr(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function z0(t){let e=t.recordType;if(!e)throw new jt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
117
+ `,ml=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};QS=new Set(["assert","buffer","child_process","cluster","crypto","dns","events","fs","http","http2","https","net","os","path","process","querystring","readline","stream","string_decoder","timers","tls","tty","url","util","v8","vm","worker_threads","zlib"])});import{promises as yl}from"node:fs";import{join as sT}from"node:path";function iT(t){return{recordType:t.recordType??"unknown",event:t.event??"before_save",direction:t.direction??"standalone",origin:t.origin??"user",source:t.source??null,payload:t.payload??{},prior:t.prior,user:t.user,tenantConfig:t.tenantConfig??{},metadata:t.metadata}}async function aT(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await Vo(t,iT(e.context)),i=s.rejection?"reject":"pass";return{name:n,expected:o,observed:i,pass:i===o,rejection:s.rejection,patchCount:s.patches.length}}catch(s){return{name:n,expected:o,observed:"pass",pass:!1,patchCount:0,error:s instanceof Error?s.message:String(s)}}}async function Ri(t,e){let r=await Ei(t),n=[];for(let o=0;o<e.length;o+=1)n.push(await aT(r,e[o],`sample[${o}]`));return n}async function Ho(t){let e;try{e=await yl.readdir(t)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of e.sort()){if(!n.endsWith(".json"))continue;let o=await yl.readFile(sT(t,n),"utf8"),s=JSON.parse(o),i=Array.isArray(s)?s:[s];for(let a=0;a<i.length;a+=1){let c=i[a];r.push({file:n,fixture:{...c,name:c.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function Ko(t){return yl.readFile(t,"utf8")}var bl=O(()=>{gl()});function Mr(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function MT(t){let e=t.recordType;if(!e)throw new jt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
117
118
  source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
118
119
  run: (ctx) => {
119
120
  // Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
120
121
  // with ctx.patch({...}); observe with ctx.log('info', '...').
121
- },`,a="custom";else if(n==="require-field"){let y=t.field;if(!y)throw new jt("require-field template needs --field=<name>");i=`
122
+ },`,a="custom";else if(n==="require-field"){let b=t.field;if(!b)throw new jt("require-field template needs --field=<name>");i=`
122
123
  run: (ctx) => {
123
- const v = ctx.payload[${JSON.stringify(y)}];
124
+ const v = ctx.payload[${JSON.stringify(b)}];
124
125
  if (v === undefined || v === null || v === '') {
125
126
  ctx.reject({
126
127
  code: 'MANDATORY_FIELD_MISSING',
127
- field: ${JSON.stringify(y)},
128
- message: ${JSON.stringify(`${y} is required`)},
128
+ field: ${JSON.stringify(b)},
129
+ message: ${JSON.stringify(`${b} is required`)},
129
130
  });
130
131
  }
131
- },`,a=`require-field-${y}`}else if(n==="enforce-format"){let y=t.field;if(!y)throw new jt("enforce-format template needs --field=<name>");if(!t.regex)throw new jt("enforce-format template needs --regex=<pattern>");i=`
132
+ },`,a=`require-field-${b}`}else if(n==="enforce-format"){let b=t.field;if(!b)throw new jt("enforce-format template needs --field=<name>");if(!t.regex)throw new jt("enforce-format template needs --regex=<pattern>");i=`
132
133
  run: (ctx) => {
133
- const v = ctx.payload[${JSON.stringify(y)}];
134
+ const v = ctx.payload[${JSON.stringify(b)}];
134
135
  if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
135
136
  ctx.reject({
136
137
  code: 'INVALID_FORMAT',
137
- field: ${JSON.stringify(y)},
138
- message: ${JSON.stringify(`${y} does not match expected format`)},
138
+ field: ${JSON.stringify(b)},
139
+ message: ${JSON.stringify(`${b} does not match expected format`)},
139
140
  });
140
141
  }
141
- },`,a=`enforce-format-${y}`}else throw new jt(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${Lr(t.regex).slice(0,24)}`:""}`,u=`/**
142
+ },`,a=`enforce-format-${b}`}else throw new jt(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${Mr(t.regex).slice(0,24)}`:""}`,u=`/**
142
143
  * ${t.description??`${a} on ${e}.${r}`}
143
144
  *
144
145
  * Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
@@ -151,7 +152,7 @@ export default defineHook<Record<string, unknown>>({
151
152
  recordType: ${JSON.stringify(e)},
152
153
  event: ${JSON.stringify(r)},${s}${i}
153
154
  });
154
- `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function N0(t){let e=t.recordType;if(!e)throw new jt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new jt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new jt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new jt(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let o=t.toRecordType??e,s=t.event??"after_canonicalize_inbound",i=t.id??`${Lr(r)}2${Lr(n)}:${Lr(e)}`,c=`/**
155
+ `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function DT(t){let e=t.recordType;if(!e)throw new jt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new jt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new jt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new jt(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let o=t.toRecordType??e,s=t.event??"after_canonicalize_inbound",i=t.id??`${Mr(r)}2${Mr(n)}:${Mr(e)}`,c=`/**
155
156
  * ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
156
157
  *
157
158
  * Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
@@ -194,7 +195,7 @@ export default defineConduit<Record<string, unknown>>({
194
195
  },
195
196
  idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
196
197
  });
197
- `;return{relativePath:`conduits/${Lr(r)}-${Lr(e)}-to-${Lr(n)}-${Lr(o)}.ts`,content:c}}function Qn(t,e){let r=j0[t];if(!r)throw new jt(`unknown extension kind '${t}'. Scaffoldable kinds: ${Pg.join(", ")}.`);return r(e)}var Pg,jt,j0,$l=O(()=>{Pg=["hook","conduit"];jt=class extends Error{};j0={hook:z0,conduit:N0}});function tE(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619)>>>0;return e>>>0}function rE(t){return ay[tE(t)%ay.length]}function nE(t){let e=t.trim().split(/[\s\-_.]+/).filter(r=>/[a-z0-9]/i.test(r));return e.length===0?t.trim().slice(0,1).toUpperCase()||"\u2022":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase()}function cy(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ly(t,e){let[r,n]=rE(t),o=cy(nE(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${cy(e)}">
198
+ `;return{relativePath:`conduits/${Mr(r)}-${Mr(e)}-to-${Mr(n)}-${Mr(o)}.ts`,content:c}}function ro(t,e){let r=UT[t];if(!r)throw new jt(`unknown extension kind '${t}'. Scaffoldable kinds: ${Og.join(", ")}.`);return r(e)}var Og,jt,UT,Sl=O(()=>{Og=["hook","conduit"];jt=class extends Error{};UT={hook:MT,conduit:DT}});function sE(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619)>>>0;return e>>>0}function iE(t){return uy[sE(t)%uy.length]}function aE(t){let e=t.trim().split(/[\s\-_.]+/).filter(r=>/[a-z0-9]/i.test(r));return e.length===0?t.trim().slice(0,1).toUpperCase()||"\u2022":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase()}function dy(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function py(t,e){let[r,n]=iE(t),o=dy(aE(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${dy(e)}">
198
199
  <defs>
199
200
  <linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
200
201
  <stop offset="0" stop-color="${r}"/>
@@ -204,9 +205,9 @@ export default defineConduit<Record<string, unknown>>({
204
205
  <rect width="64" height="64" rx="14" fill="url(#tile)"/>
205
206
  <text x="32" y="34" text-anchor="middle" dominant-baseline="central" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="26" font-weight="600" fill="#ffffff">${o}</text>
206
207
  </svg>
207
- `}var ay,uy=O(()=>{ay=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var dy,py=O(()=>{dy=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var wy={};No(wy,{MAIN_TSX:()=>by,STYLES_CSS:()=>_y,TSCONFIG:()=>gy,TURBOBASE_CLIENT:()=>fy,indexHtml:()=>yy,instanceOriginFromEnv:()=>lE,packageJson:()=>hy,scaffoldAppFiles:()=>dE,starterApp:()=>pE,viteConfig:()=>my});function sE(t){let e={name:t.title},r=(t.description??"").trim().slice(0,oE);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...dy},JSON.stringify(e,null,2)+`
208
- `}function hy(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview"},dependencies:{react:"^18.3.1","react-dom":"^18.3.1"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
209
- `}function cE(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}function lE(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function my(t,e={}){let r=cE(e.instanceOrigin);return`import { defineConfig } from 'vite';
208
+ `}var uy,fy=O(()=>{uy=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var hy,my=O(()=>{hy=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var $y={};jo($y,{MAIN_TSX:()=>vy,STYLES_CSS:()=>xy,TSCONFIG:()=>wy,TURBOBASE_CLIENT:()=>gy,indexHtml:()=>_y,instanceOriginFromEnv:()=>fE,packageJson:()=>yy,scaffoldAppFiles:()=>mE,starterApp:()=>gE,viteConfig:()=>by});function lE(t){let e={name:t.title},r=(t.description??"").trim().slice(0,cE);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...hy},JSON.stringify(e,null,2)+`
209
+ `}function yy(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview"},dependencies:{react:"^18.3.1","react-dom":"^18.3.1"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
210
+ `}function pE(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}function fE(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function by(t,e={}){let r=pE(e.instanceOrigin);return`import { defineConfig } from 'vite';
210
211
  import react from '@vitejs/plugin-react';
211
212
 
212
213
  // A same-origin static SPA served at /a/${t}. \`base\` MUST match that mount
@@ -220,8 +221,8 @@ import react from '@vitejs/plugin-react';
220
221
  // you sign in, and the cookies land on localhost:3000. Override the targets
221
222
  // with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
222
223
  // them at boot; restart the dev server after changing one).
223
- const TENANT = process.env.SUPABASE_URL || '${r??iE}'; // /rest + the Realtime WS
224
- const API = process.env.TURBOBASE_API_URL || '${r??aE}'; // /v1, /auth, /login, /_app
224
+ const TENANT = process.env.SUPABASE_URL || '${r??uE}'; // /rest + the Realtime WS
225
+ const API = process.env.TURBOBASE_API_URL || '${r??dE}'; // /v1, /auth, /login, /_app
225
226
 
226
227
  // Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
227
228
  // this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
@@ -253,7 +254,7 @@ export default defineConfig({
253
254
  },
254
255
  build: { outDir: 'dist' },
255
256
  });
256
- `}function yy(t){return`<!doctype html>
257
+ `}function _y(t){return`<!doctype html>
257
258
  <html lang="en">
258
259
  <head>
259
260
  <meta charset="UTF-8" />
@@ -266,7 +267,7 @@ export default defineConfig({
266
267
  <script type="module" src="/src/main.tsx"></script>
267
268
  </body>
268
269
  </html>
269
- `}function dE(t){return{"package.json":hy(t.slug),"vite.config.ts":my(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":uE,"tsconfig.json":gy,"index.html":yy(t.title),"public/turbobase.json":sE(t),"public/favicon.svg":ly(t.slug,t.title),"src/main.tsx":by,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":fy,"src/styles.css":_y,"README.md":`# ${t.title}
270
+ `}function mE(t){return{"package.json":yy(t.slug),"vite.config.ts":by(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":hE,"tsconfig.json":wy,"index.html":_y(t.title),"public/turbobase.json":lE(t),"public/favicon.svg":py(t.slug,t.title),"src/main.tsx":vy,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":gy,"src/styles.css":xy,"README.md":`# ${t.title}
270
271
 
271
272
  \`\`\`sh
272
273
  npm install
@@ -287,7 +288,7 @@ every read comes back "permission denied", which looks like an RLS problem.
287
288
 
288
289
  \`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
289
290
  live access token and is gitignored \u2014 keep it that way.
290
- `}}function pE(t){return`import React from 'react';
291
+ `}}function gE(t){return`import React from 'react';
291
292
  import { select } from './lib/turbobase';
292
293
 
293
294
  /** Swap for any record type \u2014 GET /v1/catalog/records lists what this instance has. */
@@ -313,7 +314,7 @@ export default function App() {
313
314
  </main>
314
315
  );
315
316
  }
316
- `}var oE,fy,iE,aE,uE,gy,by,_y,vy=O(()=>{uy();py();oE=200;fy=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
317
+ `}var cE,gy,uE,dE,hE,wy,vy,xy,ky=O(()=>{fy();my();cE=200;gy=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
317
318
  // Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
318
319
  // A cold first paint that fans out many reads should use batch() \u2014 ONE request
319
320
  // that multiplexes them, sidestepping the per-request rate limiter.
@@ -691,12 +692,28 @@ async function batchChunk<T>(queries: string[]): Promise<BatchResult<T>[]> {
691
692
  //
692
693
  // select() is capped by the server at \${SERVER_MAX_ROWS} rows and warns when it
693
694
  // truncates. selectPage() pages the FULL result set with a PostgREST-native
694
- // keyset seek: order by the mirror sort key (\`pg_row_id\` when present, else
695
- // \`external_id\` \u2014 pass { sortKey } for read-only masters), request one probe row
696
- // beyond the page to detect a next page without a count, and seek the next page
697
- // with \`<sortKey>=gt.<lastValue>\`. The opaque cursor pins itself to the exact
698
- // query (table + filters + select) that minted it, so replaying it against a
699
- // changed query throws instead of silently mixing two result sets.
695
+ // keyset seek: order by the mirror sort key, request one probe row beyond the
696
+ // page to detect a next page without a count, and seek the next page with
697
+ // \`<sortKey>=gt.<lastValue>\`. The opaque cursor pins itself to the exact query
698
+ // (table + filters + select) that minted it, so replaying it against a changed
699
+ // query throws instead of silently mixing two result sets.
700
+ //
701
+ // A SEEK KEY MUST BE NOT NULL AND UNIQUE, and nothing can check that for you at
702
+ // runtime. \`<key>=gt.<last>\` skips every row that SHARES the boundary value,
703
+ // and a NULL sorts to one end and is never passed \u2014 so a key that is neither
704
+ // returns a short list with no error anywhere. Your generated types say which
705
+ // columns qualify: a table with \`pg_row_id\` has \`external_id?: string | null\`,
706
+ // and a table without one has \`external_id: string\` (non-optional, because it
707
+ // is still that table's primary key). So:
708
+ //
709
+ // pg_row_id in the type -> seek on pg_row_id. It is the default; pass nothing.
710
+ // no pg_row_id -> pass { sortKey: 'external_id' }.
711
+ //
712
+ // Re-check that when you regenerate types. Several mirror tables gained
713
+ // \`pg_row_id\` after they were first read, and the same release made their
714
+ // \`external_id\` nullable and unique only per connection \u2014 so a \`sortKey\`
715
+ // override that was correct when it was written silently became a row-dropping
716
+ // bug, on a table whose seek column still existed.
700
717
  // ---------------------------------------------------------------------------
701
718
 
702
719
  /** One page of a keyset read: the trimmed rows, plus the token to fetch the next
@@ -791,7 +808,10 @@ function queryHash(table: string, params: URLSearchParams, sortKey: string): str
791
808
  * ({ rows, nextCursor } = await selectPage('item_receipt?select=*', { pageSize: 50, cursor: nextCursor }));
792
809
  *
793
810
  * \`sortKey\` defaults to \`pg_row_id\`; pass { sortKey: 'external_id' } for a
794
- * read-only master table that has no \`pg_row_id\`.
811
+ * read-only master table that has no \`pg_row_id\` \u2014 and ONLY for that case. See
812
+ * the NOT NULL + UNIQUE rule above the Page type: on a table that HAS
813
+ * \`pg_row_id\`, \`external_id\` is nullable and unique only per connection, so
814
+ * seeking on it drops rows silently.
795
815
  *
796
816
  * EMBEDS PAGE TOO: \`selectPage('purchase_order?select=*,receipt_lines(*)')\` keysets
797
817
  * the PARENT (purchase_order) and carries the embed with each parent row, so a
@@ -859,17 +879,52 @@ export async function selectPage<T = unknown>(
859
879
  const hasMore = probe.length > pageSize;
860
880
  const rows = hasMore ? probe.slice(0, pageSize) : probe;
861
881
 
882
+ // An override that has gone stale, caught from the response itself.
883
+ //
884
+ // Seeking on anything but \`pg_row_id\` is only valid on a table that HASN'T
885
+ // got one. If the rows coming back carry \`pg_row_id\`, the table has one \u2014 so
886
+ // the override is wrong now, whatever it was when it was written. That is not
887
+ // hypothetical: five transaction headers gained \`pg_row_id\` and had their
888
+ // \`external_id\` made nullable in the SAME release, so every app carrying the
889
+ // documented \`{ sortKey: 'external_id' }\` fallback silently started dropping
890
+ // rows, on a column that still existed.
891
+ //
892
+ // Free \u2014 the evidence is already in hand, no extra request. It only fires
893
+ // when the projection includes \`pg_row_id\` (\`select=*\`, or an explicit list
894
+ // naming it); a narrow select that omits it cannot be checked here, which is
895
+ // what SEEK_KEYS in your generated types is for.
896
+ if (opts.sortKey && opts.sortKey !== 'pg_row_id' && rows.length > 0) {
897
+ if (Object.prototype.hasOwnProperty.call(rows[0] as object, 'pg_row_id')) {
898
+ throw new TurbobaseCursorError(
899
+ \`"\${table}" has a pg_row_id, so { sortKey: '\${opts.sortKey}' } is unsafe: on a table with \` +
900
+ 'pg_row_id, external_id is nullable and unique only per connection, and a keyset seek ' +
901
+ 'on it drops rows silently. Remove the sortKey override (pg_row_id is the default), or ' +
902
+ 'read it from SEEK_KEYS in your generated types.',
903
+ );
904
+ }
905
+ }
906
+
862
907
  let nextCursor: string | null = null;
863
908
  if (hasMore && rows.length > 0) {
864
909
  const last = rows[rows.length - 1] as Record<string, unknown>;
865
910
  const lastValue = last[sortKey];
866
- if (lastValue != null) {
867
- nextCursor = encodeCursor({ t: table, k: sortKey, v: String(lastValue), h: filterHash });
911
+ // A null here means the seek key is nullable, which means it is not a valid
912
+ // seek key (see the NOT NULL + UNIQUE rule above). There is no correct
913
+ // cursor to mint \u2014 but returning \`nextCursor: null\` alongside \`hasMore\`
914
+ // would tell the caller the list ENDED, which is the silent truncation this
915
+ // whole path exists to avoid. Say it instead.
916
+ if (lastValue == null) {
917
+ throw new TurbobaseCursorError(
918
+ \`cannot page "\${table}": the sort key "\${sortKey}" is null on the last row of this page, \` +
919
+ 'so there are more rows but no valid cursor. A seek key must be NOT NULL and UNIQUE \u2014 ' +
920
+ 'seek on pg_row_id if this table has one.',
921
+ );
868
922
  }
923
+ nextCursor = encodeCursor({ t: table, k: sortKey, v: String(lastValue), h: filterHash });
869
924
  }
870
925
  return { rows, nextCursor };
871
926
  }
872
- `;iE="http://localhost:54331",aE="http://localhost:4100";uE=`node_modules/
927
+ `;uE="http://localhost:54331",dE="http://localhost:4100";hE=`node_modules/
873
928
  dist/
874
929
  build/
875
930
 
@@ -881,8 +936,8 @@ build/
881
936
  !.env.example
882
937
 
883
938
  .DS_Store
884
- `,gy=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0},include:["src"]},null,2)}
885
- `;by=`import React from 'react';
939
+ `,wy=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0},include:["src"]},null,2)}
940
+ `;vy=`import React from 'react';
886
941
  import { createRoot } from 'react-dom/client';
887
942
  import App from './App';
888
943
  import './styles.css';
@@ -892,80 +947,80 @@ createRoot(document.getElementById('root')!).render(
892
947
  <App />
893
948
  </React.StrictMode>,
894
949
  );
895
- `,_y=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
950
+ `,xy=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
896
951
  * { box-sizing: border-box; }
897
952
  body { margin: 0; background: #f8fafc; color: #0f172a; }
898
- `});var es=O(()=>{bi()});function A(t,e,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Tt(t){return t&&Object.assign(ji,t),ji}var hE,xr,ji,eo=O(()=>{hE=Object.freeze({status:"aborted"});xr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ji={}});var fe={};No(fe,{BIGINT_FORMAT_RANGES:()=>$y,Class:()=>Ul,NUMBER_FORMAT_RANGES:()=>Kl,aborted:()=>vn,allowsEval:()=>Bl,assert:()=>_E,assertEqual:()=>mE,assertIs:()=>yE,assertNever:()=>bE,assertNotEqual:()=>gE,assignProp:()=>Fl,cached:()=>ns,captureStackTrace:()=>Mi,cleanEnum:()=>OE,cleanRegex:()=>ss,clone:()=>Et,createTransparentProxy:()=>SE,defineLazy:()=>Ie,esc:()=>wn,escapeRegex:()=>Mr,extend:()=>RE,finalizeIssue:()=>Kt,floatSafeRemainder:()=>ql,getElementAtPath:()=>wE,getEnumValues:()=>rs,getLengthableOrigin:()=>is,getParsedType:()=>kE,getSizableOrigin:()=>ky,isObject:()=>to,isPlainObject:()=>ro,issue:()=>Gl,joinValues:()=>Li,jsonStringifyReplacer:()=>Zl,merge:()=>PE,normalizeParams:()=>X,nullish:()=>os,numKeys:()=>$E,omit:()=>EE,optionalKeys:()=>Hl,partial:()=>AE,pick:()=>TE,prefixIssues:()=>sr,primitiveTypes:()=>xy,promiseAllObject:()=>vE,propertyKeyTypes:()=>Vl,randomString:()=>xE,required:()=>IE,stringifyPrimitive:()=>Di,unwrapMessage:()=>ts});function mE(t){return t}function gE(t){return t}function yE(t){}function bE(t){throw new Error}function _E(t){}function rs(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Li(t,e="|"){return t.map(r=>Di(r)).join(e)}function Zl(t,e){return typeof e=="bigint"?e.toString():e}function ns(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function os(t){return t==null}function ss(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ql(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Ie(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Fl(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function wE(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function vE(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function xE(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function wn(t){return JSON.stringify(t)}function to(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ro(t){if(to(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(to(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function $E(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Mr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Et(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function X(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function SE(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Di(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Hl(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function TE(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Et(t,{...t._zod.def,shape:r,checks:[]})}function EE(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Et(t,{...t._zod.def,shape:r,checks:[]})}function RE(t,e){if(!ro(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Fl(this,"shape",n),n},checks:[]};return Et(t,r)}function PE(t,e){return Et(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Fl(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function AE(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Et(e,{...e._zod.def,shape:o,checks:[]})}function IE(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Et(e,{...e._zod.def,shape:o,checks:[]})}function vn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function sr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ts(t){return typeof t=="string"?t:t?.message}function Kt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=ts(t.inst?._zod.def?.error?.(t))??ts(e?.error?.(t))??ts(r.customError?.(t))??ts(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function ky(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function is(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Gl(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function OE(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Mi,Bl,kE,Vl,xy,Kl,$y,Ul,ir=O(()=>{Mi=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Bl=ns(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});kE=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Vl=new Set(["string","number","symbol"]),xy=new Set(["string","number","bigint","boolean","symbol","undefined"]);Kl={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},$y={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Ul=class{constructor(...e){}}});function Wl(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Jl(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(t),n}var Sy,Ui,as,Yl=O(()=>{eo();ir();Sy=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Zl,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ui=A("$ZodError",Sy),as=A("$ZodError",Sy,{Parent:Error})});var Xl,Ql,eu,tu,ru,xn,nu,$n,ou=O(()=>{eo();Yl();ir();Xl=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new xr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Kt(c,s,Tt())));throw Mi(a,o?.callee),a}return i.value},Ql=Xl(as),eu=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Kt(c,s,Tt())));throw Mi(a,o?.callee),a}return i.value},tu=eu(as),ru=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new xr;return s.issues.length?{success:!1,error:new(t??Ui)(s.issues.map(i=>Kt(i,o,Tt())))}:{success:!0,data:s.value}},xn=ru(as),nu=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Kt(i,o,Tt())))}:{success:!0,data:s.value}},$n=nu(as)});function Ny(){return new RegExp(zE,"u")}function Vy(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Hy(t){return new RegExp(`^${Vy(t)}$`)}function Ky(t){let e=Vy({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Fy}T(?:${n})$`)}var Ty,Ey,Ry,Py,Ay,Iy,Oy,Cy,su,zy,zE,jy,Ly,My,Dy,Uy,iu,Zy,qy,Fy,By,Gy,Wy,Jy,Yy,Xy,Qy,eb,qi=O(()=>{Ty=/^[cC][^\s-]{8,}$/,Ey=/^[0-9a-z]+$/,Ry=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Py=/^[0-9a-vA-V]{20}$/,Ay=/^[A-Za-z0-9]{27}$/,Iy=/^[a-zA-Z0-9_-]{21}$/,Oy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Cy=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,su=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,zy=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,zE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";jy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ly=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,My=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Dy=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Uy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,iu=/^[A-Za-z0-9_-]*$/,Zy=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,qy=/^\+(?:[0-9]){6,14}[0-9]$/,Fy="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",By=new RegExp(`^${Fy}$`);Gy=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Wy=/^\d+$/,Jy=/^-?\d+(?:\.\d+)?/i,Yy=/true|false/i,Xy=/null/i,Qy=/^[^A-Z]*$/,eb=/^[^a-z]*$/});var et,tb,au,cu,rb,nb,ob,sb,ib,cs,ab,cb,lb,ub,db,pb,fb,Fi=O(()=>{eo();qi();ir();et=A("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),tb={number:"number",bigint:"bigint",object:"date"},au=A("$ZodCheckLessThan",(t,e)=>{et.init(t,e);let r=tb[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),cu=A("$ZodCheckGreaterThan",(t,e)=>{et.init(t,e);let r=tb[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),rb=A("$ZodCheckMultipleOf",(t,e)=>{et.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):ql(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),nb=A("$ZodCheckNumberFormat",(t,e)=>{et.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Kl[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Wy)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),ob=A("$ZodCheckMaxLength",(t,e)=>{var r;et.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!os(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=is(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),sb=A("$ZodCheckMinLength",(t,e)=>{var r;et.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!os(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=is(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),ib=A("$ZodCheckLengthEquals",(t,e)=>{var r;et.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!os(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=is(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),cs=A("$ZodCheckStringFormat",(t,e)=>{var r,n;et.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),ab=A("$ZodCheckRegex",(t,e)=>{cs.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),cb=A("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Qy),cs.init(t,e)}),lb=A("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=eb),cs.init(t,e)}),ub=A("$ZodCheckIncludes",(t,e)=>{et.init(t,e);let r=Mr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),db=A("$ZodCheckStartsWith",(t,e)=>{et.init(t,e);let r=new RegExp(`^${Mr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),pb=A("$ZodCheckEndsWith",(t,e)=>{et.init(t,e);let r=new RegExp(`.*${Mr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),fb=A("$ZodCheckOverwrite",(t,e)=>{et.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Bi,lu=O(()=>{Bi=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
953
+ `});var ts=O(()=>{bi()});function I(t,e,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function St(t){return t&&Object.assign(ji,t),ji}var bE,$r,ji,no=O(()=>{bE=Object.freeze({status:"aborted"});$r=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ji={}});var ge={};jo(ge,{BIGINT_FORMAT_RANGES:()=>Ty,Class:()=>ql,NUMBER_FORMAT_RANGES:()=>Wl,aborted:()=>xn,allowsEval:()=>Hl,assert:()=>$E,assertEqual:()=>wE,assertIs:()=>vE,assertNever:()=>xE,assertNotEqual:()=>_E,assignProp:()=>Vl,cached:()=>os,captureStackTrace:()=>Mi,cleanEnum:()=>jE,cleanRegex:()=>is,clone:()=>Tt,createTransparentProxy:()=>PE,defineLazy:()=>Oe,esc:()=>vn,escapeRegex:()=>Dr,extend:()=>OE,finalizeIssue:()=>Ht,floatSafeRemainder:()=>Bl,getElementAtPath:()=>kE,getEnumValues:()=>ns,getLengthableOrigin:()=>as,getParsedType:()=>RE,getSizableOrigin:()=>Ey,isObject:()=>oo,isPlainObject:()=>so,issue:()=>Jl,joinValues:()=>Li,jsonStringifyReplacer:()=>Fl,merge:()=>CE,normalizeParams:()=>Q,nullish:()=>ss,numKeys:()=>EE,omit:()=>IE,optionalKeys:()=>Gl,partial:()=>zE,pick:()=>AE,prefixIssues:()=>sr,primitiveTypes:()=>Sy,promiseAllObject:()=>SE,propertyKeyTypes:()=>Kl,randomString:()=>TE,required:()=>NE,stringifyPrimitive:()=>Di,unwrapMessage:()=>rs});function wE(t){return t}function _E(t){return t}function vE(t){}function xE(t){throw new Error}function $E(t){}function ns(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Li(t,e="|"){return t.map(r=>Di(r)).join(e)}function Fl(t,e){return typeof e=="bigint"?e.toString():e}function os(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ss(t){return t==null}function is(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Bl(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Oe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Vl(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function kE(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function SE(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function TE(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function vn(t){return JSON.stringify(t)}function oo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function so(t){if(oo(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(oo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function EE(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Dr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function Q(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function PE(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Di(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Gl(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function AE(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Tt(t,{...t._zod.def,shape:r,checks:[]})}function IE(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Tt(t,{...t._zod.def,shape:r,checks:[]})}function OE(t,e){if(!so(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Vl(this,"shape",n),n},checks:[]};return Tt(t,r)}function CE(t,e){return Tt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Vl(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function zE(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Tt(e,{...e._zod.def,shape:o,checks:[]})}function NE(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Tt(e,{...e._zod.def,shape:o,checks:[]})}function xn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function sr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function rs(t){return typeof t=="string"?t:t?.message}function Ht(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=rs(t.inst?._zod.def?.error?.(t))??rs(e?.error?.(t))??rs(r.customError?.(t))??rs(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Ey(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function as(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Jl(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function jE(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Mi,Hl,RE,Kl,Sy,Wl,Ty,ql,ir=O(()=>{Mi=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Hl=os(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});RE=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Kl=new Set(["string","number","symbol"]),Sy=new Set(["string","number","bigint","boolean","symbol","undefined"]);Wl={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ty={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};ql=class{constructor(...e){}}});function Yl(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Xl(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(t),n}var Ry,Ui,cs,Ql=O(()=>{no();ir();Ry=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Fl,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ui=I("$ZodError",Ry),cs=I("$ZodError",Ry,{Parent:Error})});var eu,tu,ru,nu,ou,$n,su,kn,iu=O(()=>{no();Ql();ir();eu=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new $r;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Ht(c,s,St())));throw Mi(a,o?.callee),a}return i.value},tu=eu(cs),ru=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Ht(c,s,St())));throw Mi(a,o?.callee),a}return i.value},nu=ru(cs),ou=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new $r;return s.issues.length?{success:!1,error:new(t??Ui)(s.issues.map(i=>Ht(i,o,St())))}:{success:!0,data:s.value}},$n=ou(cs),su=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Ht(i,o,St())))}:{success:!0,data:s.value}},kn=su(cs)});function My(){return new RegExp(ME,"u")}function Gy(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Wy(t){return new RegExp(`^${Gy(t)}$`)}function Jy(t){let e=Gy({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Hy}T(?:${n})$`)}var Py,Ay,Iy,Oy,Cy,zy,Ny,jy,au,Ly,ME,Dy,Uy,Zy,qy,Fy,cu,By,Vy,Hy,Ky,Yy,Xy,Qy,eb,tb,rb,nb,qi=O(()=>{Py=/^[cC][^\s-]{8,}$/,Ay=/^[0-9a-z]+$/,Iy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Oy=/^[0-9a-vA-V]{20}$/,Cy=/^[A-Za-z0-9]{27}$/,zy=/^[a-zA-Z0-9_-]{21}$/,Ny=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jy=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,au=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Ly=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ME="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Dy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Uy=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Zy=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,qy=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Fy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cu=/^[A-Za-z0-9_-]*$/,By=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Vy=/^\+(?:[0-9]){6,14}[0-9]$/,Hy="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Ky=new RegExp(`^${Hy}$`);Yy=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Xy=/^\d+$/,Qy=/^-?\d+(?:\.\d+)?/i,eb=/true|false/i,tb=/null/i,rb=/^[^A-Z]*$/,nb=/^[^a-z]*$/});var et,ob,lu,uu,sb,ib,ab,cb,lb,ls,ub,db,pb,fb,hb,mb,gb,Fi=O(()=>{no();qi();ir();et=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ob={number:"number",bigint:"bigint",object:"date"},lu=I("$ZodCheckLessThan",(t,e)=>{et.init(t,e);let r=ob[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),uu=I("$ZodCheckGreaterThan",(t,e)=>{et.init(t,e);let r=ob[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),sb=I("$ZodCheckMultipleOf",(t,e)=>{et.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Bl(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),ib=I("$ZodCheckNumberFormat",(t,e)=>{et.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Wl[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Xy)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),ab=I("$ZodCheckMaxLength",(t,e)=>{var r;et.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ss(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=as(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),cb=I("$ZodCheckMinLength",(t,e)=>{var r;et.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ss(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=as(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),lb=I("$ZodCheckLengthEquals",(t,e)=>{var r;et.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ss(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=as(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),ls=I("$ZodCheckStringFormat",(t,e)=>{var r,n;et.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),ub=I("$ZodCheckRegex",(t,e)=>{ls.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),db=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=rb),ls.init(t,e)}),pb=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=nb),ls.init(t,e)}),fb=I("$ZodCheckIncludes",(t,e)=>{et.init(t,e);let r=Dr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),hb=I("$ZodCheckStartsWith",(t,e)=>{et.init(t,e);let r=new RegExp(`^${Dr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),mb=I("$ZodCheckEndsWith",(t,e)=>{et.init(t,e);let r=new RegExp(`.*${Dr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),gb=I("$ZodCheckOverwrite",(t,e)=>{et.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Bi,du=O(()=>{Bi=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
899
954
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
900
- `))}}});var mb,uu=O(()=>{mb={major:4,minor:0,patch:0}});function Pb(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function NE(t){if(!iu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Pb(r)}function jE(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function gb(t,e,r){t.issues.length&&e.issues.push(...sr(r,t.issues)),e.value[r]=t.value}function Vi(t,e,r){t.issues.length&&e.issues.push(...sr(r,t.issues)),e.value[r]=t.value}function yb(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...sr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function bb(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Kt(s,n,Tt())))}),e}function du(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(ro(t)&&ro(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=du(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=du(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function _b(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),vn(t))return t;let n=du(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function wb(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function vb(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function xb(t,e,r){return vn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function $b(t){return t.value=Object.freeze(t.value),t}function kb(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Gl(o))}}var Re,ls,Oe,pu,fu,hu,mu,gu,yu,bu,_u,wu,vu,xu,Sb,Tb,Eb,Rb,$u,ku,Su,Tu,Eu,Ru,Pu,Au,Hi,Iu,Ou,Cu,zu,Nu,ju,Ki,Gi,Lu,Mu,Du,Uu,Zu,qu,Fu,Bu,Vu,Hu,Ku,Gu,Wu,Ju,Yu,Ab=O(()=>{Fi();eo();lu();ou();qi();ir();uu();ir();Re=A("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=mb;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=vn(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,y=u._zod.check(s);if(y instanceof Promise&&a?.async===!1)throw new xr;if(l||y instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await y,s.issues.length!==d&&(c||(c=vn(s,d)))});else{if(s.issues.length===d)continue;c||(c=vn(s,d))}}return l?l.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new xr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=xn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return $n(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ls=A("$ZodString",(t,e)=>{Re.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Gy(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Oe=A("$ZodStringFormat",(t,e)=>{cs.init(t,e),ls.init(t,e)}),pu=A("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Cy),Oe.init(t,e)}),fu=A("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=su(n))}else e.pattern??(e.pattern=su());Oe.init(t,e)}),hu=A("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=zy),Oe.init(t,e)}),mu=A("$ZodURL",(t,e)=>{Oe.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Zy.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),gu=A("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Ny()),Oe.init(t,e)}),yu=A("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Iy),Oe.init(t,e)}),bu=A("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ty),Oe.init(t,e)}),_u=A("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ey),Oe.init(t,e)}),wu=A("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ry),Oe.init(t,e)}),vu=A("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Py),Oe.init(t,e)}),xu=A("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Ay),Oe.init(t,e)}),Sb=A("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ky(e)),Oe.init(t,e)}),Tb=A("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=By),Oe.init(t,e)}),Eb=A("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Hy(e)),Oe.init(t,e)}),Rb=A("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Oy),Oe.init(t,e)}),$u=A("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=jy),Oe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),ku=A("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ly),Oe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Su=A("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=My),Oe.init(t,e)}),Tu=A("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Dy),Oe.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Eu=A("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Uy),Oe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Pb(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Ru=A("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=iu),Oe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{NE(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Pu=A("$ZodE164",(t,e)=>{e.pattern??(e.pattern=qy),Oe.init(t,e)});Au=A("$ZodJWT",(t,e)=>{Oe.init(t,e),t._zod.check=r=>{jE(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Hi=A("$ZodNumber",(t,e)=>{Re.init(t,e),t._zod.pattern=t._zod.bag.pattern??Jy,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Iu=A("$ZodNumber",(t,e)=>{nb.init(t,e),Hi.init(t,e)}),Ou=A("$ZodBoolean",(t,e)=>{Re.init(t,e),t._zod.pattern=Yy,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),Cu=A("$ZodNull",(t,e)=>{Re.init(t,e),t._zod.pattern=Xy,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),zu=A("$ZodUnknown",(t,e)=>{Re.init(t,e),t._zod.parse=r=>r}),Nu=A("$ZodNever",(t,e)=>{Re.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});ju=A("$ZodArray",(t,e)=>{Re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(l=>gb(l,r,i))):gb(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Ki=A("$ZodObject",(t,e)=>{Re.init(t,e);let r=ns(()=>{let d=Object.keys(e.shape);for(let h of d)if(!(e.shape[h]instanceof Re))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let y=Hl(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(y)}});Ie(t._zod,"propValues",()=>{let d=e.shape,y={};for(let h in d){let f=d[h]._zod;if(f.values){y[h]??(y[h]=new Set);for(let g of f.values)y[h].add(g)}}return y});let n=d=>{let y=new Bi(["shape","payload","ctx"]),h=r.value,f=R=>{let C=wn(R);return`shape[${C}]._zod.run({ value: input[${C}], issues: [] }, ctx)`};y.write("const input = payload.value;");let g=Object.create(null),w=0;for(let R of h.keys)g[R]=`key_${w++}`;y.write("const newResult = {}");for(let R of h.keys)if(h.optionalKeys.has(R)){let C=g[R];y.write(`const ${C} = ${f(R)};`);let B=wn(R);y.write(`
901
- if (${C}.issues.length) {
902
- if (input[${B}] === undefined) {
903
- if (${B} in input) {
904
- newResult[${B}] = undefined;
955
+ `))}}});var bb,pu=O(()=>{bb={major:4,minor:0,patch:0}});function Ob(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function DE(t){if(!cu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Ob(r)}function UE(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function wb(t,e,r){t.issues.length&&e.issues.push(...sr(r,t.issues)),e.value[r]=t.value}function Vi(t,e,r){t.issues.length&&e.issues.push(...sr(r,t.issues)),e.value[r]=t.value}function _b(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...sr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function vb(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Ht(s,n,St())))}),e}function fu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(so(t)&&so(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=fu(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=fu(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function xb(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),xn(t))return t;let n=fu(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function $b(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function kb(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function Sb(t,e,r){return xn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Tb(t){return t.value=Object.freeze(t.value),t}function Eb(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Jl(o))}}var Re,us,Ce,hu,mu,gu,yu,bu,wu,_u,vu,xu,$u,ku,Rb,Pb,Ab,Ib,Su,Tu,Eu,Ru,Pu,Au,Iu,Ou,Hi,Cu,zu,Nu,ju,Lu,Mu,Ki,Gi,Du,Uu,Zu,qu,Fu,Bu,Vu,Hu,Ku,Gu,Wu,Ju,Yu,Xu,Qu,Cb=O(()=>{Fi();no();du();iu();qi();ir();pu();ir();Re=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=bb;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=xn(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,b=u._zod.check(s);if(b instanceof Promise&&a?.async===!1)throw new $r;if(l||b instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await b,s.issues.length!==d&&(c||(c=xn(s,d)))});else{if(s.issues.length===d)continue;c||(c=xn(s,d))}}return l?l.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new $r;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=$n(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return kn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),us=I("$ZodString",(t,e)=>{Re.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Yy(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Ce=I("$ZodStringFormat",(t,e)=>{ls.init(t,e),us.init(t,e)}),hu=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=jy),Ce.init(t,e)}),mu=I("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=au(n))}else e.pattern??(e.pattern=au());Ce.init(t,e)}),gu=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Ly),Ce.init(t,e)}),yu=I("$ZodURL",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:By.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),bu=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=My()),Ce.init(t,e)}),wu=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=zy),Ce.init(t,e)}),_u=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Py),Ce.init(t,e)}),vu=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ay),Ce.init(t,e)}),xu=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Iy),Ce.init(t,e)}),$u=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Oy),Ce.init(t,e)}),ku=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Cy),Ce.init(t,e)}),Rb=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Jy(e)),Ce.init(t,e)}),Pb=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ky),Ce.init(t,e)}),Ab=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Wy(e)),Ce.init(t,e)}),Ib=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ny),Ce.init(t,e)}),Su=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Dy),Ce.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Tu=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Uy),Ce.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Eu=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Zy),Ce.init(t,e)}),Ru=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=qy),Ce.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Pu=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Fy),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Ob(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Au=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=cu),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{DE(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Iu=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Vy),Ce.init(t,e)});Ou=I("$ZodJWT",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{UE(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Hi=I("$ZodNumber",(t,e)=>{Re.init(t,e),t._zod.pattern=t._zod.bag.pattern??Qy,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Cu=I("$ZodNumber",(t,e)=>{ib.init(t,e),Hi.init(t,e)}),zu=I("$ZodBoolean",(t,e)=>{Re.init(t,e),t._zod.pattern=eb,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),Nu=I("$ZodNull",(t,e)=>{Re.init(t,e),t._zod.pattern=tb,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),ju=I("$ZodUnknown",(t,e)=>{Re.init(t,e),t._zod.parse=r=>r}),Lu=I("$ZodNever",(t,e)=>{Re.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Mu=I("$ZodArray",(t,e)=>{Re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(l=>wb(l,r,i))):wb(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Ki=I("$ZodObject",(t,e)=>{Re.init(t,e);let r=os(()=>{let d=Object.keys(e.shape);for(let h of d)if(!(e.shape[h]instanceof Re))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let b=Gl(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(b)}});Oe(t._zod,"propValues",()=>{let d=e.shape,b={};for(let h in d){let f=d[h]._zod;if(f.values){b[h]??(b[h]=new Set);for(let y of f.values)b[h].add(y)}}return b});let n=d=>{let b=new Bi(["shape","payload","ctx"]),h=r.value,f=R=>{let z=vn(R);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};b.write("const input = payload.value;");let y=Object.create(null),v=0;for(let R of h.keys)y[R]=`key_${v++}`;b.write("const newResult = {}");for(let R of h.keys)if(h.optionalKeys.has(R)){let z=y[R];b.write(`const ${z} = ${f(R)};`);let V=vn(R);b.write(`
956
+ if (${z}.issues.length) {
957
+ if (input[${V}] === undefined) {
958
+ if (${V} in input) {
959
+ newResult[${V}] = undefined;
905
960
  }
906
961
  } else {
907
962
  payload.issues = payload.issues.concat(
908
- ${C}.issues.map((iss) => ({
963
+ ${z}.issues.map((iss) => ({
909
964
  ...iss,
910
- path: iss.path ? [${B}, ...iss.path] : [${B}],
965
+ path: iss.path ? [${V}, ...iss.path] : [${V}],
911
966
  }))
912
967
  );
913
968
  }
914
- } else if (${C}.value === undefined) {
915
- if (${B} in input) newResult[${B}] = undefined;
969
+ } else if (${z}.value === undefined) {
970
+ if (${V} in input) newResult[${V}] = undefined;
916
971
  } else {
917
- newResult[${B}] = ${C}.value;
972
+ newResult[${V}] = ${z}.value;
918
973
  }
919
- `)}else{let C=g[R];y.write(`const ${C} = ${f(R)};`),y.write(`
920
- if (${C}.issues.length) payload.issues = payload.issues.concat(${C}.issues.map(iss => ({
974
+ `)}else{let z=y[R];b.write(`const ${z} = ${f(R)};`),b.write(`
975
+ if (${z}.issues.length) payload.issues = payload.issues.concat(${z}.issues.map(iss => ({
921
976
  ...iss,
922
- path: iss.path ? [${wn(R)}, ...iss.path] : [${wn(R)}]
923
- })));`),y.write(`newResult[${wn(R)}] = ${C}.value`)}y.write("payload.value = newResult;"),y.write("return payload;");let E=y.compile();return(R,C)=>E(d,R,C)},o,s=to,i=!ji.jitless,c=i&&Bl.value,l=e.catchall,u;t._zod.parse=(d,y)=>{u??(u=r.value);let h=d.value;if(!s(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;let f=[];if(i&&c&&y?.async===!1&&y.jitless!==!0)o||(o=n(e.shape)),d=o(d,y);else{d.value={};let C=u.shape;for(let B of u.keys){let W=C[B],He=W._zod.run({value:h[B],issues:[]},y),Xe=W._zod.optin==="optional"&&W._zod.optout==="optional";He instanceof Promise?f.push(He.then(St=>Xe?yb(St,d,B,h):Vi(St,d,B))):Xe?yb(He,d,B,h):Vi(He,d,B)}}if(!l)return f.length?Promise.all(f).then(()=>d):d;let g=[],w=u.keySet,E=l._zod,R=E.def.type;for(let C of Object.keys(h)){if(w.has(C))continue;if(R==="never"){g.push(C);continue}let B=E.run({value:h[C],issues:[]},y);B instanceof Promise?f.push(B.then(W=>Vi(W,d,C))):Vi(B,d,C)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:h,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Gi=A("$ZodUnion",(t,e)=>{Re.init(t,e),Ie(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ie(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ie(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ie(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>ss(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>bb(i,r,t,n)):bb(s,r,t,n)}}),Lu=A("$ZodDiscriminatedUnion",(t,e)=>{Gi.init(t,e);let r=t._zod.parse;Ie(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=ns(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!to(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Mu=A("$ZodIntersection",(t,e)=>{Re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,l])=>_b(r,c,l)):_b(r,s,i)}});Du=A("$ZodRecord",(t,e)=>{Re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!ro(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...sr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...sr(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>Kt(l,n,Tt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...sr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...sr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Uu=A("$ZodEnum",(t,e)=>{Re.init(t,e);let r=rs(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Vl.has(typeof n)).map(n=>typeof n=="string"?Mr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Zu=A("$ZodLiteral",(t,e)=>{Re.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Mr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),qu=A("$ZodTransform",(t,e)=>{Re.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new xr;return r.value=o,r}}),Fu=A("$ZodOptional",(t,e)=>{Re.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ie(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ie(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ss(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Bu=A("$ZodNullable",(t,e)=>{Re.init(t,e),Ie(t._zod,"optin",()=>e.innerType._zod.optin),Ie(t._zod,"optout",()=>e.innerType._zod.optout),Ie(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ss(r.source)}|null)$`):void 0}),Ie(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Vu=A("$ZodDefault",(t,e)=>{Re.init(t,e),t._zod.optin="optional",Ie(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>wb(s,e)):wb(o,e)}});Hu=A("$ZodPrefault",(t,e)=>{Re.init(t,e),t._zod.optin="optional",Ie(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Ku=A("$ZodNonOptional",(t,e)=>{Re.init(t,e),Ie(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>vb(s,t)):vb(o,t)}});Gu=A("$ZodCatch",(t,e)=>{Re.init(t,e),t._zod.optin="optional",Ie(t._zod,"optout",()=>e.innerType._zod.optout),Ie(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Kt(i,n,Tt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Kt(s,n,Tt()))},input:r.value}),r.issues=[]),r)}}),Wu=A("$ZodPipe",(t,e)=>{Re.init(t,e),Ie(t._zod,"values",()=>e.in._zod.values),Ie(t._zod,"optin",()=>e.in._zod.optin),Ie(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>xb(s,e,n)):xb(o,e,n)}});Ju=A("$ZodReadonly",(t,e)=>{Re.init(t,e),Ie(t._zod,"propValues",()=>e.innerType._zod.propValues),Ie(t._zod,"values",()=>e.innerType._zod.values),Ie(t._zod,"optin",()=>e.innerType._zod.optin),Ie(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then($b):$b(o)}});Yu=A("$ZodCustom",(t,e)=>{et.init(t,e),Re.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>kb(s,r,n,t));kb(o,r,n,t)}})});function Ib(){return{localeError:ME()}}var LE,ME,Ob=O(()=>{ir();LE=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},ME=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${LE(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Di(n.values[0])}`:`Invalid option: expected one of ${Li(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Li(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Wi=O(()=>{});function Cb(){return new us}var us,Dr,Qu=O(()=>{us=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Dr=Cb()});function ed(t,e){return new t({type:"string",...X(e)})}function td(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...X(e)})}function Ji(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...X(e)})}function rd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...X(e)})}function nd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(e)})}function od(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(e)})}function sd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(e)})}function id(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...X(e)})}function ad(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...X(e)})}function cd(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(e)})}function ld(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...X(e)})}function ud(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(e)})}function dd(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...X(e)})}function pd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...X(e)})}function fd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(e)})}function hd(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(e)})}function md(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(e)})}function gd(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(e)})}function yd(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(e)})}function bd(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...X(e)})}function _d(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...X(e)})}function wd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...X(e)})}function vd(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...X(e)})}function zb(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(e)})}function Nb(t,e){return new t({type:"string",format:"date",check:"string_format",...X(e)})}function jb(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...X(e)})}function Lb(t,e){return new t({type:"string",format:"duration",check:"string_format",...X(e)})}function xd(t,e){return new t({type:"number",checks:[],...X(e)})}function $d(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...X(e)})}function kd(t,e){return new t({type:"boolean",...X(e)})}function Sd(t,e){return new t({type:"null",...X(e)})}function Td(t){return new t({type:"unknown"})}function Ed(t,e){return new t({type:"never",...X(e)})}function Yi(t,e){return new au({check:"less_than",...X(e),value:t,inclusive:!1})}function ds(t,e){return new au({check:"less_than",...X(e),value:t,inclusive:!0})}function Xi(t,e){return new cu({check:"greater_than",...X(e),value:t,inclusive:!1})}function ps(t,e){return new cu({check:"greater_than",...X(e),value:t,inclusive:!0})}function Qi(t,e){return new rb({check:"multiple_of",...X(e),value:t})}function ea(t,e){return new ob({check:"max_length",...X(e),maximum:t})}function no(t,e){return new sb({check:"min_length",...X(e),minimum:t})}function ta(t,e){return new ib({check:"length_equals",...X(e),length:t})}function Rd(t,e){return new ab({check:"string_format",format:"regex",...X(e),pattern:t})}function Pd(t){return new cb({check:"string_format",format:"lowercase",...X(t)})}function Ad(t){return new lb({check:"string_format",format:"uppercase",...X(t)})}function Id(t,e){return new ub({check:"string_format",format:"includes",...X(e),includes:t})}function Od(t,e){return new db({check:"string_format",format:"starts_with",...X(e),prefix:t})}function Cd(t,e){return new pb({check:"string_format",format:"ends_with",...X(e),suffix:t})}function kn(t){return new fb({check:"overwrite",tx:t})}function zd(t){return kn(e=>e.normalize(t))}function Nd(){return kn(t=>t.trim())}function jd(){return kn(t=>t.toLowerCase())}function Ld(){return kn(t=>t.toUpperCase())}function Mb(t,e,r){return new t({type:"array",element:e,...X(r)})}function Md(t,e,r){let n=X(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Dd(t,e,r){return new t({type:"custom",check:"custom",fn:e,...X(r)})}var Db=O(()=>{Fi();ir()});var Ub=O(()=>{});function Ud(t,e){if(t instanceof us){let n=new ra(e),o={};for(let a of t._idmap.entries()){let[c,l]=a;n.process(l)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,l]=a;s[c]=n.emit(l,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new ra(e);return r.process(t),r.emit(t,e)}function We(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return We(o.element,r);case"object":{for(let s in o.shape)if(We(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(We(s,r))return!0;return!1}case"intersection":return We(o.left,r)||We(o.right,r);case"tuple":{for(let s of o.items)if(We(s,r))return!0;return!!(o.rest&&We(o.rest,r))}case"record":return We(o.keyType,r)||We(o.valueType,r);case"map":return We(o.keyType,r)||We(o.valueType,r);case"set":return We(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return We(o.innerType,r);case"lazy":return We(o.getter(),r);case"default":return We(o.innerType,r);case"prefault":return We(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return We(o.in,r)||We(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var ra,Zb=O(()=>{Qu();ir();ra=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Dr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},y=e._zod.parent;if(y)a.ref=y,this.process(y,d),this.seen.get(y).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let f=h;f.type="string";let{minimum:g,maximum:w,format:E,patterns:R,contentEncoding:C}=e._zod.bag;if(typeof g=="number"&&(f.minLength=g),typeof w=="number"&&(f.maxLength=w),E&&(f.format=s[E]??E,f.format===""&&delete f.format),C&&(f.contentEncoding=C),R&&R.size>0){let B=[...R];B.length===1?f.pattern=B[0].source:B.length>1&&(a.schema.allOf=[...B.map(W=>({...this.target==="draft-7"?{type:"string"}:{},pattern:W.source}))])}break}case"number":{let f=h,{minimum:g,maximum:w,format:E,multipleOf:R,exclusiveMaximum:C,exclusiveMinimum:B}=e._zod.bag;typeof E=="string"&&E.includes("int")?f.type="integer":f.type="number",typeof B=="number"&&(f.exclusiveMinimum=B),typeof g=="number"&&(f.minimum=g,typeof B=="number"&&(B>=g?delete f.minimum:delete f.exclusiveMinimum)),typeof C=="number"&&(f.exclusiveMaximum=C),typeof w=="number"&&(f.maximum=w,typeof C=="number"&&(C<=w?delete f.maximum:delete f.exclusiveMaximum)),typeof R=="number"&&(f.multipleOf=R);break}case"boolean":{let f=h;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=h,{minimum:g,maximum:w}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof w=="number"&&(f.maxItems=w),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=h;f.type="object",f.properties={};let g=o.shape;for(let R in g)f.properties[R]=this.process(g[R],{...d,path:[...d.path,"properties",R]});let w=new Set(Object.keys(g)),E=new Set([...w].filter(R=>{let C=o.shape[R]._zod;return this.io==="input"?C.optin===void 0:C.optout===void 0}));E.size>0&&(f.required=Array.from(E)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=h;f.anyOf=o.options.map((g,w)=>this.process(g,{...d,path:[...d.path,"anyOf",w]}));break}case"intersection":{let f=h,g=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),w=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),E=C=>"allOf"in C&&Object.keys(C).length===1,R=[...E(g)?g.allOf:[g],...E(w)?w.allOf:[w]];f.allOf=R;break}case"tuple":{let f=h;f.type="array";let g=o.items.map((R,C)=>this.process(R,{...d,path:[...d.path,"prefixItems",C]}));if(this.target==="draft-2020-12"?f.prefixItems=g:f.items=g,o.rest){let R=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=R:f.additionalItems=R}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:w,maximum:E}=e._zod.bag;typeof w=="number"&&(f.minItems=w),typeof E=="number"&&(f.maxItems=E);break}case"record":{let f=h;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=h,g=rs(o.entries);g.every(w=>typeof w=="number")&&(f.type="number"),g.every(w=>typeof w=="string")&&(f.type="string"),f.enum=g;break}case"literal":{let f=h,g=[];for(let w of o.values)if(w===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof w=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(w))}else g.push(w);if(g.length!==0)if(g.length===1){let w=g[0];f.type=w===null?"null":typeof w,f.const=w}else g.every(w=>typeof w=="number")&&(f.type="number"),g.every(w=>typeof w=="string")&&(f.type="string"),g.every(w=>typeof w=="boolean")&&(f.type="string"),g.every(w=>w===null)&&(f.type="null"),f.enum=g;break}case"file":{let f=h,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:w,maximum:E,mime:R}=e._zod.bag;w!==void 0&&(g.minLength=w),E!==void 0&&(g.maxLength=E),R?R.length===1?(g.contentMediaType=R[0],Object.assign(f,g)):f.anyOf=R.map(C=>({...g,contentMediaType:C})):Object.assign(f,g);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);h.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=h;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=h,g=e._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=g.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&We(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=u=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let g=n.external.registry.get(u[0])?.id,w=n.external.uri??(R=>R);if(g)return{ref:w(g)};let E=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=E,{defId:E,ref:`${w("__shared")}#/${d}/${E}`}}if(u[1]===o)return{ref:"#"};let h=`#/${d}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:h+f}},i=u=>{if(u[1].schema.$ref)return;let d=u[1],{ref:y,defId:h}=s(u);d.def={...d.schema},h&&(d.defId=h);let f=d.schema;for(let g in f)delete f[g];f.$ref=y};if(n.cycles==="throw")for(let u of this.seen.entries()){let d=u[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
977
+ path: iss.path ? [${vn(R)}, ...iss.path] : [${vn(R)}]
978
+ })));`),b.write(`newResult[${vn(R)}] = ${z}.value`)}b.write("payload.value = newResult;"),b.write("return payload;");let E=b.compile();return(R,z)=>E(d,R,z)},o,s=oo,i=!ji.jitless,c=i&&Hl.value,l=e.catchall,u;t._zod.parse=(d,b)=>{u??(u=r.value);let h=d.value;if(!s(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),d;let f=[];if(i&&c&&b?.async===!1&&b.jitless!==!0)o||(o=n(e.shape)),d=o(d,b);else{d.value={};let z=u.shape;for(let V of u.keys){let J=z[V],He=J._zod.run({value:h[V],issues:[]},b),Xe=J._zod.optin==="optional"&&J._zod.optout==="optional";He instanceof Promise?f.push(He.then(Rr=>Xe?_b(Rr,d,V,h):Vi(Rr,d,V))):Xe?_b(He,d,V,h):Vi(He,d,V)}}if(!l)return f.length?Promise.all(f).then(()=>d):d;let y=[],v=u.keySet,E=l._zod,R=E.def.type;for(let z of Object.keys(h)){if(v.has(z))continue;if(R==="never"){y.push(z);continue}let V=E.run({value:h[z],issues:[]},b);V instanceof Promise?f.push(V.then(J=>Vi(J,d,z))):Vi(V,d,z)}return y.length&&d.issues.push({code:"unrecognized_keys",keys:y,input:h,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Gi=I("$ZodUnion",(t,e)=>{Re.init(t,e),Oe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Oe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Oe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Oe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>is(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>vb(i,r,t,n)):vb(s,r,t,n)}}),Du=I("$ZodDiscriminatedUnion",(t,e)=>{Gi.init(t,e);let r=t._zod.parse;Oe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=os(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!oo(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Uu=I("$ZodIntersection",(t,e)=>{Re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,l])=>xb(r,c,l)):xb(r,s,i)}});Zu=I("$ZodRecord",(t,e)=>{Re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!so(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...sr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...sr(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>Ht(l,n,St())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...sr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...sr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),qu=I("$ZodEnum",(t,e)=>{Re.init(t,e);let r=ns(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Kl.has(typeof n)).map(n=>typeof n=="string"?Dr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Fu=I("$ZodLiteral",(t,e)=>{Re.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Dr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),Bu=I("$ZodTransform",(t,e)=>{Re.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new $r;return r.value=o,r}}),Vu=I("$ZodOptional",(t,e)=>{Re.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Oe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Oe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${is(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Hu=I("$ZodNullable",(t,e)=>{Re.init(t,e),Oe(t._zod,"optin",()=>e.innerType._zod.optin),Oe(t._zod,"optout",()=>e.innerType._zod.optout),Oe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${is(r.source)}|null)$`):void 0}),Oe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Ku=I("$ZodDefault",(t,e)=>{Re.init(t,e),t._zod.optin="optional",Oe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>$b(s,e)):$b(o,e)}});Gu=I("$ZodPrefault",(t,e)=>{Re.init(t,e),t._zod.optin="optional",Oe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Wu=I("$ZodNonOptional",(t,e)=>{Re.init(t,e),Oe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>kb(s,t)):kb(o,t)}});Ju=I("$ZodCatch",(t,e)=>{Re.init(t,e),t._zod.optin="optional",Oe(t._zod,"optout",()=>e.innerType._zod.optout),Oe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Ht(i,n,St()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Ht(s,n,St()))},input:r.value}),r.issues=[]),r)}}),Yu=I("$ZodPipe",(t,e)=>{Re.init(t,e),Oe(t._zod,"values",()=>e.in._zod.values),Oe(t._zod,"optin",()=>e.in._zod.optin),Oe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Sb(s,e,n)):Sb(o,e,n)}});Xu=I("$ZodReadonly",(t,e)=>{Re.init(t,e),Oe(t._zod,"propValues",()=>e.innerType._zod.propValues),Oe(t._zod,"values",()=>e.innerType._zod.values),Oe(t._zod,"optin",()=>e.innerType._zod.optin),Oe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Tb):Tb(o)}});Qu=I("$ZodCustom",(t,e)=>{et.init(t,e),Re.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Eb(s,r,n,t));Eb(o,r,n,t)}})});function zb(){return{localeError:qE()}}var ZE,qE,Nb=O(()=>{ir();ZE=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},qE=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${ZE(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Di(n.values[0])}`:`Invalid option: expected one of ${Li(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Li(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Wi=O(()=>{});function jb(){return new ds}var ds,Ur,td=O(()=>{ds=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Ur=jb()});function rd(t,e){return new t({type:"string",...Q(e)})}function nd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Q(e)})}function Ji(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Q(e)})}function od(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Q(e)})}function sd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Q(e)})}function id(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Q(e)})}function ad(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Q(e)})}function cd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Q(e)})}function ld(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Q(e)})}function ud(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Q(e)})}function dd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Q(e)})}function pd(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Q(e)})}function fd(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Q(e)})}function hd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Q(e)})}function md(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Q(e)})}function gd(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Q(e)})}function yd(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Q(e)})}function bd(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Q(e)})}function wd(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Q(e)})}function _d(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Q(e)})}function vd(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Q(e)})}function xd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Q(e)})}function $d(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Q(e)})}function Lb(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Q(e)})}function Mb(t,e){return new t({type:"string",format:"date",check:"string_format",...Q(e)})}function Db(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Q(e)})}function Ub(t,e){return new t({type:"string",format:"duration",check:"string_format",...Q(e)})}function kd(t,e){return new t({type:"number",checks:[],...Q(e)})}function Sd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Q(e)})}function Td(t,e){return new t({type:"boolean",...Q(e)})}function Ed(t,e){return new t({type:"null",...Q(e)})}function Rd(t){return new t({type:"unknown"})}function Pd(t,e){return new t({type:"never",...Q(e)})}function Yi(t,e){return new lu({check:"less_than",...Q(e),value:t,inclusive:!1})}function ps(t,e){return new lu({check:"less_than",...Q(e),value:t,inclusive:!0})}function Xi(t,e){return new uu({check:"greater_than",...Q(e),value:t,inclusive:!1})}function fs(t,e){return new uu({check:"greater_than",...Q(e),value:t,inclusive:!0})}function Qi(t,e){return new sb({check:"multiple_of",...Q(e),value:t})}function ea(t,e){return new ab({check:"max_length",...Q(e),maximum:t})}function io(t,e){return new cb({check:"min_length",...Q(e),minimum:t})}function ta(t,e){return new lb({check:"length_equals",...Q(e),length:t})}function Ad(t,e){return new ub({check:"string_format",format:"regex",...Q(e),pattern:t})}function Id(t){return new db({check:"string_format",format:"lowercase",...Q(t)})}function Od(t){return new pb({check:"string_format",format:"uppercase",...Q(t)})}function Cd(t,e){return new fb({check:"string_format",format:"includes",...Q(e),includes:t})}function zd(t,e){return new hb({check:"string_format",format:"starts_with",...Q(e),prefix:t})}function Nd(t,e){return new mb({check:"string_format",format:"ends_with",...Q(e),suffix:t})}function Sn(t){return new gb({check:"overwrite",tx:t})}function jd(t){return Sn(e=>e.normalize(t))}function Ld(){return Sn(t=>t.trim())}function Md(){return Sn(t=>t.toLowerCase())}function Dd(){return Sn(t=>t.toUpperCase())}function Zb(t,e,r){return new t({type:"array",element:e,...Q(r)})}function Ud(t,e,r){let n=Q(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Zd(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Q(r)})}var qb=O(()=>{Fi();ir()});var Fb=O(()=>{});function qd(t,e){if(t instanceof ds){let n=new ra(e),o={};for(let a of t._idmap.entries()){let[c,l]=a;n.process(l)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,l]=a;s[c]=n.emit(l,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new ra(e);return r.process(t),r.emit(t,e)}function We(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return We(o.element,r);case"object":{for(let s in o.shape)if(We(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(We(s,r))return!0;return!1}case"intersection":return We(o.left,r)||We(o.right,r);case"tuple":{for(let s of o.items)if(We(s,r))return!0;return!!(o.rest&&We(o.rest,r))}case"record":return We(o.keyType,r)||We(o.valueType,r);case"map":return We(o.keyType,r)||We(o.valueType,r);case"set":return We(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return We(o.innerType,r);case"lazy":return We(o.getter(),r);case"default":return We(o.innerType,r);case"prefault":return We(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return We(o.in,r)||We(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var ra,Bb=O(()=>{td();ir();ra=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ur,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},b=e._zod.parent;if(b)a.ref=b,this.process(b,d),this.seen.get(b).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let f=h;f.type="string";let{minimum:y,maximum:v,format:E,patterns:R,contentEncoding:z}=e._zod.bag;if(typeof y=="number"&&(f.minLength=y),typeof v=="number"&&(f.maxLength=v),E&&(f.format=s[E]??E,f.format===""&&delete f.format),z&&(f.contentEncoding=z),R&&R.size>0){let V=[...R];V.length===1?f.pattern=V[0].source:V.length>1&&(a.schema.allOf=[...V.map(J=>({...this.target==="draft-7"?{type:"string"}:{},pattern:J.source}))])}break}case"number":{let f=h,{minimum:y,maximum:v,format:E,multipleOf:R,exclusiveMaximum:z,exclusiveMinimum:V}=e._zod.bag;typeof E=="string"&&E.includes("int")?f.type="integer":f.type="number",typeof V=="number"&&(f.exclusiveMinimum=V),typeof y=="number"&&(f.minimum=y,typeof V=="number"&&(V>=y?delete f.minimum:delete f.exclusiveMinimum)),typeof z=="number"&&(f.exclusiveMaximum=z),typeof v=="number"&&(f.maximum=v,typeof z=="number"&&(z<=v?delete f.maximum:delete f.exclusiveMaximum)),typeof R=="number"&&(f.multipleOf=R);break}case"boolean":{let f=h;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=h,{minimum:y,maximum:v}=e._zod.bag;typeof y=="number"&&(f.minItems=y),typeof v=="number"&&(f.maxItems=v),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=h;f.type="object",f.properties={};let y=o.shape;for(let R in y)f.properties[R]=this.process(y[R],{...d,path:[...d.path,"properties",R]});let v=new Set(Object.keys(y)),E=new Set([...v].filter(R=>{let z=o.shape[R]._zod;return this.io==="input"?z.optin===void 0:z.optout===void 0}));E.size>0&&(f.required=Array.from(E)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=h;f.anyOf=o.options.map((y,v)=>this.process(y,{...d,path:[...d.path,"anyOf",v]}));break}case"intersection":{let f=h,y=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),v=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),E=z=>"allOf"in z&&Object.keys(z).length===1,R=[...E(y)?y.allOf:[y],...E(v)?v.allOf:[v]];f.allOf=R;break}case"tuple":{let f=h;f.type="array";let y=o.items.map((R,z)=>this.process(R,{...d,path:[...d.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?f.prefixItems=y:f.items=y,o.rest){let R=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=R:f.additionalItems=R}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:v,maximum:E}=e._zod.bag;typeof v=="number"&&(f.minItems=v),typeof E=="number"&&(f.maxItems=E);break}case"record":{let f=h;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=h,y=ns(o.entries);y.every(v=>typeof v=="number")&&(f.type="number"),y.every(v=>typeof v=="string")&&(f.type="string"),f.enum=y;break}case"literal":{let f=h,y=[];for(let v of o.values)if(v===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof v=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");y.push(Number(v))}else y.push(v);if(y.length!==0)if(y.length===1){let v=y[0];f.type=v===null?"null":typeof v,f.const=v}else y.every(v=>typeof v=="number")&&(f.type="number"),y.every(v=>typeof v=="string")&&(f.type="string"),y.every(v=>typeof v=="boolean")&&(f.type="string"),y.every(v=>v===null)&&(f.type="null"),f.enum=y;break}case"file":{let f=h,y={type:"string",format:"binary",contentEncoding:"binary"},{minimum:v,maximum:E,mime:R}=e._zod.bag;v!==void 0&&(y.minLength=v),E!==void 0&&(y.maxLength=E),R?R.length===1?(y.contentMediaType=R[0],Object.assign(f,y)):f.anyOf=R.map(z=>({...y,contentMediaType:z})):Object.assign(f,y);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);h.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=h;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=h,y=e._zod.pattern;if(!y)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=y.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&We(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=u=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let y=n.external.registry.get(u[0])?.id,v=n.external.uri??(R=>R);if(y)return{ref:v(y)};let E=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=E,{defId:E,ref:`${v("__shared")}#/${d}/${E}`}}if(u[1]===o)return{ref:"#"};let h=`#/${d}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:h+f}},i=u=>{if(u[1].schema.$ref)return;let d=u[1],{ref:b,defId:h}=s(u);d.def={...d.schema},h&&(d.defId=h);let f=d.schema;for(let y in f)delete f[y];f.$ref=b};if(n.cycles==="throw")for(let u of this.seen.entries()){let d=u[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
924
979
 
925
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let d=u[1];if(e===u[0]){i(u);continue}if(n.external){let h=n.external.registry.get(u[0])?.id;if(e!==u[0]&&h){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(d.cycle){i(u);continue}if(d.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,d)=>{let y=this.seen.get(u),h=y.def??y.schema,f={...h};if(y.ref===null)return;let g=y.ref;if(y.ref=null,g){a(g,d);let w=this.seen.get(g).schema;w.$ref&&d.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(w)):(Object.assign(h,w),Object.assign(h,f))}y.isParent||this.override({zodSchema:u,jsonSchema:h,path:y.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,o.def);let l=n.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(l[d.defId]=d.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var qb=O(()=>{});var ut=O(()=>{eo();ou();Yl();Ab();Fi();uu();ir();qi();Wi();Qu();lu();Ub();Db();Zb();qb()});var Zd=O(()=>{ut()});function qd(t,e){let r={type:"object",get shape(){return fe.assignProp(this,"shape",{...t}),this.shape},...fe.normalizeParams(e)};return new wR(r)}var _R,wR,Fb=O(()=>{ut();ut();Zd();_R=A("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Re.init(t,e),t.def=e,t.parse=(r,n)=>Ql(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>xn(t,r,n),t.parseAsync=async(r,n)=>tu(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>$n(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Et(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),wR=A("ZodMiniObject",(t,e)=>{Ki.init(t,e),_R.init(t,e),fe.defineLazy(t,"shape",()=>e.shape)})});var Bb=O(()=>{});var Vb=O(()=>{});var Hb=O(()=>{});var Kb=O(()=>{ut();Zd();Fb();Bb();ut();Wi();Vb();Hb()});var Gb=O(()=>{Kb()});var Fd=O(()=>{Gb()});function ar(t){return!!t._zod}function Tn(t){let e=Object.values(t);if(e.length===0)return qd({});let r=e.every(ar),n=e.every(o=>!ar(o));if(r)return qd(t);if(n)return Wc(t);throw new Error("Mixed Zod versions detected in object shape.")}function Ur(t,e){return ar(t)?xn(t,e):t.safeParse(e)}async function na(t,e){return ar(t)?await $n(t,e):await t.safeParseAsync(e)}function Zr(t){if(!t)return;let e;if(ar(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function oo(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Tn(t)}}if(ar(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function $R(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function oa(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${$R(e.path)}`:e.message).join(`
926
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Jb(t){return t.description}function Yb(t){if(ar(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function so(t){if(ar(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var fs=O(()=>{es();Fd()});var Bd=O(()=>{ut()});var hs={};No(hs,{ZodISODate:()=>Qb,ZodISODateTime:()=>Xb,ZodISODuration:()=>t_,ZodISOTime:()=>e_,date:()=>Hd,datetime:()=>Vd,duration:()=>Gd,time:()=>Kd});function Vd(t){return zb(Xb,t)}function Hd(t){return Nb(Qb,t)}function Kd(t){return jb(e_,t)}function Gd(t){return Lb(t_,t)}var Xb,Qb,e_,t_,Wd=O(()=>{ut();Jd();Xb=A("ZodISODateTime",(t,e)=>{Sb.init(t,e),De.init(t,e)});Qb=A("ZodISODate",(t,e)=>{Tb.init(t,e),De.init(t,e)});e_=A("ZodISOTime",(t,e)=>{Eb.init(t,e),De.init(t,e)});t_=A("ZodISODuration",(t,e)=>{Rb.init(t,e),De.init(t,e)})});var r_,rZ,ms,Yd=O(()=>{ut();ut();r_=(t,e)=>{Ui.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Jl(t,r)},flatten:{value:r=>Wl(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},rZ=A("ZodError",r_),ms=A("ZodError",r_,{Parent:Error})});var n_,o_,s_,i_,Xd=O(()=>{ut();Yd();n_=Xl(ms),o_=eu(ms),s_=ru(ms),i_=nu(ms)});function P(t){return ed(IR,t)}function Se(t){return xd(d_,t)}function c_(t){return $d(WR,t)}function Ye(t){return kd(JR,t)}function p_(t){return Sd(YR,t)}function Ue(){return Td(XR)}function eP(t){return Ed(QR,t)}function me(t,e){return Mb(tP,t,e)}function F(t,e){let r={type:"object",get shape(){return fe.assignProp(this,"shape",{...t}),this.shape},...fe.normalizeParams(e)};return new f_(r)}function dt(t,e){return new f_({type:"object",get shape(){return fe.assignProp(this,"shape",{...t}),this.shape},catchall:Ue(),...fe.normalizeParams(e)})}function ze(t,e){return new h_({type:"union",options:t,...fe.normalizeParams(e)})}function tp(t,e,r){return new rP({type:"union",options:e,discriminator:t,...fe.normalizeParams(r)})}function ia(t,e){return new nP({type:"intersection",left:t,right:e})}function Ce(t,e,r){return new oP({type:"record",keyType:t,valueType:e,...fe.normalizeParams(r)})}function wt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Qd({type:"enum",entries:r,...fe.normalizeParams(e)})}function K(t,e){return new sP({type:"literal",values:Array.isArray(t)?t:[t],...fe.normalizeParams(e)})}function m_(t){return new iP({type:"transform",transform:t})}function Ze(t){return new g_({type:"optional",innerType:t})}function l_(t){return new aP({type:"nullable",innerType:t})}function lP(t,e){return new cP({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function dP(t,e){return new uP({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function pP(t,e){return new y_({type:"nonoptional",innerType:t,...fe.normalizeParams(e)})}function hP(t,e){return new fP({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function ep(t,e){return new mP({type:"pipe",in:t,out:e})}function yP(t){return new gP({type:"readonly",innerType:t})}function bP(t){let e=new et({check:"custom"});return e._zod.check=t,e}function __(t,e){return Md(b_,t??(()=>!0),e)}function _P(t,e={}){return Dd(b_,t,e)}function wP(t){let e=bP(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(fe.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(fe.issue(o))}},t(r.value,r)));return e}function rp(t,e){return ep(m_(t),e)}var Fe,u_,IR,De,OR,a_,sa,CR,zR,NR,jR,LR,MR,DR,UR,ZR,qR,FR,BR,VR,HR,KR,GR,d_,WR,JR,YR,XR,QR,tP,f_,h_,rP,nP,oP,Qd,sP,iP,g_,aP,cP,uP,y_,fP,mP,gP,b_,Jd=O(()=>{ut();ut();Bd();Wd();Xd();Fe=A("ZodType",(t,e)=>(Re.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Et(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>n_(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>s_(t,r,n),t.parseAsync=async(r,n)=>o_(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>i_(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(_P(r,n)),t.superRefine=r=>t.check(wP(r)),t.overwrite=r=>t.check(kn(r)),t.optional=()=>Ze(t),t.nullable=()=>l_(t),t.nullish=()=>Ze(l_(t)),t.nonoptional=r=>pP(t,r),t.array=()=>me(t),t.or=r=>ze([t,r]),t.and=r=>ia(t,r),t.transform=r=>ep(t,m_(r)),t.default=r=>lP(t,r),t.prefault=r=>dP(t,r),t.catch=r=>hP(t,r),t.pipe=r=>ep(t,r),t.readonly=()=>yP(t),t.describe=r=>{let n=t.clone();return Dr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Dr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Dr.get(t);let n=t.clone();return Dr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),u_=A("_ZodString",(t,e)=>{ls.init(t,e),Fe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Rd(...n)),t.includes=(...n)=>t.check(Id(...n)),t.startsWith=(...n)=>t.check(Od(...n)),t.endsWith=(...n)=>t.check(Cd(...n)),t.min=(...n)=>t.check(no(...n)),t.max=(...n)=>t.check(ea(...n)),t.length=(...n)=>t.check(ta(...n)),t.nonempty=(...n)=>t.check(no(1,...n)),t.lowercase=n=>t.check(Pd(n)),t.uppercase=n=>t.check(Ad(n)),t.trim=()=>t.check(Nd()),t.normalize=(...n)=>t.check(zd(...n)),t.toLowerCase=()=>t.check(jd()),t.toUpperCase=()=>t.check(Ld())}),IR=A("ZodString",(t,e)=>{ls.init(t,e),u_.init(t,e),t.email=r=>t.check(td(OR,r)),t.url=r=>t.check(id(CR,r)),t.jwt=r=>t.check(vd(GR,r)),t.emoji=r=>t.check(ad(zR,r)),t.guid=r=>t.check(Ji(a_,r)),t.uuid=r=>t.check(rd(sa,r)),t.uuidv4=r=>t.check(nd(sa,r)),t.uuidv6=r=>t.check(od(sa,r)),t.uuidv7=r=>t.check(sd(sa,r)),t.nanoid=r=>t.check(cd(NR,r)),t.guid=r=>t.check(Ji(a_,r)),t.cuid=r=>t.check(ld(jR,r)),t.cuid2=r=>t.check(ud(LR,r)),t.ulid=r=>t.check(dd(MR,r)),t.base64=r=>t.check(bd(VR,r)),t.base64url=r=>t.check(_d(HR,r)),t.xid=r=>t.check(pd(DR,r)),t.ksuid=r=>t.check(fd(UR,r)),t.ipv4=r=>t.check(hd(ZR,r)),t.ipv6=r=>t.check(md(qR,r)),t.cidrv4=r=>t.check(gd(FR,r)),t.cidrv6=r=>t.check(yd(BR,r)),t.e164=r=>t.check(wd(KR,r)),t.datetime=r=>t.check(Vd(r)),t.date=r=>t.check(Hd(r)),t.time=r=>t.check(Kd(r)),t.duration=r=>t.check(Gd(r))});De=A("ZodStringFormat",(t,e)=>{Oe.init(t,e),u_.init(t,e)}),OR=A("ZodEmail",(t,e)=>{hu.init(t,e),De.init(t,e)}),a_=A("ZodGUID",(t,e)=>{pu.init(t,e),De.init(t,e)}),sa=A("ZodUUID",(t,e)=>{fu.init(t,e),De.init(t,e)}),CR=A("ZodURL",(t,e)=>{mu.init(t,e),De.init(t,e)}),zR=A("ZodEmoji",(t,e)=>{gu.init(t,e),De.init(t,e)}),NR=A("ZodNanoID",(t,e)=>{yu.init(t,e),De.init(t,e)}),jR=A("ZodCUID",(t,e)=>{bu.init(t,e),De.init(t,e)}),LR=A("ZodCUID2",(t,e)=>{_u.init(t,e),De.init(t,e)}),MR=A("ZodULID",(t,e)=>{wu.init(t,e),De.init(t,e)}),DR=A("ZodXID",(t,e)=>{vu.init(t,e),De.init(t,e)}),UR=A("ZodKSUID",(t,e)=>{xu.init(t,e),De.init(t,e)}),ZR=A("ZodIPv4",(t,e)=>{$u.init(t,e),De.init(t,e)}),qR=A("ZodIPv6",(t,e)=>{ku.init(t,e),De.init(t,e)}),FR=A("ZodCIDRv4",(t,e)=>{Su.init(t,e),De.init(t,e)}),BR=A("ZodCIDRv6",(t,e)=>{Tu.init(t,e),De.init(t,e)}),VR=A("ZodBase64",(t,e)=>{Eu.init(t,e),De.init(t,e)}),HR=A("ZodBase64URL",(t,e)=>{Ru.init(t,e),De.init(t,e)}),KR=A("ZodE164",(t,e)=>{Pu.init(t,e),De.init(t,e)}),GR=A("ZodJWT",(t,e)=>{Au.init(t,e),De.init(t,e)}),d_=A("ZodNumber",(t,e)=>{Hi.init(t,e),Fe.init(t,e),t.gt=(n,o)=>t.check(Xi(n,o)),t.gte=(n,o)=>t.check(ps(n,o)),t.min=(n,o)=>t.check(ps(n,o)),t.lt=(n,o)=>t.check(Yi(n,o)),t.lte=(n,o)=>t.check(ds(n,o)),t.max=(n,o)=>t.check(ds(n,o)),t.int=n=>t.check(c_(n)),t.safe=n=>t.check(c_(n)),t.positive=n=>t.check(Xi(0,n)),t.nonnegative=n=>t.check(ps(0,n)),t.negative=n=>t.check(Yi(0,n)),t.nonpositive=n=>t.check(ds(0,n)),t.multipleOf=(n,o)=>t.check(Qi(n,o)),t.step=(n,o)=>t.check(Qi(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});WR=A("ZodNumberFormat",(t,e)=>{Iu.init(t,e),d_.init(t,e)});JR=A("ZodBoolean",(t,e)=>{Ou.init(t,e),Fe.init(t,e)});YR=A("ZodNull",(t,e)=>{Cu.init(t,e),Fe.init(t,e)});XR=A("ZodUnknown",(t,e)=>{zu.init(t,e),Fe.init(t,e)});QR=A("ZodNever",(t,e)=>{Nu.init(t,e),Fe.init(t,e)});tP=A("ZodArray",(t,e)=>{ju.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(no(r,n)),t.nonempty=r=>t.check(no(1,r)),t.max=(r,n)=>t.check(ea(r,n)),t.length=(r,n)=>t.check(ta(r,n)),t.unwrap=()=>t.element});f_=A("ZodObject",(t,e)=>{Ki.init(t,e),Fe.init(t,e),fe.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>wt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ue()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ue()}),t.strict=()=>t.clone({...t._zod.def,catchall:eP()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>fe.extend(t,r),t.merge=r=>fe.merge(t,r),t.pick=r=>fe.pick(t,r),t.omit=r=>fe.omit(t,r),t.partial=(...r)=>fe.partial(g_,t,r[0]),t.required=(...r)=>fe.required(y_,t,r[0])});h_=A("ZodUnion",(t,e)=>{Gi.init(t,e),Fe.init(t,e),t.options=e.options});rP=A("ZodDiscriminatedUnion",(t,e)=>{h_.init(t,e),Lu.init(t,e)});nP=A("ZodIntersection",(t,e)=>{Mu.init(t,e),Fe.init(t,e)});oP=A("ZodRecord",(t,e)=>{Du.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Qd=A("ZodEnum",(t,e)=>{Uu.init(t,e),Fe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Qd({...e,checks:[],...fe.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Qd({...e,checks:[],...fe.normalizeParams(o),entries:s})}});sP=A("ZodLiteral",(t,e)=>{Zu.init(t,e),Fe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});iP=A("ZodTransform",(t,e)=>{qu.init(t,e),Fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(fe.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(fe.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});g_=A("ZodOptional",(t,e)=>{Fu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});aP=A("ZodNullable",(t,e)=>{Bu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});cP=A("ZodDefault",(t,e)=>{Vu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});uP=A("ZodPrefault",(t,e)=>{Hu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});y_=A("ZodNonOptional",(t,e)=>{Ku.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});fP=A("ZodCatch",(t,e)=>{Gu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});mP=A("ZodPipe",(t,e)=>{Wu.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});gP=A("ZodReadonly",(t,e)=>{Ju.init(t,e),Fe.init(t,e)});b_=A("ZodCustom",(t,e)=>{Yu.init(t,e),Fe.init(t,e)})});var w_=O(()=>{});var v_=O(()=>{});var x_=O(()=>{ut();Jd();Bd();Yd();Xd();w_();ut();Ob();Wi();Wd();v_();Tt(Ib())});var $_=O(()=>{x_()});var k_=O(()=>{$_()});function Z_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function q_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var op,S_,qr,ca,Je,T_,E_,bZ,$P,kP,sp,Rt,gs,R_,tt,Lt,Mt,rt,la,P_,ip,A_,I_,ap,ys,J,cp,O_,C_,_Z,ua,SP,da,TP,bs,io,z_,EP,RP,PP,AP,IP,OP,lp,CP,zP,up,pa,NP,jP,fa,LP,_s,ws,MP,vs,ao,DP,xs,ha,ma,ga,wZ,ya,ba,_a,N_,j_,L_,dp,M_,$s,co,D_,UP,wa,ZP,va,qP,pp,FP,xa,BP,VP,HP,KP,GP,WP,JP,YP,XP,QP,$a,eA,tA,ka,fp,hp,mp,rA,nA,oA,gp,sA,iA,aA,cA,lA,U_,Sa,uA,Ta,vZ,dA,lo,pA,xZ,ks,fA,yp,hA,mA,gA,yA,bA,_A,wA,aa,vA,xA,$A,Ss,bp,kA,SA,TA,EA,RA,PA,AA,IA,OA,CA,zA,NA,jA,LA,MA,DA,UA,ZA,uo,qA,FA,BA,Ea,VA,HA,KA,_p,GA,$Z,kZ,SZ,TZ,EZ,RZ,H,np,po=O(()=>{k_();op="2025-11-25",S_=[op,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],qr="io.modelcontextprotocol/related-task",ca="2.0",Je=__(t=>t!==null&&(typeof t=="object"||typeof t=="function")),T_=ze([P(),Se().int()]),E_=P(),bZ=dt({ttl:Se().optional(),pollInterval:Se().optional()}),$P=F({ttl:Se().optional()}),kP=F({taskId:P()}),sp=dt({progressToken:T_.optional(),[qr]:kP.optional()}),Rt=F({_meta:sp.optional()}),gs=Rt.extend({task:$P.optional()}),R_=t=>gs.safeParse(t).success,tt=F({method:P(),params:Rt.loose().optional()}),Lt=F({_meta:sp.optional()}),Mt=F({method:P(),params:Lt.loose().optional()}),rt=dt({_meta:sp.optional()}),la=ze([P(),Se().int()]),P_=F({jsonrpc:K(ca),id:la,...tt.shape}).strict(),ip=t=>P_.safeParse(t).success,A_=F({jsonrpc:K(ca),...Mt.shape}).strict(),I_=t=>A_.safeParse(t).success,ap=F({jsonrpc:K(ca),id:la,result:rt}).strict(),ys=t=>ap.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(J||(J={}));cp=F({jsonrpc:K(ca),id:la.optional(),error:F({code:Se().int(),message:P(),data:Ue().optional()})}).strict(),O_=t=>cp.safeParse(t).success,C_=ze([P_,A_,ap,cp]),_Z=ze([ap,cp]),ua=rt.strict(),SP=Lt.extend({requestId:la.optional(),reason:P().optional()}),da=Mt.extend({method:K("notifications/cancelled"),params:SP}),TP=F({src:P(),mimeType:P().optional(),sizes:me(P()).optional(),theme:wt(["light","dark"]).optional()}),bs=F({icons:me(TP).optional()}),io=F({name:P(),title:P().optional()}),z_=io.extend({...io.shape,...bs.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),EP=ia(F({applyDefaults:Ye().optional()}),Ce(P(),Ue())),RP=rp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ia(F({form:EP.optional(),url:Je.optional()}),Ce(P(),Ue()).optional())),PP=dt({list:Je.optional(),cancel:Je.optional(),requests:dt({sampling:dt({createMessage:Je.optional()}).optional(),elicitation:dt({create:Je.optional()}).optional()}).optional()}),AP=dt({list:Je.optional(),cancel:Je.optional(),requests:dt({tools:dt({call:Je.optional()}).optional()}).optional()}),IP=F({experimental:Ce(P(),Je).optional(),sampling:F({context:Je.optional(),tools:Je.optional()}).optional(),elicitation:RP.optional(),roots:F({listChanged:Ye().optional()}).optional(),tasks:PP.optional(),extensions:Ce(P(),Je).optional()}),OP=Rt.extend({protocolVersion:P(),capabilities:IP,clientInfo:z_}),lp=tt.extend({method:K("initialize"),params:OP}),CP=F({experimental:Ce(P(),Je).optional(),logging:Je.optional(),completions:Je.optional(),prompts:F({listChanged:Ye().optional()}).optional(),resources:F({subscribe:Ye().optional(),listChanged:Ye().optional()}).optional(),tools:F({listChanged:Ye().optional()}).optional(),tasks:AP.optional(),extensions:Ce(P(),Je).optional()}),zP=rt.extend({protocolVersion:P(),capabilities:CP,serverInfo:z_,instructions:P().optional()}),up=Mt.extend({method:K("notifications/initialized"),params:Lt.optional()}),pa=tt.extend({method:K("ping"),params:Rt.optional()}),NP=F({progress:Se(),total:Ze(Se()),message:Ze(P())}),jP=F({...Lt.shape,...NP.shape,progressToken:T_}),fa=Mt.extend({method:K("notifications/progress"),params:jP}),LP=Rt.extend({cursor:E_.optional()}),_s=tt.extend({params:LP.optional()}),ws=rt.extend({nextCursor:E_.optional()}),MP=wt(["working","input_required","completed","failed","cancelled"]),vs=F({taskId:P(),status:MP,ttl:ze([Se(),p_()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:Ze(Se()),statusMessage:Ze(P())}),ao=rt.extend({task:vs}),DP=Lt.merge(vs),xs=Mt.extend({method:K("notifications/tasks/status"),params:DP}),ha=tt.extend({method:K("tasks/get"),params:Rt.extend({taskId:P()})}),ma=rt.merge(vs),ga=tt.extend({method:K("tasks/result"),params:Rt.extend({taskId:P()})}),wZ=rt.loose(),ya=_s.extend({method:K("tasks/list")}),ba=ws.extend({tasks:me(vs)}),_a=tt.extend({method:K("tasks/cancel"),params:Rt.extend({taskId:P()})}),N_=rt.merge(vs),j_=F({uri:P(),mimeType:Ze(P()),_meta:Ce(P(),Ue()).optional()}),L_=j_.extend({text:P()}),dp=P().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),M_=j_.extend({blob:dp}),$s=wt(["user","assistant"]),co=F({audience:me($s).optional(),priority:Se().min(0).max(1).optional(),lastModified:hs.datetime({offset:!0}).optional()}),D_=F({...io.shape,...bs.shape,uri:P(),description:Ze(P()),mimeType:Ze(P()),size:Ze(Se()),annotations:co.optional(),_meta:Ze(dt({}))}),UP=F({...io.shape,...bs.shape,uriTemplate:P(),description:Ze(P()),mimeType:Ze(P()),annotations:co.optional(),_meta:Ze(dt({}))}),wa=_s.extend({method:K("resources/list")}),ZP=ws.extend({resources:me(D_)}),va=_s.extend({method:K("resources/templates/list")}),qP=ws.extend({resourceTemplates:me(UP)}),pp=Rt.extend({uri:P()}),FP=pp,xa=tt.extend({method:K("resources/read"),params:FP}),BP=rt.extend({contents:me(ze([L_,M_]))}),VP=Mt.extend({method:K("notifications/resources/list_changed"),params:Lt.optional()}),HP=pp,KP=tt.extend({method:K("resources/subscribe"),params:HP}),GP=pp,WP=tt.extend({method:K("resources/unsubscribe"),params:GP}),JP=Lt.extend({uri:P()}),YP=Mt.extend({method:K("notifications/resources/updated"),params:JP}),XP=F({name:P(),description:Ze(P()),required:Ze(Ye())}),QP=F({...io.shape,...bs.shape,description:Ze(P()),arguments:Ze(me(XP)),_meta:Ze(dt({}))}),$a=_s.extend({method:K("prompts/list")}),eA=ws.extend({prompts:me(QP)}),tA=Rt.extend({name:P(),arguments:Ce(P(),P()).optional()}),ka=tt.extend({method:K("prompts/get"),params:tA}),fp=F({type:K("text"),text:P(),annotations:co.optional(),_meta:Ce(P(),Ue()).optional()}),hp=F({type:K("image"),data:dp,mimeType:P(),annotations:co.optional(),_meta:Ce(P(),Ue()).optional()}),mp=F({type:K("audio"),data:dp,mimeType:P(),annotations:co.optional(),_meta:Ce(P(),Ue()).optional()}),rA=F({type:K("tool_use"),name:P(),id:P(),input:Ce(P(),Ue()),_meta:Ce(P(),Ue()).optional()}),nA=F({type:K("resource"),resource:ze([L_,M_]),annotations:co.optional(),_meta:Ce(P(),Ue()).optional()}),oA=D_.extend({type:K("resource_link")}),gp=ze([fp,hp,mp,oA,nA]),sA=F({role:$s,content:gp}),iA=rt.extend({description:P().optional(),messages:me(sA)}),aA=Mt.extend({method:K("notifications/prompts/list_changed"),params:Lt.optional()}),cA=F({title:P().optional(),readOnlyHint:Ye().optional(),destructiveHint:Ye().optional(),idempotentHint:Ye().optional(),openWorldHint:Ye().optional()}),lA=F({taskSupport:wt(["required","optional","forbidden"]).optional()}),U_=F({...io.shape,...bs.shape,description:P().optional(),inputSchema:F({type:K("object"),properties:Ce(P(),Je).optional(),required:me(P()).optional()}).catchall(Ue()),outputSchema:F({type:K("object"),properties:Ce(P(),Je).optional(),required:me(P()).optional()}).catchall(Ue()).optional(),annotations:cA.optional(),execution:lA.optional(),_meta:Ce(P(),Ue()).optional()}),Sa=_s.extend({method:K("tools/list")}),uA=ws.extend({tools:me(U_)}),Ta=rt.extend({content:me(gp).default([]),structuredContent:Ce(P(),Ue()).optional(),isError:Ye().optional()}),vZ=Ta.or(rt.extend({toolResult:Ue()})),dA=gs.extend({name:P(),arguments:Ce(P(),Ue()).optional()}),lo=tt.extend({method:K("tools/call"),params:dA}),pA=Mt.extend({method:K("notifications/tools/list_changed"),params:Lt.optional()}),xZ=F({autoRefresh:Ye().default(!0),debounceMs:Se().int().nonnegative().default(300)}),ks=wt(["debug","info","notice","warning","error","critical","alert","emergency"]),fA=Rt.extend({level:ks}),yp=tt.extend({method:K("logging/setLevel"),params:fA}),hA=Lt.extend({level:ks,logger:P().optional(),data:Ue()}),mA=Mt.extend({method:K("notifications/message"),params:hA}),gA=F({name:P().optional()}),yA=F({hints:me(gA).optional(),costPriority:Se().min(0).max(1).optional(),speedPriority:Se().min(0).max(1).optional(),intelligencePriority:Se().min(0).max(1).optional()}),bA=F({mode:wt(["auto","required","none"]).optional()}),_A=F({type:K("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:me(gp).default([]),structuredContent:F({}).loose().optional(),isError:Ye().optional(),_meta:Ce(P(),Ue()).optional()}),wA=tp("type",[fp,hp,mp]),aa=tp("type",[fp,hp,mp,rA,_A]),vA=F({role:$s,content:ze([aa,me(aa)]),_meta:Ce(P(),Ue()).optional()}),xA=gs.extend({messages:me(vA),modelPreferences:yA.optional(),systemPrompt:P().optional(),includeContext:wt(["none","thisServer","allServers"]).optional(),temperature:Se().optional(),maxTokens:Se().int(),stopSequences:me(P()).optional(),metadata:Je.optional(),tools:me(U_).optional(),toolChoice:bA.optional()}),$A=tt.extend({method:K("sampling/createMessage"),params:xA}),Ss=rt.extend({model:P(),stopReason:Ze(wt(["endTurn","stopSequence","maxTokens"]).or(P())),role:$s,content:wA}),bp=rt.extend({model:P(),stopReason:Ze(wt(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:$s,content:ze([aa,me(aa)])}),kA=F({type:K("boolean"),title:P().optional(),description:P().optional(),default:Ye().optional()}),SA=F({type:K("string"),title:P().optional(),description:P().optional(),minLength:Se().optional(),maxLength:Se().optional(),format:wt(["email","uri","date","date-time"]).optional(),default:P().optional()}),TA=F({type:wt(["number","integer"]),title:P().optional(),description:P().optional(),minimum:Se().optional(),maximum:Se().optional(),default:Se().optional()}),EA=F({type:K("string"),title:P().optional(),description:P().optional(),enum:me(P()),default:P().optional()}),RA=F({type:K("string"),title:P().optional(),description:P().optional(),oneOf:me(F({const:P(),title:P()})),default:P().optional()}),PA=F({type:K("string"),title:P().optional(),description:P().optional(),enum:me(P()),enumNames:me(P()).optional(),default:P().optional()}),AA=ze([EA,RA]),IA=F({type:K("array"),title:P().optional(),description:P().optional(),minItems:Se().optional(),maxItems:Se().optional(),items:F({type:K("string"),enum:me(P())}),default:me(P()).optional()}),OA=F({type:K("array"),title:P().optional(),description:P().optional(),minItems:Se().optional(),maxItems:Se().optional(),items:F({anyOf:me(F({const:P(),title:P()}))}),default:me(P()).optional()}),CA=ze([IA,OA]),zA=ze([PA,AA,CA]),NA=ze([zA,kA,SA,TA]),jA=gs.extend({mode:K("form").optional(),message:P(),requestedSchema:F({type:K("object"),properties:Ce(P(),NA),required:me(P()).optional()})}),LA=gs.extend({mode:K("url"),message:P(),elicitationId:P(),url:P().url()}),MA=ze([jA,LA]),DA=tt.extend({method:K("elicitation/create"),params:MA}),UA=Lt.extend({elicitationId:P()}),ZA=Mt.extend({method:K("notifications/elicitation/complete"),params:UA}),uo=rt.extend({action:wt(["accept","decline","cancel"]),content:rp(t=>t===null?void 0:t,Ce(P(),ze([P(),Se(),Ye(),me(P())])).optional())}),qA=F({type:K("ref/resource"),uri:P()}),FA=F({type:K("ref/prompt"),name:P()}),BA=Rt.extend({ref:ze([FA,qA]),argument:F({name:P(),value:P()}),context:F({arguments:Ce(P(),P()).optional()}).optional()}),Ea=tt.extend({method:K("completion/complete"),params:BA});VA=rt.extend({completion:dt({values:me(P()).max(100),total:Ze(Se().int()),hasMore:Ze(Ye())})}),HA=F({uri:P().startsWith("file://"),name:P().optional(),_meta:Ce(P(),Ue()).optional()}),KA=tt.extend({method:K("roots/list"),params:Rt.optional()}),_p=rt.extend({roots:me(HA)}),GA=Mt.extend({method:K("notifications/roots/list_changed"),params:Lt.optional()}),$Z=ze([pa,lp,Ea,yp,ka,$a,wa,va,xa,KP,WP,lo,Sa,ha,ga,ya,_a]),kZ=ze([da,fa,up,GA,xs]),SZ=ze([ua,Ss,bp,uo,_p,ma,ba,ao]),TZ=ze([pa,$A,DA,KA,ha,ga,ya,_a]),EZ=ze([da,fa,mA,YP,VP,pA,aA,xs,ZA]),RZ=ze([ua,zP,VA,iA,eA,ZP,qP,BP,Ta,uA,ma,ba,ao]),H=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===J.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new np(o.elicitations,r)}return new t(e,r,n)}},np=class extends H{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(J.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Fr(t){return t==="completed"||t==="failed"||t==="cancelled"}var F_=O(()=>{});var V_,B_,H_,Ra=O(()=>{V_=Symbol("Let zodToJsonSchema decide on which parser to use"),B_={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},H_=t=>typeof t=="string"?{...B_,name:t}:{...B_,...t}});var K_,wp=O(()=>{Ra();K_=t=>{let e=H_(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function vp(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ge(t,e,r,n,o){t[e]=r,vp(t,e,n,o)}var Br=O(()=>{});var Pa,Aa=O(()=>{Pa=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function qe(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Pa(e,t.currentPath):e.join("/")}}var Dt=O(()=>{Aa()});function G_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==L.ZodAny&&(r.items=ee(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ge(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ge(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ge(r,"minItems",t.exactLength.value,t.exactLength.message,e),ge(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var xp=O(()=>{es();Br();Ge()});function W_(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ge(r,"minimum",n.value,n.message,e):ge(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ge(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ge(r,"maximum",n.value,n.message,e):ge(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ge(r,"maximum",n.value,n.message,e));break;case"multipleOf":ge(r,"multipleOf",n.value,n.message,e);break}return r}var $p=O(()=>{Br()});function J_(){return{type:"boolean"}}var kp=O(()=>{});function Ia(t,e){return ee(t.type._def,e)}var Oa=O(()=>{Ge()});var Y_,Sp=O(()=>{Ge();Y_=(t,e)=>ee(t.innerType._def,e)});function Tp(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Tp(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return WA(t,e)}}var WA,Ep=O(()=>{Br();WA=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ge(r,"minimum",n.value,n.message,e);break;case"max":ge(r,"maximum",n.value,n.message,e);break}return r}});function X_(t,e){return{...ee(t.innerType._def,e),default:t.defaultValue()}}var Rp=O(()=>{Ge()});function Q_(t,e){return e.effectStrategy==="input"?ee(t.schema._def,e):qe(e)}var Pp=O(()=>{Ge();Dt()});function ew(t){return{type:"string",enum:Array.from(t.values)}}var Ap=O(()=>{});function tw(t,e){let r=[ee(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ee(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(JA(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var JA,Ip=O(()=>{Ge();JA=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function rw(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Op=O(()=>{});function Ca(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ge(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ge(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Wt(r,"email",n.message,e);break;case"format:idn-email":Wt(r,"idn-email",n.message,e);break;case"pattern:zod":pt(r,Gt.email,n.message,e);break}break;case"url":Wt(r,"uri",n.message,e);break;case"uuid":Wt(r,"uuid",n.message,e);break;case"regex":pt(r,n.regex,n.message,e);break;case"cuid":pt(r,Gt.cuid,n.message,e);break;case"cuid2":pt(r,Gt.cuid2,n.message,e);break;case"startsWith":pt(r,RegExp(`^${zp(n.value,e)}`),n.message,e);break;case"endsWith":pt(r,RegExp(`${zp(n.value,e)}$`),n.message,e);break;case"datetime":Wt(r,"date-time",n.message,e);break;case"date":Wt(r,"date",n.message,e);break;case"time":Wt(r,"time",n.message,e);break;case"duration":Wt(r,"duration",n.message,e);break;case"length":ge(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ge(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{pt(r,RegExp(zp(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Wt(r,"ipv4",n.message,e),n.version!=="v4"&&Wt(r,"ipv6",n.message,e);break}case"base64url":pt(r,Gt.base64url,n.message,e);break;case"jwt":pt(r,Gt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&pt(r,Gt.ipv4Cidr,n.message,e),n.version!=="v4"&&pt(r,Gt.ipv6Cidr,n.message,e);break}case"emoji":pt(r,Gt.emoji(),n.message,e);break;case"ulid":{pt(r,Gt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Wt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ge(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{pt(r,Gt.base64,n.message,e);break}}break}case"nanoid":pt(r,Gt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function zp(t,e){return e.patternStrategy==="escape"?XA(t):t}function XA(t){let e="";for(let r=0;r<t.length;r++)YA.has(t[r])||(e+="\\"),e+=t[r];return e}function Wt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ge(t,"format",e,r,n)}function pt(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:nw(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ge(t,"pattern",nw(e,n),r,n)}function nw(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
980
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let d=u[1];if(e===u[0]){i(u);continue}if(n.external){let h=n.external.registry.get(u[0])?.id;if(e!==u[0]&&h){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(d.cycle){i(u);continue}if(d.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,d)=>{let b=this.seen.get(u),h=b.def??b.schema,f={...h};if(b.ref===null)return;let y=b.ref;if(b.ref=null,y){a(y,d);let v=this.seen.get(y).schema;v.$ref&&d.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(v)):(Object.assign(h,v),Object.assign(h,f))}b.isParent||this.override({zodSchema:u,jsonSchema:h,path:b.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,o.def);let l=n.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(l[d.defId]=d.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var Vb=O(()=>{});var ut=O(()=>{no();iu();Ql();Cb();Fi();pu();ir();qi();Wi();td();du();Fb();qb();Bb();Vb()});var Fd=O(()=>{ut()});function Bd(t,e){let r={type:"object",get shape(){return ge.assignProp(this,"shape",{...t}),this.shape},...ge.normalizeParams(e)};return new kR(r)}var $R,kR,Hb=O(()=>{ut();ut();Fd();$R=I("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Re.init(t,e),t.def=e,t.parse=(r,n)=>tu(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>$n(t,r,n),t.parseAsync=async(r,n)=>nu(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>kn(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Tt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),kR=I("ZodMiniObject",(t,e)=>{Ki.init(t,e),$R.init(t,e),ge.defineLazy(t,"shape",()=>e.shape)})});var Kb=O(()=>{});var Gb=O(()=>{});var Wb=O(()=>{});var Jb=O(()=>{ut();Fd();Hb();Kb();ut();Wi();Gb();Wb()});var Yb=O(()=>{Jb()});var Vd=O(()=>{Yb()});function ar(t){return!!t._zod}function En(t){let e=Object.values(t);if(e.length===0)return Bd({});let r=e.every(ar),n=e.every(o=>!ar(o));if(r)return Bd(t);if(n)return Jc(t);throw new Error("Mixed Zod versions detected in object shape.")}function Zr(t,e){return ar(t)?$n(t,e):t.safeParse(e)}async function na(t,e){return ar(t)?await kn(t,e):await t.safeParseAsync(e)}function qr(t){if(!t)return;let e;if(ar(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function ao(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return En(t)}}if(ar(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function ER(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function oa(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${ER(e.path)}`:e.message).join(`
981
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Qb(t){return t.description}function ew(t){if(ar(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function co(t){if(ar(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var hs=O(()=>{ts();Vd()});var Hd=O(()=>{ut()});var ms={};jo(ms,{ZodISODate:()=>rw,ZodISODateTime:()=>tw,ZodISODuration:()=>ow,ZodISOTime:()=>nw,date:()=>Gd,datetime:()=>Kd,duration:()=>Jd,time:()=>Wd});function Kd(t){return Lb(tw,t)}function Gd(t){return Mb(rw,t)}function Wd(t){return Db(nw,t)}function Jd(t){return Ub(ow,t)}var tw,rw,nw,ow,Yd=O(()=>{ut();Xd();tw=I("ZodISODateTime",(t,e)=>{Rb.init(t,e),De.init(t,e)});rw=I("ZodISODate",(t,e)=>{Pb.init(t,e),De.init(t,e)});nw=I("ZodISOTime",(t,e)=>{Ab.init(t,e),De.init(t,e)});ow=I("ZodISODuration",(t,e)=>{Ib.init(t,e),De.init(t,e)})});var sw,iZ,gs,Qd=O(()=>{ut();ut();sw=(t,e)=>{Ui.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Xl(t,r)},flatten:{value:r=>Yl(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},iZ=I("ZodError",sw),gs=I("ZodError",sw,{Parent:Error})});var iw,aw,cw,lw,ep=O(()=>{ut();Qd();iw=eu(gs),aw=ru(gs),cw=ou(gs),lw=su(gs)});function P(t){return rd(NR,t)}function Te(t){return kd(hw,t)}function dw(t){return Sd(QR,t)}function Ye(t){return Td(eP,t)}function mw(t){return Ed(tP,t)}function Ue(){return Rd(rP)}function oP(t){return Pd(nP,t)}function ye(t,e){return Zb(sP,t,e)}function B(t,e){let r={type:"object",get shape(){return ge.assignProp(this,"shape",{...t}),this.shape},...ge.normalizeParams(e)};return new gw(r)}function dt(t,e){return new gw({type:"object",get shape(){return ge.assignProp(this,"shape",{...t}),this.shape},catchall:Ue(),...ge.normalizeParams(e)})}function Ne(t,e){return new yw({type:"union",options:t,...ge.normalizeParams(e)})}function np(t,e,r){return new iP({type:"union",options:e,discriminator:t,...ge.normalizeParams(r)})}function ia(t,e){return new aP({type:"intersection",left:t,right:e})}function ze(t,e,r){return new cP({type:"record",keyType:t,valueType:e,...ge.normalizeParams(r)})}function _t(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new tp({type:"enum",entries:r,...ge.normalizeParams(e)})}function G(t,e){return new lP({type:"literal",values:Array.isArray(t)?t:[t],...ge.normalizeParams(e)})}function bw(t){return new uP({type:"transform",transform:t})}function Ze(t){return new ww({type:"optional",innerType:t})}function pw(t){return new dP({type:"nullable",innerType:t})}function fP(t,e){return new pP({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function mP(t,e){return new hP({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function gP(t,e){return new _w({type:"nonoptional",innerType:t,...ge.normalizeParams(e)})}function bP(t,e){return new yP({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function rp(t,e){return new wP({type:"pipe",in:t,out:e})}function vP(t){return new _P({type:"readonly",innerType:t})}function xP(t){let e=new et({check:"custom"});return e._zod.check=t,e}function xw(t,e){return Ud(vw,t??(()=>!0),e)}function $P(t,e={}){return Zd(vw,t,e)}function kP(t){let e=xP(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ge.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ge.issue(o))}},t(r.value,r)));return e}function op(t,e){return rp(bw(t),e)}var Fe,fw,NR,De,jR,uw,sa,LR,MR,DR,UR,ZR,qR,FR,BR,VR,HR,KR,GR,WR,JR,YR,XR,hw,QR,eP,tP,rP,nP,sP,gw,yw,iP,aP,cP,tp,lP,uP,ww,dP,pP,hP,_w,yP,wP,_P,vw,Xd=O(()=>{ut();ut();Hd();Yd();ep();Fe=I("ZodType",(t,e)=>(Re.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Tt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>iw(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>cw(t,r,n),t.parseAsync=async(r,n)=>aw(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>lw(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check($P(r,n)),t.superRefine=r=>t.check(kP(r)),t.overwrite=r=>t.check(Sn(r)),t.optional=()=>Ze(t),t.nullable=()=>pw(t),t.nullish=()=>Ze(pw(t)),t.nonoptional=r=>gP(t,r),t.array=()=>ye(t),t.or=r=>Ne([t,r]),t.and=r=>ia(t,r),t.transform=r=>rp(t,bw(r)),t.default=r=>fP(t,r),t.prefault=r=>mP(t,r),t.catch=r=>bP(t,r),t.pipe=r=>rp(t,r),t.readonly=()=>vP(t),t.describe=r=>{let n=t.clone();return Ur.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Ur.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Ur.get(t);let n=t.clone();return Ur.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),fw=I("_ZodString",(t,e)=>{us.init(t,e),Fe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Ad(...n)),t.includes=(...n)=>t.check(Cd(...n)),t.startsWith=(...n)=>t.check(zd(...n)),t.endsWith=(...n)=>t.check(Nd(...n)),t.min=(...n)=>t.check(io(...n)),t.max=(...n)=>t.check(ea(...n)),t.length=(...n)=>t.check(ta(...n)),t.nonempty=(...n)=>t.check(io(1,...n)),t.lowercase=n=>t.check(Id(n)),t.uppercase=n=>t.check(Od(n)),t.trim=()=>t.check(Ld()),t.normalize=(...n)=>t.check(jd(...n)),t.toLowerCase=()=>t.check(Md()),t.toUpperCase=()=>t.check(Dd())}),NR=I("ZodString",(t,e)=>{us.init(t,e),fw.init(t,e),t.email=r=>t.check(nd(jR,r)),t.url=r=>t.check(cd(LR,r)),t.jwt=r=>t.check($d(XR,r)),t.emoji=r=>t.check(ld(MR,r)),t.guid=r=>t.check(Ji(uw,r)),t.uuid=r=>t.check(od(sa,r)),t.uuidv4=r=>t.check(sd(sa,r)),t.uuidv6=r=>t.check(id(sa,r)),t.uuidv7=r=>t.check(ad(sa,r)),t.nanoid=r=>t.check(ud(DR,r)),t.guid=r=>t.check(Ji(uw,r)),t.cuid=r=>t.check(dd(UR,r)),t.cuid2=r=>t.check(pd(ZR,r)),t.ulid=r=>t.check(fd(qR,r)),t.base64=r=>t.check(_d(WR,r)),t.base64url=r=>t.check(vd(JR,r)),t.xid=r=>t.check(hd(FR,r)),t.ksuid=r=>t.check(md(BR,r)),t.ipv4=r=>t.check(gd(VR,r)),t.ipv6=r=>t.check(yd(HR,r)),t.cidrv4=r=>t.check(bd(KR,r)),t.cidrv6=r=>t.check(wd(GR,r)),t.e164=r=>t.check(xd(YR,r)),t.datetime=r=>t.check(Kd(r)),t.date=r=>t.check(Gd(r)),t.time=r=>t.check(Wd(r)),t.duration=r=>t.check(Jd(r))});De=I("ZodStringFormat",(t,e)=>{Ce.init(t,e),fw.init(t,e)}),jR=I("ZodEmail",(t,e)=>{gu.init(t,e),De.init(t,e)}),uw=I("ZodGUID",(t,e)=>{hu.init(t,e),De.init(t,e)}),sa=I("ZodUUID",(t,e)=>{mu.init(t,e),De.init(t,e)}),LR=I("ZodURL",(t,e)=>{yu.init(t,e),De.init(t,e)}),MR=I("ZodEmoji",(t,e)=>{bu.init(t,e),De.init(t,e)}),DR=I("ZodNanoID",(t,e)=>{wu.init(t,e),De.init(t,e)}),UR=I("ZodCUID",(t,e)=>{_u.init(t,e),De.init(t,e)}),ZR=I("ZodCUID2",(t,e)=>{vu.init(t,e),De.init(t,e)}),qR=I("ZodULID",(t,e)=>{xu.init(t,e),De.init(t,e)}),FR=I("ZodXID",(t,e)=>{$u.init(t,e),De.init(t,e)}),BR=I("ZodKSUID",(t,e)=>{ku.init(t,e),De.init(t,e)}),VR=I("ZodIPv4",(t,e)=>{Su.init(t,e),De.init(t,e)}),HR=I("ZodIPv6",(t,e)=>{Tu.init(t,e),De.init(t,e)}),KR=I("ZodCIDRv4",(t,e)=>{Eu.init(t,e),De.init(t,e)}),GR=I("ZodCIDRv6",(t,e)=>{Ru.init(t,e),De.init(t,e)}),WR=I("ZodBase64",(t,e)=>{Pu.init(t,e),De.init(t,e)}),JR=I("ZodBase64URL",(t,e)=>{Au.init(t,e),De.init(t,e)}),YR=I("ZodE164",(t,e)=>{Iu.init(t,e),De.init(t,e)}),XR=I("ZodJWT",(t,e)=>{Ou.init(t,e),De.init(t,e)}),hw=I("ZodNumber",(t,e)=>{Hi.init(t,e),Fe.init(t,e),t.gt=(n,o)=>t.check(Xi(n,o)),t.gte=(n,o)=>t.check(fs(n,o)),t.min=(n,o)=>t.check(fs(n,o)),t.lt=(n,o)=>t.check(Yi(n,o)),t.lte=(n,o)=>t.check(ps(n,o)),t.max=(n,o)=>t.check(ps(n,o)),t.int=n=>t.check(dw(n)),t.safe=n=>t.check(dw(n)),t.positive=n=>t.check(Xi(0,n)),t.nonnegative=n=>t.check(fs(0,n)),t.negative=n=>t.check(Yi(0,n)),t.nonpositive=n=>t.check(ps(0,n)),t.multipleOf=(n,o)=>t.check(Qi(n,o)),t.step=(n,o)=>t.check(Qi(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});QR=I("ZodNumberFormat",(t,e)=>{Cu.init(t,e),hw.init(t,e)});eP=I("ZodBoolean",(t,e)=>{zu.init(t,e),Fe.init(t,e)});tP=I("ZodNull",(t,e)=>{Nu.init(t,e),Fe.init(t,e)});rP=I("ZodUnknown",(t,e)=>{ju.init(t,e),Fe.init(t,e)});nP=I("ZodNever",(t,e)=>{Lu.init(t,e),Fe.init(t,e)});sP=I("ZodArray",(t,e)=>{Mu.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(io(r,n)),t.nonempty=r=>t.check(io(1,r)),t.max=(r,n)=>t.check(ea(r,n)),t.length=(r,n)=>t.check(ta(r,n)),t.unwrap=()=>t.element});gw=I("ZodObject",(t,e)=>{Ki.init(t,e),Fe.init(t,e),ge.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>_t(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ue()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ue()}),t.strict=()=>t.clone({...t._zod.def,catchall:oP()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ge.extend(t,r),t.merge=r=>ge.merge(t,r),t.pick=r=>ge.pick(t,r),t.omit=r=>ge.omit(t,r),t.partial=(...r)=>ge.partial(ww,t,r[0]),t.required=(...r)=>ge.required(_w,t,r[0])});yw=I("ZodUnion",(t,e)=>{Gi.init(t,e),Fe.init(t,e),t.options=e.options});iP=I("ZodDiscriminatedUnion",(t,e)=>{yw.init(t,e),Du.init(t,e)});aP=I("ZodIntersection",(t,e)=>{Uu.init(t,e),Fe.init(t,e)});cP=I("ZodRecord",(t,e)=>{Zu.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});tp=I("ZodEnum",(t,e)=>{qu.init(t,e),Fe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new tp({...e,checks:[],...ge.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new tp({...e,checks:[],...ge.normalizeParams(o),entries:s})}});lP=I("ZodLiteral",(t,e)=>{Fu.init(t,e),Fe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});uP=I("ZodTransform",(t,e)=>{Bu.init(t,e),Fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ge.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ge.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});ww=I("ZodOptional",(t,e)=>{Vu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});dP=I("ZodNullable",(t,e)=>{Hu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});pP=I("ZodDefault",(t,e)=>{Ku.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});hP=I("ZodPrefault",(t,e)=>{Gu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});_w=I("ZodNonOptional",(t,e)=>{Wu.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});yP=I("ZodCatch",(t,e)=>{Ju.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});wP=I("ZodPipe",(t,e)=>{Yu.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});_P=I("ZodReadonly",(t,e)=>{Xu.init(t,e),Fe.init(t,e)});vw=I("ZodCustom",(t,e)=>{Qu.init(t,e),Fe.init(t,e)})});var $w=O(()=>{});var kw=O(()=>{});var Sw=O(()=>{ut();Xd();Hd();Qd();ep();$w();ut();Nb();Wi();Yd();kw();St(zb())});var Tw=O(()=>{Sw()});var Ew=O(()=>{Tw()});function Bw(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Vw(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var ip,Rw,Fr,ca,Je,Pw,Aw,xZ,EP,RP,ap,Et,ys,Iw,tt,Lt,Mt,rt,la,Ow,cp,Cw,zw,lp,bs,Y,up,Nw,jw,$Z,ua,PP,da,AP,ws,lo,Lw,IP,OP,CP,zP,NP,jP,dp,LP,MP,pp,pa,DP,UP,fa,ZP,_s,vs,qP,xs,uo,FP,$s,ha,ma,ga,kZ,ya,ba,wa,Mw,Dw,Uw,fp,Zw,ks,po,qw,BP,_a,VP,va,HP,hp,KP,xa,GP,WP,JP,YP,XP,QP,eA,tA,rA,nA,$a,oA,sA,ka,mp,gp,yp,iA,aA,cA,bp,lA,uA,dA,pA,fA,Fw,Sa,hA,Ta,SZ,mA,fo,gA,TZ,Ss,yA,wp,bA,wA,_A,vA,xA,$A,kA,aa,SA,TA,EA,Ts,_p,RA,PA,AA,IA,OA,CA,zA,NA,jA,LA,MA,DA,UA,ZA,qA,FA,BA,VA,ho,HA,KA,GA,Ea,WA,JA,YA,vp,XA,EZ,RZ,PZ,AZ,IZ,OZ,K,sp,mo=O(()=>{Ew();ip="2025-11-25",Rw=[ip,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Fr="io.modelcontextprotocol/related-task",ca="2.0",Je=xw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Pw=Ne([P(),Te().int()]),Aw=P(),xZ=dt({ttl:Te().optional(),pollInterval:Te().optional()}),EP=B({ttl:Te().optional()}),RP=B({taskId:P()}),ap=dt({progressToken:Pw.optional(),[Fr]:RP.optional()}),Et=B({_meta:ap.optional()}),ys=Et.extend({task:EP.optional()}),Iw=t=>ys.safeParse(t).success,tt=B({method:P(),params:Et.loose().optional()}),Lt=B({_meta:ap.optional()}),Mt=B({method:P(),params:Lt.loose().optional()}),rt=dt({_meta:ap.optional()}),la=Ne([P(),Te().int()]),Ow=B({jsonrpc:G(ca),id:la,...tt.shape}).strict(),cp=t=>Ow.safeParse(t).success,Cw=B({jsonrpc:G(ca),...Mt.shape}).strict(),zw=t=>Cw.safeParse(t).success,lp=B({jsonrpc:G(ca),id:la,result:rt}).strict(),bs=t=>lp.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Y||(Y={}));up=B({jsonrpc:G(ca),id:la.optional(),error:B({code:Te().int(),message:P(),data:Ue().optional()})}).strict(),Nw=t=>up.safeParse(t).success,jw=Ne([Ow,Cw,lp,up]),$Z=Ne([lp,up]),ua=rt.strict(),PP=Lt.extend({requestId:la.optional(),reason:P().optional()}),da=Mt.extend({method:G("notifications/cancelled"),params:PP}),AP=B({src:P(),mimeType:P().optional(),sizes:ye(P()).optional(),theme:_t(["light","dark"]).optional()}),ws=B({icons:ye(AP).optional()}),lo=B({name:P(),title:P().optional()}),Lw=lo.extend({...lo.shape,...ws.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),IP=ia(B({applyDefaults:Ye().optional()}),ze(P(),Ue())),OP=op(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ia(B({form:IP.optional(),url:Je.optional()}),ze(P(),Ue()).optional())),CP=dt({list:Je.optional(),cancel:Je.optional(),requests:dt({sampling:dt({createMessage:Je.optional()}).optional(),elicitation:dt({create:Je.optional()}).optional()}).optional()}),zP=dt({list:Je.optional(),cancel:Je.optional(),requests:dt({tools:dt({call:Je.optional()}).optional()}).optional()}),NP=B({experimental:ze(P(),Je).optional(),sampling:B({context:Je.optional(),tools:Je.optional()}).optional(),elicitation:OP.optional(),roots:B({listChanged:Ye().optional()}).optional(),tasks:CP.optional(),extensions:ze(P(),Je).optional()}),jP=Et.extend({protocolVersion:P(),capabilities:NP,clientInfo:Lw}),dp=tt.extend({method:G("initialize"),params:jP}),LP=B({experimental:ze(P(),Je).optional(),logging:Je.optional(),completions:Je.optional(),prompts:B({listChanged:Ye().optional()}).optional(),resources:B({subscribe:Ye().optional(),listChanged:Ye().optional()}).optional(),tools:B({listChanged:Ye().optional()}).optional(),tasks:zP.optional(),extensions:ze(P(),Je).optional()}),MP=rt.extend({protocolVersion:P(),capabilities:LP,serverInfo:Lw,instructions:P().optional()}),pp=Mt.extend({method:G("notifications/initialized"),params:Lt.optional()}),pa=tt.extend({method:G("ping"),params:Et.optional()}),DP=B({progress:Te(),total:Ze(Te()),message:Ze(P())}),UP=B({...Lt.shape,...DP.shape,progressToken:Pw}),fa=Mt.extend({method:G("notifications/progress"),params:UP}),ZP=Et.extend({cursor:Aw.optional()}),_s=tt.extend({params:ZP.optional()}),vs=rt.extend({nextCursor:Aw.optional()}),qP=_t(["working","input_required","completed","failed","cancelled"]),xs=B({taskId:P(),status:qP,ttl:Ne([Te(),mw()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:Ze(Te()),statusMessage:Ze(P())}),uo=rt.extend({task:xs}),FP=Lt.merge(xs),$s=Mt.extend({method:G("notifications/tasks/status"),params:FP}),ha=tt.extend({method:G("tasks/get"),params:Et.extend({taskId:P()})}),ma=rt.merge(xs),ga=tt.extend({method:G("tasks/result"),params:Et.extend({taskId:P()})}),kZ=rt.loose(),ya=_s.extend({method:G("tasks/list")}),ba=vs.extend({tasks:ye(xs)}),wa=tt.extend({method:G("tasks/cancel"),params:Et.extend({taskId:P()})}),Mw=rt.merge(xs),Dw=B({uri:P(),mimeType:Ze(P()),_meta:ze(P(),Ue()).optional()}),Uw=Dw.extend({text:P()}),fp=P().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Zw=Dw.extend({blob:fp}),ks=_t(["user","assistant"]),po=B({audience:ye(ks).optional(),priority:Te().min(0).max(1).optional(),lastModified:ms.datetime({offset:!0}).optional()}),qw=B({...lo.shape,...ws.shape,uri:P(),description:Ze(P()),mimeType:Ze(P()),size:Ze(Te()),annotations:po.optional(),_meta:Ze(dt({}))}),BP=B({...lo.shape,...ws.shape,uriTemplate:P(),description:Ze(P()),mimeType:Ze(P()),annotations:po.optional(),_meta:Ze(dt({}))}),_a=_s.extend({method:G("resources/list")}),VP=vs.extend({resources:ye(qw)}),va=_s.extend({method:G("resources/templates/list")}),HP=vs.extend({resourceTemplates:ye(BP)}),hp=Et.extend({uri:P()}),KP=hp,xa=tt.extend({method:G("resources/read"),params:KP}),GP=rt.extend({contents:ye(Ne([Uw,Zw]))}),WP=Mt.extend({method:G("notifications/resources/list_changed"),params:Lt.optional()}),JP=hp,YP=tt.extend({method:G("resources/subscribe"),params:JP}),XP=hp,QP=tt.extend({method:G("resources/unsubscribe"),params:XP}),eA=Lt.extend({uri:P()}),tA=Mt.extend({method:G("notifications/resources/updated"),params:eA}),rA=B({name:P(),description:Ze(P()),required:Ze(Ye())}),nA=B({...lo.shape,...ws.shape,description:Ze(P()),arguments:Ze(ye(rA)),_meta:Ze(dt({}))}),$a=_s.extend({method:G("prompts/list")}),oA=vs.extend({prompts:ye(nA)}),sA=Et.extend({name:P(),arguments:ze(P(),P()).optional()}),ka=tt.extend({method:G("prompts/get"),params:sA}),mp=B({type:G("text"),text:P(),annotations:po.optional(),_meta:ze(P(),Ue()).optional()}),gp=B({type:G("image"),data:fp,mimeType:P(),annotations:po.optional(),_meta:ze(P(),Ue()).optional()}),yp=B({type:G("audio"),data:fp,mimeType:P(),annotations:po.optional(),_meta:ze(P(),Ue()).optional()}),iA=B({type:G("tool_use"),name:P(),id:P(),input:ze(P(),Ue()),_meta:ze(P(),Ue()).optional()}),aA=B({type:G("resource"),resource:Ne([Uw,Zw]),annotations:po.optional(),_meta:ze(P(),Ue()).optional()}),cA=qw.extend({type:G("resource_link")}),bp=Ne([mp,gp,yp,cA,aA]),lA=B({role:ks,content:bp}),uA=rt.extend({description:P().optional(),messages:ye(lA)}),dA=Mt.extend({method:G("notifications/prompts/list_changed"),params:Lt.optional()}),pA=B({title:P().optional(),readOnlyHint:Ye().optional(),destructiveHint:Ye().optional(),idempotentHint:Ye().optional(),openWorldHint:Ye().optional()}),fA=B({taskSupport:_t(["required","optional","forbidden"]).optional()}),Fw=B({...lo.shape,...ws.shape,description:P().optional(),inputSchema:B({type:G("object"),properties:ze(P(),Je).optional(),required:ye(P()).optional()}).catchall(Ue()),outputSchema:B({type:G("object"),properties:ze(P(),Je).optional(),required:ye(P()).optional()}).catchall(Ue()).optional(),annotations:pA.optional(),execution:fA.optional(),_meta:ze(P(),Ue()).optional()}),Sa=_s.extend({method:G("tools/list")}),hA=vs.extend({tools:ye(Fw)}),Ta=rt.extend({content:ye(bp).default([]),structuredContent:ze(P(),Ue()).optional(),isError:Ye().optional()}),SZ=Ta.or(rt.extend({toolResult:Ue()})),mA=ys.extend({name:P(),arguments:ze(P(),Ue()).optional()}),fo=tt.extend({method:G("tools/call"),params:mA}),gA=Mt.extend({method:G("notifications/tools/list_changed"),params:Lt.optional()}),TZ=B({autoRefresh:Ye().default(!0),debounceMs:Te().int().nonnegative().default(300)}),Ss=_t(["debug","info","notice","warning","error","critical","alert","emergency"]),yA=Et.extend({level:Ss}),wp=tt.extend({method:G("logging/setLevel"),params:yA}),bA=Lt.extend({level:Ss,logger:P().optional(),data:Ue()}),wA=Mt.extend({method:G("notifications/message"),params:bA}),_A=B({name:P().optional()}),vA=B({hints:ye(_A).optional(),costPriority:Te().min(0).max(1).optional(),speedPriority:Te().min(0).max(1).optional(),intelligencePriority:Te().min(0).max(1).optional()}),xA=B({mode:_t(["auto","required","none"]).optional()}),$A=B({type:G("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:ye(bp).default([]),structuredContent:B({}).loose().optional(),isError:Ye().optional(),_meta:ze(P(),Ue()).optional()}),kA=np("type",[mp,gp,yp]),aa=np("type",[mp,gp,yp,iA,$A]),SA=B({role:ks,content:Ne([aa,ye(aa)]),_meta:ze(P(),Ue()).optional()}),TA=ys.extend({messages:ye(SA),modelPreferences:vA.optional(),systemPrompt:P().optional(),includeContext:_t(["none","thisServer","allServers"]).optional(),temperature:Te().optional(),maxTokens:Te().int(),stopSequences:ye(P()).optional(),metadata:Je.optional(),tools:ye(Fw).optional(),toolChoice:xA.optional()}),EA=tt.extend({method:G("sampling/createMessage"),params:TA}),Ts=rt.extend({model:P(),stopReason:Ze(_t(["endTurn","stopSequence","maxTokens"]).or(P())),role:ks,content:kA}),_p=rt.extend({model:P(),stopReason:Ze(_t(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:ks,content:Ne([aa,ye(aa)])}),RA=B({type:G("boolean"),title:P().optional(),description:P().optional(),default:Ye().optional()}),PA=B({type:G("string"),title:P().optional(),description:P().optional(),minLength:Te().optional(),maxLength:Te().optional(),format:_t(["email","uri","date","date-time"]).optional(),default:P().optional()}),AA=B({type:_t(["number","integer"]),title:P().optional(),description:P().optional(),minimum:Te().optional(),maximum:Te().optional(),default:Te().optional()}),IA=B({type:G("string"),title:P().optional(),description:P().optional(),enum:ye(P()),default:P().optional()}),OA=B({type:G("string"),title:P().optional(),description:P().optional(),oneOf:ye(B({const:P(),title:P()})),default:P().optional()}),CA=B({type:G("string"),title:P().optional(),description:P().optional(),enum:ye(P()),enumNames:ye(P()).optional(),default:P().optional()}),zA=Ne([IA,OA]),NA=B({type:G("array"),title:P().optional(),description:P().optional(),minItems:Te().optional(),maxItems:Te().optional(),items:B({type:G("string"),enum:ye(P())}),default:ye(P()).optional()}),jA=B({type:G("array"),title:P().optional(),description:P().optional(),minItems:Te().optional(),maxItems:Te().optional(),items:B({anyOf:ye(B({const:P(),title:P()}))}),default:ye(P()).optional()}),LA=Ne([NA,jA]),MA=Ne([CA,zA,LA]),DA=Ne([MA,RA,PA,AA]),UA=ys.extend({mode:G("form").optional(),message:P(),requestedSchema:B({type:G("object"),properties:ze(P(),DA),required:ye(P()).optional()})}),ZA=ys.extend({mode:G("url"),message:P(),elicitationId:P(),url:P().url()}),qA=Ne([UA,ZA]),FA=tt.extend({method:G("elicitation/create"),params:qA}),BA=Lt.extend({elicitationId:P()}),VA=Mt.extend({method:G("notifications/elicitation/complete"),params:BA}),ho=rt.extend({action:_t(["accept","decline","cancel"]),content:op(t=>t===null?void 0:t,ze(P(),Ne([P(),Te(),Ye(),ye(P())])).optional())}),HA=B({type:G("ref/resource"),uri:P()}),KA=B({type:G("ref/prompt"),name:P()}),GA=Et.extend({ref:Ne([KA,HA]),argument:B({name:P(),value:P()}),context:B({arguments:ze(P(),P()).optional()}).optional()}),Ea=tt.extend({method:G("completion/complete"),params:GA});WA=rt.extend({completion:dt({values:ye(P()).max(100),total:Ze(Te().int()),hasMore:Ze(Ye())})}),JA=B({uri:P().startsWith("file://"),name:P().optional(),_meta:ze(P(),Ue()).optional()}),YA=tt.extend({method:G("roots/list"),params:Et.optional()}),vp=rt.extend({roots:ye(JA)}),XA=Mt.extend({method:G("notifications/roots/list_changed"),params:Lt.optional()}),EZ=Ne([pa,dp,Ea,wp,ka,$a,_a,va,xa,YP,QP,fo,Sa,ha,ga,ya,wa]),RZ=Ne([da,fa,pp,XA,$s]),PZ=Ne([ua,Ts,_p,ho,vp,ma,ba,uo]),AZ=Ne([pa,EA,FA,YA,ha,ga,ya,wa]),IZ=Ne([da,fa,wA,tA,WP,gA,dA,$s,VA]),OZ=Ne([ua,MP,WA,uA,oA,VP,HP,GP,Ta,hA,ma,ba,uo]),K=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===Y.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new sp(o.elicitations,r)}return new t(e,r,n)}},sp=class extends K{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Y.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Br(t){return t==="completed"||t==="failed"||t==="cancelled"}var Hw=O(()=>{});var Gw,Kw,Ww,Ra=O(()=>{Gw=Symbol("Let zodToJsonSchema decide on which parser to use"),Kw={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Ww=t=>typeof t=="string"?{...Kw,name:t}:{...Kw,...t}});var Jw,xp=O(()=>{Ra();Jw=t=>{let e=Ww(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function $p(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function be(t,e,r,n,o){t[e]=r,$p(t,e,n,o)}var Vr=O(()=>{});var Pa,Aa=O(()=>{Pa=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function qe(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Pa(e,t.currentPath):e.join("/")}}var Dt=O(()=>{Aa()});function Yw(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==M.ZodAny&&(r.items=ee(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&be(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&be(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(be(r,"minItems",t.exactLength.value,t.exactLength.message,e),be(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var kp=O(()=>{ts();Vr();Ge()});function Xw(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?be(r,"minimum",n.value,n.message,e):be(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),be(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?be(r,"maximum",n.value,n.message,e):be(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),be(r,"maximum",n.value,n.message,e));break;case"multipleOf":be(r,"multipleOf",n.value,n.message,e);break}return r}var Sp=O(()=>{Vr()});function Qw(){return{type:"boolean"}}var Tp=O(()=>{});function Ia(t,e){return ee(t.type._def,e)}var Oa=O(()=>{Ge()});var e_,Ep=O(()=>{Ge();e_=(t,e)=>ee(t.innerType._def,e)});function Rp(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Rp(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return QA(t,e)}}var QA,Pp=O(()=>{Vr();QA=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":be(r,"minimum",n.value,n.message,e);break;case"max":be(r,"maximum",n.value,n.message,e);break}return r}});function t_(t,e){return{...ee(t.innerType._def,e),default:t.defaultValue()}}var Ap=O(()=>{Ge()});function r_(t,e){return e.effectStrategy==="input"?ee(t.schema._def,e):qe(e)}var Ip=O(()=>{Ge();Dt()});function n_(t){return{type:"string",enum:Array.from(t.values)}}var Op=O(()=>{});function o_(t,e){let r=[ee(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ee(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(eI(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var eI,Cp=O(()=>{Ge();eI=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function s_(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var zp=O(()=>{});function Ca(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":be(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":be(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Gt(r,"email",n.message,e);break;case"format:idn-email":Gt(r,"idn-email",n.message,e);break;case"pattern:zod":pt(r,Kt.email,n.message,e);break}break;case"url":Gt(r,"uri",n.message,e);break;case"uuid":Gt(r,"uuid",n.message,e);break;case"regex":pt(r,n.regex,n.message,e);break;case"cuid":pt(r,Kt.cuid,n.message,e);break;case"cuid2":pt(r,Kt.cuid2,n.message,e);break;case"startsWith":pt(r,RegExp(`^${jp(n.value,e)}`),n.message,e);break;case"endsWith":pt(r,RegExp(`${jp(n.value,e)}$`),n.message,e);break;case"datetime":Gt(r,"date-time",n.message,e);break;case"date":Gt(r,"date",n.message,e);break;case"time":Gt(r,"time",n.message,e);break;case"duration":Gt(r,"duration",n.message,e);break;case"length":be(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),be(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{pt(r,RegExp(jp(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Gt(r,"ipv4",n.message,e),n.version!=="v4"&&Gt(r,"ipv6",n.message,e);break}case"base64url":pt(r,Kt.base64url,n.message,e);break;case"jwt":pt(r,Kt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&pt(r,Kt.ipv4Cidr,n.message,e),n.version!=="v4"&&pt(r,Kt.ipv6Cidr,n.message,e);break}case"emoji":pt(r,Kt.emoji(),n.message,e);break;case"ulid":{pt(r,Kt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Gt(r,"binary",n.message,e);break}case"contentEncoding:base64":{be(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{pt(r,Kt.base64,n.message,e);break}}break}case"nanoid":pt(r,Kt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function jp(t,e){return e.patternStrategy==="escape"?rI(t):t}function rI(t){let e="";for(let r=0;r<t.length;r++)tI.has(t[r])||(e+="\\"),e+=t[r];return e}function Gt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):be(t,"format",e,r,n)}function pt(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:i_(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):be(t,"pattern",i_(e,n),r,n)}function i_(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
927
982
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
928
983
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
929
984
  `:`[${n[c]}\r
930
- ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Cp,Gt,YA,za=O(()=>{Br();Gt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Cp===void 0&&(Cp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Cp),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};YA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Na(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===L.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:ee(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??qe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ee(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===L.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ca(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===L.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===L.ZodBranded&&t.keyType._def.type._def.typeName===L.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ia(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var ja=O(()=>{es();Ge();za();Oa();Dt()});function ow(t,e){if(e.mapStrategy==="record")return Na(t,e);let r=ee(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||qe(e),n=ee(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||qe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Np=O(()=>{Ge();ja();Dt()});function sw(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var jp=O(()=>{});function iw(t){return t.target==="openAi"?void 0:{not:qe({...t,currentPath:[...t.currentPath,"not"]})}}var Lp=O(()=>{Dt()});function aw(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Mp=O(()=>{});function lw(t,e){if(e.target==="openApi3")return cw(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ts&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Ts[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return cw(t,e)}var Ts,cw,La=O(()=>{Ge();Ts={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};cw=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ee(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function uw(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Ts[t.innerType._def.typeName],nullable:!0}:{type:[Ts[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ee(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ee(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Dp=O(()=>{Ge();La()});function dw(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",vp(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ge(r,"minimum",n.value,n.message,e):ge(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ge(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ge(r,"maximum",n.value,n.message,e):ge(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ge(r,"maximum",n.value,n.message,e));break;case"multipleOf":ge(r,"multipleOf",n.value,n.message,e);break}return r}var Up=O(()=>{Br()});function pw(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let l=eI(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ee(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,l||o.push(a))}o.length&&(n.required=o);let i=QA(t,e);return i!==void 0&&(n.additionalProperties=i),n}function QA(t,e){if(t.catchall._def.typeName!=="ZodNever")return ee(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function eI(t){try{return t.isOptional()}catch{return!0}}var Zp=O(()=>{Ge()});var fw,qp=O(()=>{Ge();Dt();fw=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ee(t.innerType._def,e);let r=ee(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:qe(e)},r]}:qe(e)}});var hw,Fp=O(()=>{Ge();hw=(t,e)=>{if(e.pipeStrategy==="input")return ee(t.in._def,e);if(e.pipeStrategy==="output")return ee(t.out._def,e);let r=ee(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ee(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function mw(t,e){return ee(t.type._def,e)}var Bp=O(()=>{Ge()});function gw(t,e){let n={type:"array",uniqueItems:!0,items:ee(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ge(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ge(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Vp=O(()=>{Br();Ge()});function yw(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ee(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ee(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ee(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Hp=O(()=>{Ge()});function bw(t){return{not:qe(t)}}var Kp=O(()=>{Dt()});function _w(t){return qe(t)}var Gp=O(()=>{Dt()});var ww,Wp=O(()=>{Ge();ww=(t,e)=>ee(t.innerType._def,e)});var vw,Jp=O(()=>{es();Dt();xp();$p();kp();Oa();Sp();Ep();Rp();Pp();Ap();Ip();Op();Np();jp();Lp();Mp();Dp();Up();Zp();qp();Fp();Bp();ja();Vp();za();Hp();Kp();La();Gp();Wp();vw=(t,e,r)=>{switch(e){case L.ZodString:return Ca(t,r);case L.ZodNumber:return dw(t,r);case L.ZodObject:return pw(t,r);case L.ZodBigInt:return W_(t,r);case L.ZodBoolean:return J_();case L.ZodDate:return Tp(t,r);case L.ZodUndefined:return bw(r);case L.ZodNull:return aw(r);case L.ZodArray:return G_(t,r);case L.ZodUnion:case L.ZodDiscriminatedUnion:return lw(t,r);case L.ZodIntersection:return tw(t,r);case L.ZodTuple:return yw(t,r);case L.ZodRecord:return Na(t,r);case L.ZodLiteral:return rw(t,r);case L.ZodEnum:return ew(t);case L.ZodNativeEnum:return sw(t);case L.ZodNullable:return uw(t,r);case L.ZodOptional:return fw(t,r);case L.ZodMap:return ow(t,r);case L.ZodSet:return gw(t,r);case L.ZodLazy:return()=>t.getter()._def;case L.ZodPromise:return mw(t,r);case L.ZodNaN:case L.ZodNever:return iw(r);case L.ZodEffects:return Q_(t,r);case L.ZodAny:return qe(r);case L.ZodUnknown:return _w(r);case L.ZodDefault:return X_(t,r);case L.ZodBranded:return Ia(t,r);case L.ZodReadonly:return ww(t,r);case L.ZodCatch:return Y_(t,r);case L.ZodPipeline:return hw(t,r);case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:return;default:return(n=>{})(e)}}});function ee(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==V_)return a}if(n&&!r){let a=tI(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=vw(t,t.typeName,e),i=typeof s=="function"?ee(s(),e):s;if(i&&rI(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var tI,rI,Ge=O(()=>{Ra();Jp();Aa();Dt();tI=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Pa(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),qe(e)):e.$refStrategy==="seen"?qe(e):void 0}},rI=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var xw=O(()=>{});var Yp,Xp=O(()=>{Ge();wp();Dt();Yp=(t,e)=>{let r=K_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ee(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??qe(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ee(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??qe(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var $w=O(()=>{Ra();wp();Br();Aa();Ge();xw();Dt();xp();$p();kp();Oa();Sp();Ep();Rp();Pp();Ap();Ip();Op();Np();jp();Lp();Mp();Dp();Up();Zp();qp();Fp();Bp();Wp();ja();Vp();za();Hp();Kp();La();Gp();Jp();Xp();Xp()});function nI(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Qp(t,e){return ar(t)?Ud(t,{target:nI(e?.target),io:e?.pipeStrategy??"input"}):Yp(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function ef(t){let r=Zr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=so(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function tf(t,e){let r=Ur(t,e);if(!r.success)throw r.error;return r.data}var rf=O(()=>{Fd();fs();$w()});function kw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Sw(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];kw(i)&&kw(s)?r[o]={...i,...s}:r[o]=s}return r}var oI,Ma,Tw=O(()=>{fs();po();F_();rf();oI=6e4,Ma=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(da,r=>{this._oncancel(r)}),this.setNotificationHandler(fa,r=>{this._onprogress(r)}),this.setRequestHandler(pa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ha,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new H(J.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ga,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,y=new H(d.error.code,d.error.message,d.error.data);u(y)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new H(J.InvalidParams,`Task not found: ${s}`);if(!Fr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Fr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[qr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ya,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new H(J.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(_a,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new H(J.InvalidParams,`Task not found: ${r.params.taskId}`);if(Fr(o.status))throw new H(J.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new H(J.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof H?o:new H(J.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),H.fromError(J.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),ys(s)||O_(s)?this._onresponse(s):ip(s)?this._onrequest(s,i):I_(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=H.fromError(J.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[qr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:J.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=R_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(u,d)},sendRequest:async(u,d,y)=>{if(i.signal.aborted)throw new H(J.ConnectionClosed,"Request was cancelled");let h={...y,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let f=h.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(u,d,h)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:J.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ys(e))n(e);else{let i=new H(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(ys(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),ys(e))o(e);else{let i=H.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof H?i:new H(J.InternalError,String(i))}}return}let s;try{let i=await this.request(e,ao,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new H(J.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Fr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new H(J.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new H(J.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof H?i:new H(J.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=R=>{u(R)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(R){d(R);return}n?.signal?.throwIfAborted();let y=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:y};n?.onprogress&&(this._progressHandlers.set(y,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:y}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[qr]:c}});let f=R=>{this._responseHandlers.delete(y),this._progressHandlers.delete(y),this._cleanupTimeout(y),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(R)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(B=>this._onerror(new Error(`Failed to send cancellation: ${B}`)));let C=R instanceof H?R:new H(J.RequestTimeout,String(R));u(C)};this._responseHandlers.set(y,R=>{if(!n?.signal?.aborted){if(R instanceof Error)return u(R);try{let C=Ur(r,R.result);C.success?l(C.data):u(C.error)}catch(C){u(C)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let g=n?.timeout??oI,w=()=>f(H.fromError(J.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(y,g,n?.maxTotalTimeout,w,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let R=C=>{let B=this._responseHandlers.get(y);B?B(C):this._onerror(new Error(`Response handler missing for side-channeled request ${y}`))};this._requestResolvers.set(y,R),this._enqueueTaskMessage(E,{type:"request",message:h,timestamp:Date.now()}).catch(C=>{this._cleanupTimeout(y),u(C)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(R=>{this._cleanupTimeout(y),u(R)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ma,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ba,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},N_,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[qr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[qr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[qr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=ef(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=tf(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=ef(e);this._notificationHandlers.set(n,o=>{let s=tf(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&ip(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new H(J.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new H(J.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new H(J.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new H(J.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=xs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Fr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new H(J.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Fr(a.status))throw new H(J.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=xs.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Fr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Ps=U(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.regexpCode=we.getEsmExportName=we.getProperty=we.safeStringify=we.stringify=we.strConcat=we.addCodeArg=we.str=we._=we.nil=we._Code=we.Name=we.IDENTIFIER=we._CodeOrName=void 0;var Es=class{};we._CodeOrName=Es;we.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var En=class extends Es{constructor(e){if(super(),!we.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};we.Name=En;var Ut=class extends Es{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof En&&(r[n.str]=(r[n.str]||0)+1),r),{})}};we._Code=Ut;we.nil=new Ut("");function Ew(t,...e){let r=[t[0]],n=0;for(;n<e.length;)of(r,e[n]),r.push(t[++n]);return new Ut(r)}we._=Ew;var nf=new Ut("+");function Rw(t,...e){let r=[Rs(t[0])],n=0;for(;n<e.length;)r.push(nf),of(r,e[n]),r.push(nf,Rs(t[++n]));return sI(r),new Ut(r)}we.str=Rw;function of(t,e){e instanceof Ut?t.push(...e._items):e instanceof En?t.push(e):t.push(cI(e))}we.addCodeArg=of;function sI(t){let e=1;for(;e<t.length-1;){if(t[e]===nf){let r=iI(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function iI(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof En||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof En))return`"${t}${e.slice(1)}`}function aI(t,e){return e.emptyStr()?t:t.emptyStr()?e:Rw`${t}${e}`}we.strConcat=aI;function cI(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Rs(Array.isArray(t)?t.join(","):t)}function lI(t){return new Ut(Rs(t))}we.stringify=lI;function Rs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}we.safeStringify=Rs;function uI(t){return typeof t=="string"&&we.IDENTIFIER.test(t)?new Ut(`.${t}`):Ew`[${t}]`}we.getProperty=uI;function dI(t){if(typeof t=="string"&&we.IDENTIFIER.test(t))return new Ut(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}we.getEsmExportName=dI;function pI(t){return new Ut(t.toString())}we.regexpCode=pI});var cf=U(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.ValueScope=xt.ValueScopeName=xt.Scope=xt.varKinds=xt.UsedValueState=void 0;var vt=Ps(),sf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Da;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Da||(xt.UsedValueState=Da={}));xt.varKinds={const:new vt.Name("const"),let:new vt.Name("let"),var:new vt.Name("var")};var Ua=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof vt.Name?e:this.name(e)}name(e){return new vt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};xt.Scope=Ua;var Za=class extends vt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,vt._)`.${new vt.Name(r)}[${n}]`}};xt.ValueScopeName=Za;var fI=(0,vt._)`\n`,af=class extends Ua{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?fI:vt.nil}}get(){return this._scope}name(e){return new Za(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,itemIndex:l}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,vt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=vt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Da.Started);let u=r(l);if(u){let d=this.opts.es5?xt.varKinds.var:xt.varKinds.const;s=(0,vt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,vt._)`${s}${u}${this.opts._n}`;else throw new sf(l);c.set(l,Da.Completed)})}return s}};xt.ValueScope=af});var ae=U(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.or=le.and=le.not=le.CodeGen=le.operators=le.varKinds=le.ValueScopeName=le.ValueScope=le.Scope=le.Name=le.regexpCode=le.stringify=le.getProperty=le.nil=le.strConcat=le.str=le._=void 0;var ye=Ps(),Jt=cf(),Vr=Ps();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return Vr._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return Vr.str}});Object.defineProperty(le,"strConcat",{enumerable:!0,get:function(){return Vr.strConcat}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return Vr.nil}});Object.defineProperty(le,"getProperty",{enumerable:!0,get:function(){return Vr.getProperty}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return Vr.stringify}});Object.defineProperty(le,"regexpCode",{enumerable:!0,get:function(){return Vr.regexpCode}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return Vr.Name}});var Va=cf();Object.defineProperty(le,"Scope",{enumerable:!0,get:function(){return Va.Scope}});Object.defineProperty(le,"ValueScope",{enumerable:!0,get:function(){return Va.ValueScope}});Object.defineProperty(le,"ValueScopeName",{enumerable:!0,get:function(){return Va.ValueScopeName}});Object.defineProperty(le,"varKinds",{enumerable:!0,get:function(){return Va.varKinds}});le.operators={GT:new ye._Code(">"),GTE:new ye._Code(">="),LT:new ye._Code("<"),LTE:new ye._Code("<="),EQ:new ye._Code("==="),NEQ:new ye._Code("!=="),NOT:new ye._Code("!"),OR:new ye._Code("||"),AND:new ye._Code("&&"),ADD:new ye._Code("+")};var $r=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},lf=class extends $r{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Jt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=ho(this.rhs,e,r)),this}get names(){return this.rhs instanceof ye._CodeOrName?this.rhs.names:{}}},qa=class extends $r{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ye.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ho(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ye.Name?{}:{...this.lhs.names};return Ba(e,this.rhs)}},uf=class extends qa{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},df=class extends $r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},pf=class extends $r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ff=class extends $r{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},hf=class extends $r{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=ho(this.code,e,r),this}get names(){return this.code instanceof ye._CodeOrName?this.code.names:{}}},As=class extends $r{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(hI(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>An(e,r.names),{})}},kr=class extends As{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},mf=class extends As{},fo=class extends kr{};fo.kind="else";var Rn=class t extends kr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new fo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Pw(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=ho(this.condition,e,r),this}get names(){let e=super.names;return Ba(e,this.condition),this.else&&An(e,this.else.names),e}};Rn.kind="if";var Pn=class extends kr{};Pn.kind="for";var gf=class extends Pn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=ho(this.iteration,e,r),this}get names(){return An(super.names,this.iteration.names)}},yf=class extends Pn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Jt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ba(super.names,this.from);return Ba(e,this.to)}},Fa=class extends Pn{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=ho(this.iterable,e,r),this}get names(){return An(super.names,this.iterable.names)}},Is=class extends kr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Is.kind="func";var Os=class extends As{render(e){return"return "+super.render(e)}};Os.kind="return";var bf=class extends kr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&An(e,this.catch.names),this.finally&&An(e,this.finally.names),e}},Cs=class extends kr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Cs.kind="catch";var zs=class extends kr{render(e){return"finally"+super.render(e)}};zs.kind="finally";var _f=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
931
- `:""},this._extScope=e,this._scope=new Jt.Scope({parent:e}),this._nodes=[new mf]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new lf(e,s,n)),s}const(e,r,n){return this._def(Jt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Jt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Jt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new qa(e,r,n))}add(e,r){return this._leafNode(new uf(e,le.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ye.nil&&this._leafNode(new hf(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ye.addCodeArg)(r,o));return r.push("}"),new ye._Code(r)}if(e,r,n){if(this._blockNode(new Rn(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Rn(e))}else(){return this._elseNode(new fo)}endIf(){return this._endBlockNode(Rn,fo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new gf(e),r)}forRange(e,r,n,o,s=this.opts.es5?Jt.varKinds.var:Jt.varKinds.let){let i=this._scope.toName(e);return this._for(new yf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Jt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ye.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ye._)`${i}.length`,a=>{this.var(s,(0,ye._)`${i}[${a}]`),n(s)})}return this._for(new Fa("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Jt.varKinds.var:Jt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ye._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Fa("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Pn)}label(e){return this._leafNode(new df(e))}break(e){return this._leafNode(new pf(e))}return(e){let r=new Os;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Os)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new bf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Cs(s),r(s)}return n&&(this._currNode=o.finally=new zs,this.code(n)),this._endBlockNode(Cs,zs)}throw(e){return this._leafNode(new ff(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ye.nil,n,o){return this._blockNode(new Is(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Is)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Rn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};le.CodeGen=_f;function An(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ba(t,e){return e instanceof ye._CodeOrName?An(t,e.names):t}function ho(t,e,r){if(t instanceof ye.Name)return n(t);if(!o(t))return t;return new ye._Code(t._items.reduce((s,i)=>(i instanceof ye.Name&&(i=n(i)),i instanceof ye._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ye._Code&&s._items.some(i=>i instanceof ye.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function hI(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Pw(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ye._)`!${wf(t)}`}le.not=Pw;var mI=Aw(le.operators.AND);function gI(...t){return t.reduce(mI)}le.and=gI;var yI=Aw(le.operators.OR);function bI(...t){return t.reduce(yI)}le.or=bI;function Aw(t){return(e,r)=>e===ye.nil?r:r===ye.nil?e:(0,ye._)`${wf(e)} ${t} ${wf(r)}`}function wf(t){return t instanceof ye.Name?t:(0,ye._)`(${t})`}});var be=U(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.checkStrictMode=de.getErrorPath=de.Type=de.useFunc=de.setEvaluated=de.evaluatedPropsToName=de.mergeEvaluated=de.eachItem=de.unescapeJsonPointer=de.escapeJsonPointer=de.escapeFragment=de.unescapeFragment=de.schemaRefOrVal=de.schemaHasRulesButRef=de.schemaHasRules=de.checkUnknownRules=de.alwaysValidSchema=de.toHash=void 0;var Ae=ae(),_I=Ps();function wI(t){let e={};for(let r of t)e[r]=!0;return e}de.toHash=wI;function vI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Cw(t,e),!zw(e,t.self.RULES.all))}de.alwaysValidSchema=vI;function Cw(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Lw(t,`unknown keyword: "${s}"`)}de.checkUnknownRules=Cw;function zw(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}de.schemaHasRules=zw;function xI(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}de.schemaHasRulesButRef=xI;function $I({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ae._)`${r}`}return(0,Ae._)`${t}${e}${(0,Ae.getProperty)(n)}`}de.schemaRefOrVal=$I;function kI(t){return Nw(decodeURIComponent(t))}de.unescapeFragment=kI;function SI(t){return encodeURIComponent(xf(t))}de.escapeFragment=SI;function xf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}de.escapeJsonPointer=xf;function Nw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}de.unescapeJsonPointer=Nw;function TI(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}de.eachItem=TI;function Iw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ae.Name?(s instanceof Ae.Name?t(o,s,i):e(o,s,i),i):s instanceof Ae.Name?(e(o,i,s),s):r(s,i);return a===Ae.Name&&!(c instanceof Ae.Name)?n(o,c):c}}de.mergeEvaluated={props:Iw({mergeNames:(t,e,r)=>t.if((0,Ae._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ae._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ae._)`${r} || {}`).code((0,Ae._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ae._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ae._)`${r} || {}`),$f(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:jw}),items:Iw({mergeNames:(t,e,r)=>t.if((0,Ae._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ae._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ae._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ae._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function jw(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ae._)`{}`);return e!==void 0&&$f(t,r,e),r}de.evaluatedPropsToName=jw;function $f(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ae._)`${e}${(0,Ae.getProperty)(n)}`,!0))}de.setEvaluated=$f;var Ow={};function EI(t,e){return t.scopeValue("func",{ref:e,code:Ow[e.code]||(Ow[e.code]=new _I._Code(e.code))})}de.useFunc=EI;var vf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(vf||(de.Type=vf={}));function RI(t,e,r){if(t instanceof Ae.Name){let n=e===vf.Num;return r?n?(0,Ae._)`"[" + ${t} + "]"`:(0,Ae._)`"['" + ${t} + "']"`:n?(0,Ae._)`"/" + ${t}`:(0,Ae._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ae.getProperty)(t).toString():"/"+xf(t)}de.getErrorPath=RI;function Lw(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}de.checkStrictMode=Lw});var Sr=U(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var it=ae(),PI={data:new it.Name("data"),valCxt:new it.Name("valCxt"),instancePath:new it.Name("instancePath"),parentData:new it.Name("parentData"),parentDataProperty:new it.Name("parentDataProperty"),rootData:new it.Name("rootData"),dynamicAnchors:new it.Name("dynamicAnchors"),vErrors:new it.Name("vErrors"),errors:new it.Name("errors"),this:new it.Name("this"),self:new it.Name("self"),scope:new it.Name("scope"),json:new it.Name("json"),jsonPos:new it.Name("jsonPos"),jsonLen:new it.Name("jsonLen"),jsonPart:new it.Name("jsonPart")};kf.default=PI});var Ns=U(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.extendErrors=at.resetErrorsCount=at.reportExtraError=at.reportError=at.keyword$DataError=at.keywordError=void 0;var _e=ae(),Ha=be(),ft=Sr();at.keywordError={message:({keyword:t})=>(0,_e.str)`must pass "${t}" keyword validation`};at.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,_e.str)`"${t}" keyword must be ${e} ($data)`:(0,_e.str)`"${t}" keyword is invalid ($data)`};function AI(t,e=at.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Uw(t,e,r);n??(i||a)?Mw(s,c):Dw(o,(0,_e._)`[${c}]`)}at.reportError=AI;function II(t,e=at.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Uw(t,e,r);Mw(o,a),s||i||Dw(n,ft.default.vErrors)}at.reportExtraError=II;function OI(t,e){t.assign(ft.default.errors,e),t.if((0,_e._)`${ft.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,_e._)`${ft.default.vErrors}.length`,e),()=>t.assign(ft.default.vErrors,null)))}at.resetErrorsCount=OI;function CI({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,ft.default.errors,a=>{t.const(i,(0,_e._)`${ft.default.vErrors}[${a}]`),t.if((0,_e._)`${i}.instancePath === undefined`,()=>t.assign((0,_e._)`${i}.instancePath`,(0,_e.strConcat)(ft.default.instancePath,s.errorPath))),t.assign((0,_e._)`${i}.schemaPath`,(0,_e.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,_e._)`${i}.schema`,r),t.assign((0,_e._)`${i}.data`,n))})}at.extendErrors=CI;function Mw(t,e){let r=t.const("err",e);t.if((0,_e._)`${ft.default.vErrors} === null`,()=>t.assign(ft.default.vErrors,(0,_e._)`[${r}]`),(0,_e._)`${ft.default.vErrors}.push(${r})`),t.code((0,_e._)`${ft.default.errors}++`)}function Dw(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,_e._)`new ${t.ValidationError}(${e})`):(r.assign((0,_e._)`${n}.errors`,e),r.return(!1))}var In={keyword:new _e.Name("keyword"),schemaPath:new _e.Name("schemaPath"),params:new _e.Name("params"),propertyName:new _e.Name("propertyName"),message:new _e.Name("message"),schema:new _e.Name("schema"),parentSchema:new _e.Name("parentSchema")};function Uw(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,_e._)`{}`:zI(t,e,r)}function zI(t,e,r={}){let{gen:n,it:o}=t,s=[NI(o,r),jI(t,r)];return LI(t,e,s),n.object(...s)}function NI({errorPath:t},{instancePath:e}){let r=e?(0,_e.str)`${t}${(0,Ha.getErrorPath)(e,Ha.Type.Str)}`:t;return[ft.default.instancePath,(0,_e.strConcat)(ft.default.instancePath,r)]}function jI({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,_e.str)`${e}/${t}`;return r&&(o=(0,_e.str)`${o}${(0,Ha.getErrorPath)(r,Ha.Type.Str)}`),[In.schemaPath,o]}function LI(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([In.keyword,o],[In.params,typeof e=="function"?e(t):e||(0,_e._)`{}`]),c.messages&&n.push([In.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([In.schema,i],[In.parentSchema,(0,_e._)`${u}${d}`],[ft.default.data,s]),l&&n.push([In.propertyName,l])}});var qw=U(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.boolOrEmptySchema=mo.topBoolOrEmptySchema=void 0;var MI=Ns(),DI=ae(),UI=Sr(),ZI={message:"boolean schema is false"};function qI(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Zw(t,!1):typeof r=="object"&&r.$async===!0?e.return(UI.default.data):(e.assign((0,DI._)`${n}.errors`,null),e.return(!0))}mo.topBoolOrEmptySchema=qI;function FI(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Zw(t)):r.var(e,!0)}mo.boolOrEmptySchema=FI;function Zw(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,MI.reportError)(o,ZI,void 0,e)}});var Sf=U(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.getRules=go.isJSONType=void 0;var BI=["string","number","integer","boolean","null","object","array"],VI=new Set(BI);function HI(t){return typeof t=="string"&&VI.has(t)}go.isJSONType=HI;function KI(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}go.getRules=KI});var Tf=U(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.shouldUseRule=Hr.shouldUseGroup=Hr.schemaHasRulesForType=void 0;function GI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Fw(t,n)}Hr.schemaHasRulesForType=GI;function Fw(t,e){return e.rules.some(r=>Bw(t,r))}Hr.shouldUseGroup=Fw;function Bw(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Hr.shouldUseRule=Bw});var js=U(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.reportTypeError=ct.checkDataTypes=ct.checkDataType=ct.coerceAndCheckDataType=ct.getJSONTypes=ct.getSchemaTypes=ct.DataType=void 0;var WI=Sf(),JI=Tf(),YI=Ns(),se=ae(),Vw=be(),yo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(yo||(ct.DataType=yo={}));function XI(t){let e=Hw(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ct.getSchemaTypes=XI;function Hw(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(WI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ct.getJSONTypes=Hw;function QI(t,e){let{gen:r,data:n,opts:o}=t,s=eO(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,JI.schemaHasRulesForType)(t,e[0]));if(i){let a=Rf(e,n,o.strictNumbers,yo.Wrong);r.if(a,()=>{s.length?tO(t,e,s):Pf(t)})}return i}ct.coerceAndCheckDataType=QI;var Kw=new Set(["string","number","integer","boolean","null"]);function eO(t,e){return e?t.filter(r=>Kw.has(r)||e==="array"&&r==="array"):[]}function tO(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,se._)`typeof ${o}`),a=n.let("coerced",(0,se._)`undefined`);s.coerceTypes==="array"&&n.if((0,se._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,se._)`${o}[0]`).assign(i,(0,se._)`typeof ${o}`).if(Rf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,se._)`${a} !== undefined`);for(let l of r)(Kw.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Pf(t),n.endIf(),n.if((0,se._)`${a} !== undefined`,()=>{n.assign(o,a),rO(t,a)});function c(l){switch(l){case"string":n.elseIf((0,se._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,se._)`"" + ${o}`).elseIf((0,se._)`${o} === null`).assign(a,(0,se._)`""`);return;case"number":n.elseIf((0,se._)`${i} == "boolean" || ${o} === null
932
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,se._)`+${o}`);return;case"integer":n.elseIf((0,se._)`${i} === "boolean" || ${o} === null
933
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,se._)`+${o}`);return;case"boolean":n.elseIf((0,se._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,se._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,se._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,se._)`${i} === "string" || ${i} === "number"
934
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,se._)`[${o}]`)}}}function rO({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,se._)`${e} !== undefined`,()=>t.assign((0,se._)`${e}[${r}]`,n))}function Ef(t,e,r,n=yo.Correct){let o=n===yo.Correct?se.operators.EQ:se.operators.NEQ,s;switch(t){case"null":return(0,se._)`${e} ${o} null`;case"array":s=(0,se._)`Array.isArray(${e})`;break;case"object":s=(0,se._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,se._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,se._)`typeof ${e} ${o} ${t}`}return n===yo.Correct?s:(0,se.not)(s);function i(a=se.nil){return(0,se.and)((0,se._)`typeof ${e} == "number"`,a,r?(0,se._)`isFinite(${e})`:se.nil)}}ct.checkDataType=Ef;function Rf(t,e,r,n){if(t.length===1)return Ef(t[0],e,r,n);let o,s=(0,Vw.toHash)(t);if(s.array&&s.object){let i=(0,se._)`typeof ${e} != "object"`;o=s.null?i:(0,se._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=se.nil;s.number&&delete s.integer;for(let i in s)o=(0,se.and)(o,Ef(i,e,r,n));return o}ct.checkDataTypes=Rf;var nO={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,se._)`{type: ${t}}`:(0,se._)`{type: ${e}}`};function Pf(t){let e=oO(t);(0,YI.reportError)(e,nO)}ct.reportTypeError=Pf;function oO(t){let{gen:e,data:r,schema:n}=t,o=(0,Vw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Ww=U(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.assignDefaults=void 0;var bo=ae(),sO=be();function iO(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Gw(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Gw(t,s,o.default))}Ka.assignDefaults=iO;function Gw(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,bo._)`${s}${(0,bo.getProperty)(e)}`;if(o){(0,sO.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,bo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,bo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,bo._)`${a} = ${(0,bo.stringify)(r)}`)}});var Zt=U(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.validateUnion=Pe.validateArray=Pe.usePattern=Pe.callValidateCode=Pe.schemaProperties=Pe.allSchemaProperties=Pe.noPropertyInData=Pe.propertyInData=Pe.isOwnProperty=Pe.hasPropFunc=Pe.reportMissingProp=Pe.checkMissingProp=Pe.checkReportMissingProp=void 0;var Ne=ae(),Af=be(),Kr=Sr(),aO=be();function cO(t,e){let{gen:r,data:n,it:o}=t;r.if(Of(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ne._)`${e}`},!0),t.error()})}Pe.checkReportMissingProp=cO;function lO({gen:t,data:e,it:{opts:r}},n,o){return(0,Ne.or)(...n.map(s=>(0,Ne.and)(Of(t,e,s,r.ownProperties),(0,Ne._)`${o} = ${s}`)))}Pe.checkMissingProp=lO;function uO(t,e){t.setParams({missingProperty:e},!0),t.error()}Pe.reportMissingProp=uO;function Jw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ne._)`Object.prototype.hasOwnProperty`})}Pe.hasPropFunc=Jw;function If(t,e,r){return(0,Ne._)`${Jw(t)}.call(${e}, ${r})`}Pe.isOwnProperty=If;function dO(t,e,r,n){let o=(0,Ne._)`${e}${(0,Ne.getProperty)(r)} !== undefined`;return n?(0,Ne._)`${o} && ${If(t,e,r)}`:o}Pe.propertyInData=dO;function Of(t,e,r,n){let o=(0,Ne._)`${e}${(0,Ne.getProperty)(r)} === undefined`;return n?(0,Ne.or)(o,(0,Ne.not)(If(t,e,r))):o}Pe.noPropertyInData=Of;function Yw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Pe.allSchemaProperties=Yw;function pO(t,e){return Yw(e).filter(r=>!(0,Af.alwaysValidSchema)(t,e[r]))}Pe.schemaProperties=pO;function fO({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Ne._)`${t}, ${e}, ${n}${o}`:e,d=[[Kr.default.instancePath,(0,Ne.strConcat)(Kr.default.instancePath,s)],[Kr.default.parentData,i.parentData],[Kr.default.parentDataProperty,i.parentDataProperty],[Kr.default.rootData,Kr.default.rootData]];i.opts.dynamicRef&&d.push([Kr.default.dynamicAnchors,Kr.default.dynamicAnchors]);let y=(0,Ne._)`${u}, ${r.object(...d)}`;return c!==Ne.nil?(0,Ne._)`${a}.call(${c}, ${y})`:(0,Ne._)`${a}(${y})`}Pe.callValidateCode=fO;var hO=(0,Ne._)`new RegExp`;function mO({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ne._)`${o.code==="new RegExp"?hO:(0,aO.useFunc)(t,o)}(${r}, ${n})`})}Pe.usePattern=mO;function gO(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Ne._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:Af.Type.Num},s),e.if((0,Ne.not)(s),a)})}}Pe.validateArray=gO;function yO(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Af.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(i,(0,Ne._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Ne.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Pe.validateUnion=yO});var ev=U(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.validateKeywordUsage=cr.validSchemaType=cr.funcKeywordCode=cr.macroKeywordCode=void 0;var ht=ae(),On=Sr(),bO=Zt(),_O=Ns();function wO(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Qw(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:ht.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}cr.macroKeywordCode=wO;function vO(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;$O(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Qw(n,o,l),d=n.let("valid");t.block$data(d,y),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function y(){if(e.errors===!1)g(),e.modifying&&Xw(t),w(()=>t.error());else{let E=e.async?h():f();e.modifying&&Xw(t),w(()=>xO(t,E))}}function h(){let E=n.let("ruleErrs",null);return n.try(()=>g((0,ht._)`await `),R=>n.assign(d,!1).if((0,ht._)`${R} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,ht._)`${R}.errors`),()=>n.throw(R))),E}function f(){let E=(0,ht._)`${u}.errors`;return n.assign(E,null),g(ht.nil),E}function g(E=e.async?(0,ht._)`await `:ht.nil){let R=c.opts.passContext?On.default.this:On.default.self,C=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ht._)`${E}${(0,bO.callValidateCode)(t,u,R,C)}`,e.modifying)}function w(E){var R;n.if((0,ht.not)((R=e.valid)!==null&&R!==void 0?R:d),E)}}cr.funcKeywordCode=vO;function Xw(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function xO(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(On.default.vErrors,(0,ht._)`${On.default.vErrors} === null ? ${e} : ${On.default.vErrors}.concat(${e})`).assign(On.default.errors,(0,ht._)`${On.default.vErrors}.length`),(0,_O.extendErrors)(t)},()=>t.error())}function $O({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Qw(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,ht.stringify)(r)})}function kO(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}cr.validSchemaType=kO;function SO({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}cr.validateKeywordUsage=SO});var rv=U(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.extendSubschemaMode=Gr.extendSubschemaData=Gr.getSubschema=void 0;var lr=ae(),tv=be();function TO(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,lr._)`${t.schemaPath}${(0,lr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,lr._)`${t.schemaPath}${(0,lr.getProperty)(e)}${(0,lr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,tv.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Gr.getSubschema=TO;function EO(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,y=a.let("data",(0,lr._)`${e.data}${(0,lr.getProperty)(r)}`,!0);c(y),t.errorPath=(0,lr.str)`${l}${(0,tv.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,lr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof lr.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Gr.extendSubschemaData=EO;function RO(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Gr.extendSubschemaMode=RO});var Cf=U((BF,nv)=>{"use strict";nv.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var sv=U((VF,ov)=>{"use strict";var Wr=ov.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Ga(e,n,o,t,"",t)};Wr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Wr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Wr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Wr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Ga(t,e,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in Wr.arrayKeywords)for(var y=0;y<d.length;y++)Ga(t,e,r,d[y],o+"/"+u+"/"+y,s,o,u,n,y)}else if(u in Wr.propsKeywords){if(d&&typeof d=="object")for(var h in d)Ga(t,e,r,d[h],o+"/"+u+"/"+PO(h),s,o,u,n,h)}else(u in Wr.keywords||t.allKeys&&!(u in Wr.skipKeywords))&&Ga(t,e,r,d,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function PO(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ls=U($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getSchemaRefs=$t.resolveUrl=$t.normalizeId=$t._getFullPath=$t.getFullPath=$t.inlineRef=void 0;var AO=be(),IO=Cf(),OO=sv(),CO=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function zO(t,e=!0){return typeof t=="boolean"?!0:e===!0?!zf(t):e?iv(t)<=e:!1}$t.inlineRef=zO;var NO=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function zf(t){for(let e in t){if(NO.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(zf)||typeof r=="object"&&zf(r))return!0}return!1}function iv(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!CO.has(r)&&(typeof t[r]=="object"&&(0,AO.eachItem)(t[r],n=>e+=iv(n)),e===1/0))return 1/0}return e}function av(t,e="",r){r!==!1&&(e=_o(e));let n=t.parse(e);return cv(t,n)}$t.getFullPath=av;function cv(t,e){return t.serialize(e).split("#")[0]+"#"}$t._getFullPath=cv;var jO=/#\/?$/;function _o(t){return t?t.replace(jO,""):""}$t.normalizeId=_o;function LO(t,e,r){return r=_o(r),t.resolve(e,r)}$t.resolveUrl=LO;var MO=/^[a-z_][-a-z0-9._]*$/i;function DO(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=_o(t[r]||e),s={"":o},i=av(n,o,!1),a={},c=new Set;return OO(t,{allKeys:!0},(d,y,h,f)=>{if(f===void 0)return;let g=i+y,w=s[f];typeof d[r]=="string"&&(w=E.call(this,d[r])),R.call(this,d.$anchor),R.call(this,d.$dynamicAnchor),s[y]=w;function E(C){let B=this.opts.uriResolver.resolve;if(C=_o(w?B(w,C):C),c.has(C))throw u(C);c.add(C);let W=this.refs[C];return typeof W=="string"&&(W=this.refs[W]),typeof W=="object"?l(d,W.schema,C):C!==_o(g)&&(C[0]==="#"?(l(d,a[C],C),a[C]=d):this.refs[C]=g),C}function R(C){if(typeof C=="string"){if(!MO.test(C))throw new Error(`invalid anchor "${C}"`);E.call(this,`#${C}`)}}}),a;function l(d,y,h){if(y!==void 0&&!IO(d,y))throw u(h)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}$t.getSchemaRefs=DO});var Us=U(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.getData=Jr.KeywordCxt=Jr.validateFunctionCode=void 0;var fv=qw(),lv=js(),jf=Tf(),Wa=js(),UO=Ww(),Ds=ev(),Nf=rv(),G=ae(),te=Sr(),ZO=Ls(),Tr=be(),Ms=Ns();function qO(t){if(gv(t)&&(yv(t),mv(t))){VO(t);return}hv(t,()=>(0,fv.topBoolOrEmptySchema)(t))}Jr.validateFunctionCode=qO;function hv({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,G._)`${te.default.data}, ${te.default.valCxt}`,n.$async,()=>{t.code((0,G._)`"use strict"; ${uv(r,o)}`),BO(t,o),t.code(s)}):t.func(e,(0,G._)`${te.default.data}, ${FO(o)}`,n.$async,()=>t.code(uv(r,o)).code(s))}function FO(t){return(0,G._)`{${te.default.instancePath}="", ${te.default.parentData}, ${te.default.parentDataProperty}, ${te.default.rootData}=${te.default.data}${t.dynamicRef?(0,G._)`, ${te.default.dynamicAnchors}={}`:G.nil}}={}`}function BO(t,e){t.if(te.default.valCxt,()=>{t.var(te.default.instancePath,(0,G._)`${te.default.valCxt}.${te.default.instancePath}`),t.var(te.default.parentData,(0,G._)`${te.default.valCxt}.${te.default.parentData}`),t.var(te.default.parentDataProperty,(0,G._)`${te.default.valCxt}.${te.default.parentDataProperty}`),t.var(te.default.rootData,(0,G._)`${te.default.valCxt}.${te.default.rootData}`),e.dynamicRef&&t.var(te.default.dynamicAnchors,(0,G._)`${te.default.valCxt}.${te.default.dynamicAnchors}`)},()=>{t.var(te.default.instancePath,(0,G._)`""`),t.var(te.default.parentData,(0,G._)`undefined`),t.var(te.default.parentDataProperty,(0,G._)`undefined`),t.var(te.default.rootData,te.default.data),e.dynamicRef&&t.var(te.default.dynamicAnchors,(0,G._)`{}`)})}function VO(t){let{schema:e,opts:r,gen:n}=t;hv(t,()=>{r.$comment&&e.$comment&&_v(t),JO(t),n.let(te.default.vErrors,null),n.let(te.default.errors,0),r.unevaluated&&HO(t),bv(t),QO(t)})}function HO(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,G._)`${r}.evaluated`),e.if((0,G._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,G._)`${t.evaluated}.props`,(0,G._)`undefined`)),e.if((0,G._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,G._)`${t.evaluated}.items`,(0,G._)`undefined`))}function uv(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,G._)`/*# sourceURL=${r} */`:G.nil}function KO(t,e){if(gv(t)&&(yv(t),mv(t))){GO(t,e);return}(0,fv.boolOrEmptySchema)(t,e)}function mv({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function gv(t){return typeof t.schema!="boolean"}function GO(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&_v(t),YO(t),XO(t);let s=n.const("_errs",te.default.errors);bv(t,s),n.var(e,(0,G._)`${s} === ${te.default.errors}`)}function yv(t){(0,Tr.checkUnknownRules)(t),WO(t)}function bv(t,e){if(t.opts.jtd)return dv(t,[],!1,e);let r=(0,lv.getSchemaTypes)(t.schema),n=(0,lv.coerceAndCheckDataType)(t,r);dv(t,r,!n,e)}function WO(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Tr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function JO(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Tr.checkStrictMode)(t,"default is ignored in the schema root")}function YO(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,ZO.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function XO(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function _v({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,G._)`${te.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,G.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,G._)`${te.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function QO(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,G._)`${te.default.errors} === 0`,()=>e.return(te.default.data),()=>e.throw((0,G._)`new ${o}(${te.default.vErrors})`)):(e.assign((0,G._)`${n}.errors`,te.default.vErrors),s.unevaluated&&eC(t),e.return((0,G._)`${te.default.errors} === 0`))}function eC({gen:t,evaluated:e,props:r,items:n}){r instanceof G.Name&&t.assign((0,G._)`${e}.props`,r),n instanceof G.Name&&t.assign((0,G._)`${e}.items`,n)}function dv(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Tr.schemaHasRulesButRef)(s,u))){o.block(()=>vv(t,"$ref",u.all.$ref.definition));return}c.jtd||tC(t,e),o.block(()=>{for(let y of u.rules)d(y);d(u.post)});function d(y){(0,jf.shouldUseGroup)(s,y)&&(y.type?(o.if((0,Wa.checkDataType)(y.type,i,c.strictNumbers)),pv(t,y),e.length===1&&e[0]===y.type&&r&&(o.else(),(0,Wa.reportTypeError)(t)),o.endIf()):pv(t,y),a||o.if((0,G._)`${te.default.errors} === ${n||0}`))}}function pv(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,UO.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,jf.shouldUseRule)(n,s)&&vv(t,s.keyword,s.definition,e.type)})}function tC(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(rC(t,e),t.opts.allowUnionTypes||nC(t,e),oC(t,t.dataTypes))}function rC(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{wv(t.dataTypes,r)||Lf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),iC(t,e)}}function nC(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Lf(t,"use allowUnionTypes to allow union type keyword")}function oC(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,jf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>sC(e,i))&&Lf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function sC(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function wv(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function iC(t,e){let r=[];for(let n of t.dataTypes)wv(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Lf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Tr.checkStrictMode)(t,e,t.opts.strictTypes)}var Ja=class{constructor(e,r,n){if((0,Ds.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Tr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",xv(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ds.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",te.default.errors))}result(e,r,n){this.failResult((0,G.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,G.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,G._)`${r} !== undefined && (${(0,G.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Ms.reportExtraError:Ms.reportError)(this,this.def.error,r)}$dataError(){(0,Ms.reportError)(this,this.def.$dataError||Ms.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ms.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=G.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=G.nil,r=G.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,G.or)((0,G._)`${o} === undefined`,r)),e!==G.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==G.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,G.or)(i(),a());function i(){if(n.length){if(!(r instanceof G.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,G._)`${(0,Wa.checkDataTypes)(c,r,s.opts.strictNumbers,Wa.DataType.Wrong)}`}return G.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,G._)`!${c}(${r})`}return G.nil}}subschema(e,r){let n=(0,Nf.getSubschema)(this.it,e);(0,Nf.extendSubschemaData)(n,this.it,e),(0,Nf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return KO(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Tr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Tr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,G.Name)),!0}};Jr.KeywordCxt=Ja;function vv(t,e,r,n){let o=new Ja(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ds.funcKeywordCode)(o,r):"macro"in r?(0,Ds.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ds.funcKeywordCode)(o,r)}var aC=/^\/(?:[^~]|~0|~1)*$/,cC=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function xv(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return te.default.rootData;if(t[0]==="/"){if(!aC.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=te.default.rootData}else{let l=cC.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=r[e-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,G._)`${s}${(0,G.getProperty)((0,Tr.unescapeJsonPointer)(l))}`,i=(0,G._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Jr.getData=xv});var Ya=U(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var Mf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Df.default=Mf});var Zs=U(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var Uf=Ls(),Zf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Uf.resolveUrl)(e,r,n),this.missingSchema=(0,Uf.normalizeId)((0,Uf.getFullPath)(e,this.missingRef))}};qf.default=Zf});var Qa=U(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.resolveSchema=qt.getCompilingSchema=qt.resolveRef=qt.compileSchema=qt.SchemaEnv=void 0;var Yt=ae(),lC=Ya(),Cn=Sr(),Xt=Ls(),$v=be(),uC=Us(),wo=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Xt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};qt.SchemaEnv=wo;function Bf(t){let e=kv.call(this,t);if(e)return e;let r=(0,Xt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Yt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:lC.default,code:(0,Yt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Cn.default.data,parentData:Cn.default.parentData,parentDataProperty:Cn.default.parentDataProperty,dataNames:[Cn.default.data],dataPathArr:[Yt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Yt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Yt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Yt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,uC.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(Cn.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let h=new Function(`${Cn.default.self}`,`${Cn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:g}=l;h.evaluated={props:f instanceof Yt.Name?void 0:f,items:g instanceof Yt.Name?void 0:g,dynamicProps:f instanceof Yt.Name,dynamicItems:g instanceof Yt.Name},h.source&&(h.source.evaluated=(0,Yt.stringify)(h.evaluated))}return t.validate=h,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}qt.compileSchema=Bf;function dC(t,e,r){var n;r=(0,Xt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=hC.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new wo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=pC.call(this,s)}qt.resolveRef=dC;function pC(t){return(0,Xt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Bf.call(this,t)}function kv(t){for(let e of this._compilations)if(fC(e,t))return e}qt.getCompilingSchema=kv;function fC(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function hC(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Xa.call(this,t,e)}function Xa(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Xt._getFullPath)(this.opts.uriResolver,r),o=(0,Xt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Ff.call(this,r,t);let s=(0,Xt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Xa.call(this,t,i);return typeof a?.schema!="object"?void 0:Ff.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Bf.call(this,i),s===(0,Xt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Xt.resolveUrl)(this.opts.uriResolver,o,l)),new wo({schema:a,schemaId:c,root:t,baseId:o})}return Ff.call(this,r,i)}}qt.resolveSchema=Xa;var mC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ff(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,$v.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!mC.has(a)&&l&&(e=(0,Xt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,$v.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Xt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Xa.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new wo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Sv=U((YF,gC)=>{gC.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Kf=U((XF,Iv)=>{"use strict";var yC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ev=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Vf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Rv=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),bC=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Hf(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var _C=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Tv(t){return t.length=0,!0}function wC(t,e,r){if(t.length){let n=Hf(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function vC(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=wC;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=Tv}else{o.push(l);continue}}return o.length&&(a===Tv?r.zone=o.join(""):i?n.push(o.join("")):n.push(Hf(o))),r.address=n.join(""),r}function Pv(t){if(xC(t,":")<2)return{host:t,isIPV6:!1};let e=vC(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function xC(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function $C(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var kC={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},SC=/[@/?#:]/g,TC=/[@/?#]/g;function Av(t,e){let r=e?TC:SC;return r.lastIndex=0,t.replace(r,n=>kC[n])}function EC(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Vf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Rv(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function RC(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Vf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Rv(s)?e+=s:e+="%"+o,r+=2;continue}}bC(t[r])?e+=t[r]:e+=escape(t[r])}return e}function PC(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Vf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function AC(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Ev(r)){let n=Pv(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Av(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Iv.exports={nonSimpleDomain:_C,recomposeAuthority:AC,reescapeHostDelimiters:Av,normalizePercentEncoding:EC,normalizePathEncoding:RC,escapePreservingEscapes:PC,removeDotSegments:$C,isIPv4:Ev,isUUID:yC,normalizeIPv6:Pv,stringArrayToHexStripped:Hf}});var jv=U((QF,Nv)=>{"use strict";var{isUUID:IC}=Kf(),OC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,CC=["http","https","ws","wss","urn","urn:uuid"];function zC(t){return CC.indexOf(t)!==-1}function Gf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Ov(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Cv(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function NC(t){return t.secure=Gf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function jC(t){if((t.port===(Gf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function LC(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(OC);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Wf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function MC(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Wf(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function DC(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!IC(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function UC(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var zv={scheme:"http",domainHost:!0,parse:Ov,serialize:Cv},ZC={scheme:"https",domainHost:zv.domainHost,parse:Ov,serialize:Cv},ec={scheme:"ws",domainHost:!0,parse:NC,serialize:jC},qC={scheme:"wss",domainHost:ec.domainHost,parse:ec.parse,serialize:ec.serialize},FC={scheme:"urn",parse:LC,serialize:MC,skipNormalize:!0},BC={scheme:"urn:uuid",parse:DC,serialize:UC,skipNormalize:!0},tc={http:zv,https:ZC,ws:ec,wss:qC,urn:FC,"urn:uuid":BC};Object.setPrototypeOf(tc,null);function Wf(t){return t&&(tc[t]||tc[t.toLowerCase()])||void 0}Nv.exports={wsIsSecure:Gf,SCHEMES:tc,isValidSchemeName:zC,getSchemeHandler:Wf}});var Zv=U((eB,oc)=>{"use strict";var{normalizeIPv6:VC,removeDotSegments:qs,recomposeAuthority:HC,normalizePercentEncoding:KC,normalizePathEncoding:GC,escapePreservingEscapes:WC,reescapeHostDelimiters:JC,isIPv4:YC,nonSimpleDomain:XC}=Kf(),{SCHEMES:QC,getSchemeHandler:Mv}=jv();function ez(t,e){return typeof t=="string"?t=az(t,e):typeof t=="object"&&(t=nc(zn(t,e),e)),t}function tz(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=rc(t,n),{parsed:i,malformedAuthorityOrPort:a}=rc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=Dv(o,i,n,!0);return n.skipEscape=!0,zn(c,n)}function Dv(t,e,r,n){let o={};return n||(t=nc(zn(t,r),r),e=nc(zn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=qs(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=qs(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=qs(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=qs(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function rz(t,e,r){let n=Lv(t,r),o=Lv(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function zn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=Mv(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=KC(r.path):(r.path=WC(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=HC(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=qs(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var nz=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,oz=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,sz=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function iz(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function rc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(oz);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(sz);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):l.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match(nz);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=iz(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(YC(n.host)===!1){let y=VC(n.host);n.host=y.host.toLowerCase(),s=y.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=Mv(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&XC(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(d){n.error=n.error||"Host's domain name can not be converted to ASCII: "+d}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=JC(unescape(n.host),s))),n.path&&(n.path=GC(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function nc(t,e){return rc(t,e).parsed}function az(t,e){return Uv(t,e).normalized}function Uv(t,e){let{parsed:r,malformedAuthorityOrPort:n}=rc(t,e);return{normalized:n?t:zn(r,e),malformedAuthorityOrPort:n}}function Lv(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Uv(t,e);return n?void 0:r}if(typeof t=="object")return zn(t,e)}var Jf={SCHEMES:QC,normalize:ez,resolve:tz,resolveComponent:Dv,equal:rz,serialize:zn,parse:nc};oc.exports=Jf;oc.exports.default=Jf;oc.exports.fastUri=Jf});var Fv=U(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var qv=Zv();qv.code='require("ajv/dist/runtime/uri").default';Yf.default=qv});var Yv=U(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.CodeGen=nt.Name=nt.nil=nt.stringify=nt.str=nt._=nt.KeywordCxt=void 0;var cz=Us();Object.defineProperty(nt,"KeywordCxt",{enumerable:!0,get:function(){return cz.KeywordCxt}});var vo=ae();Object.defineProperty(nt,"_",{enumerable:!0,get:function(){return vo._}});Object.defineProperty(nt,"str",{enumerable:!0,get:function(){return vo.str}});Object.defineProperty(nt,"stringify",{enumerable:!0,get:function(){return vo.stringify}});Object.defineProperty(nt,"nil",{enumerable:!0,get:function(){return vo.nil}});Object.defineProperty(nt,"Name",{enumerable:!0,get:function(){return vo.Name}});Object.defineProperty(nt,"CodeGen",{enumerable:!0,get:function(){return vo.CodeGen}});var lz=Ya(),Gv=Zs(),uz=Sf(),Fs=Qa(),dz=ae(),Bs=Ls(),sc=js(),Qf=be(),Bv=Sv(),pz=Fv(),Wv=(t,e)=>new RegExp(t,e);Wv.code="new RegExp";var fz=["removeAdditional","useDefaults","coerceTypes"],hz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),mz={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},gz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Vv=200;function yz(t){var e,r,n,o,s,i,a,c,l,u,d,y,h,f,g,w,E,R,C,B,W,He,Xe,St,Io;let Bt=t.strict,en=(e=t.code)===null||e===void 0?void 0:e.optimize,Mn=en===!0||en===void 0?1:en||0,Oo=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Wv,Co=(o=t.uriResolver)!==null&&o!==void 0?o:pz.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Bt)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Bt)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:Bt)!==null&&u!==void 0?u:"log",strictTuples:(y=(d=t.strictTuples)!==null&&d!==void 0?d:Bt)!==null&&y!==void 0?y:"log",strictRequired:(f=(h=t.strictRequired)!==null&&h!==void 0?h:Bt)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Mn,regExp:Oo}:{optimize:Mn,regExp:Oo},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Vv,loopEnum:(w=t.loopEnum)!==null&&w!==void 0?w:Vv,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(R=t.messages)!==null&&R!==void 0?R:!0,inlineRefs:(C=t.inlineRefs)!==null&&C!==void 0?C:!0,schemaId:(B=t.schemaId)!==null&&B!==void 0?B:"$id",addUsedSchema:(W=t.addUsedSchema)!==null&&W!==void 0?W:!0,validateSchema:(He=t.validateSchema)!==null&&He!==void 0?He:!0,validateFormats:(Xe=t.validateFormats)!==null&&Xe!==void 0?Xe:!0,unicodeRegExp:(St=t.unicodeRegExp)!==null&&St!==void 0?St:!0,int32range:(Io=t.int32range)!==null&&Io!==void 0?Io:!0,uriResolver:Co}}var Vs=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...yz(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new dz.ValueScope({scope:{},prefixes:hz,es5:r,lines:n}),this.logger=$z(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,uz.getRules)(),Hv.call(this,mz,e,"NOT SUPPORTED"),Hv.call(this,gz,e,"DEPRECATED","warn"),this._metaOpts=vz.call(this),e.formats&&_z.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&wz.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),bz.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Bv;n==="id"&&(o={...Bv},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(u,d){await s.call(this,u.$schema);let y=this._addSchema(u,d);return y.validate||i.call(this,y)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Gv.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Bs.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Kv.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Fs.SchemaEnv({schema:{},schemaId:n});if(r=Fs.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Kv.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Bs.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Sz.call(this,n,r),!r)return(0,Qf.eachItem)(n,s=>Xf.call(this,s)),this;Ez.call(this,r);let o={...r,type:(0,sc.getJSONTypes)(r.type),schemaType:(0,sc.getJSONTypes)(r.schemaType)};return(0,Qf.eachItem)(n,o.type.length===0?s=>Xf.call(this,s,o):s=>o.type.forEach(i=>Xf.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=i[a];l&&u&&(i[a]=Jv(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Bs.normalizeId)(i||n);let l=Bs.getSchemaRefs.call(this,e,n);return c=new Fs.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Fs.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Fs.compileSchema.call(this,e)}finally{this.opts=r}}};Vs.ValidationError=lz.default;Vs.MissingRefError=Gv.default;nt.default=Vs;function Hv(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Kv(t){return t=(0,Bs.normalizeId)(t),this.schemas[t]||this.refs[t]}function bz(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function _z(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function wz(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function vz(){let t={...this.opts};for(let e of fz)delete t[e];return t}var xz={log(){},warn(){},error(){}};function $z(t){if(t===!1)return xz;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var kz=/^[a-z_$][a-z0-9_$:-]*$/i;function Sz(t,e){let{RULES:r}=this;if((0,Qf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!kz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Xf(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,sc.getJSONTypes)(e.type),schemaType:(0,sc.getJSONTypes)(e.schemaType)}};e.before?Tz.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Tz(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Ez(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Jv(e)),t.validateSchema=this.compile(e,!0))}var Rz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Jv(t){return{anyOf:[t,Rz]}}});var Xv=U(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var Pz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};eh.default=Pz});var rx=U(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.callRef=Nn.getValidate=void 0;var Az=Zs(),Qv=Zt(),kt=ae(),xo=Sr(),ex=Qa(),ic=be(),Iz={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=ex.resolveRef.call(c,l,o,r);if(u===void 0)throw new Az.default(n.opts.uriResolver,o,r);if(u instanceof ex.SchemaEnv)return y(u);return h(u);function d(){if(s===l)return ac(t,i,s,s.$async);let f=e.scopeValue("root",{ref:l});return ac(t,(0,kt._)`${f}.validate`,l,l.$async)}function y(f){let g=tx(t,f);ac(t,g,f,f.$async)}function h(f){let g=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,kt.stringify)(f)}:{ref:f}),w=e.name("valid"),E=t.subschema({schema:f,dataTypes:[],schemaPath:kt.nil,topSchemaRef:g,errSchemaPath:r},w);t.mergeEvaluated(E),t.ok(w)}}};function tx(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,kt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Nn.getValidate=tx;function ac(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?xo.default.this:kt.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,kt._)`await ${(0,Qv.callValidateCode)(t,e,l)}`),h(e),i||o.assign(f,!0)},g=>{o.if((0,kt._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),y(g),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,Qv.callValidateCode)(t,e,l),()=>h(e),()=>y(e))}function y(f){let g=(0,kt._)`${f}.errors`;o.assign(xo.default.vErrors,(0,kt._)`${xo.default.vErrors} === null ? ${g} : ${xo.default.vErrors}.concat(${g})`),o.assign(xo.default.errors,(0,kt._)`${xo.default.vErrors}.length`)}function h(f){var g;if(!s.opts.unevaluated)return;let w=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(w&&!w.dynamicProps)w.props!==void 0&&(s.props=ic.mergeEvaluated.props(o,w.props,s.props));else{let E=o.var("props",(0,kt._)`${f}.evaluated.props`);s.props=ic.mergeEvaluated.props(o,E,s.props,kt.Name)}if(s.items!==!0)if(w&&!w.dynamicItems)w.items!==void 0&&(s.items=ic.mergeEvaluated.items(o,w.items,s.items));else{let E=o.var("items",(0,kt._)`${f}.evaluated.items`);s.items=ic.mergeEvaluated.items(o,E,s.items,kt.Name)}}}Nn.callRef=ac;Nn.default=Iz});var nx=U(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var Oz=Xv(),Cz=rx(),zz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Oz.default,Cz.default];th.default=zz});var ox=U(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var cc=ae(),Yr=cc.operators,lc={maximum:{okStr:"<=",ok:Yr.LTE,fail:Yr.GT},minimum:{okStr:">=",ok:Yr.GTE,fail:Yr.LT},exclusiveMaximum:{okStr:"<",ok:Yr.LT,fail:Yr.GTE},exclusiveMinimum:{okStr:">",ok:Yr.GT,fail:Yr.LTE}},Nz={message:({keyword:t,schemaCode:e})=>(0,cc.str)`must be ${lc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,cc._)`{comparison: ${lc[t].okStr}, limit: ${e}}`},jz={keyword:Object.keys(lc),type:"number",schemaType:"number",$data:!0,error:Nz,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,cc._)`${r} ${lc[e].fail} ${n} || isNaN(${r})`)}};rh.default=jz});var sx=U(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var Hs=ae(),Lz={message:({schemaCode:t})=>(0,Hs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Hs._)`{multipleOf: ${t}}`},Mz={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Lz,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Hs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Hs._)`${i} !== parseInt(${i})`;t.fail$data((0,Hs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};nh.default=Mz});var ax=U(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});function ix(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}oh.default=ix;ix.code='require("ajv/dist/runtime/ucs2length").default'});var cx=U(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var jn=ae(),Dz=be(),Uz=ax(),Zz={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,jn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,jn._)`{limit: ${t}}`},qz={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Zz,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?jn.operators.GT:jn.operators.LT,i=o.opts.unicode===!1?(0,jn._)`${r}.length`:(0,jn._)`${(0,Dz.useFunc)(t.gen,Uz.default)}(${r})`;t.fail$data((0,jn._)`${i} ${s} ${n}`)}};sh.default=qz});var lx=U(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var Fz=Zt(),Bz=be(),$o=ae(),Vz={message:({schemaCode:t})=>(0,$o.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,$o._)`{pattern: ${t}}`},Hz={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Vz,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,$o._)`new RegExp`:(0,Bz.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,$o._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,$o._)`!${u}`)}else{let c=(0,Fz.usePattern)(t,o);t.fail$data((0,$o._)`!${c}.test(${r})`)}}};ih.default=Hz});var ux=U(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var Ks=ae(),Kz={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ks.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ks._)`{limit: ${t}}`},Gz={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Kz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Ks.operators.GT:Ks.operators.LT;t.fail$data((0,Ks._)`Object.keys(${r}).length ${o} ${n}`)}};ah.default=Gz});var dx=U(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var Gs=Zt(),Ws=ae(),Wz=be(),Jz={message:({params:{missingProperty:t}})=>(0,Ws.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ws._)`{missingProperty: ${t}}`},Yz={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Jz,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:f}=t.it;for(let g of r)if(h?.[g]===void 0&&!f.has(g)){let w=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${g}" is not defined at "${w}" (strictRequired)`;(0,Wz.checkStrictMode)(i,E,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(Ws.nil,d);else for(let h of r)(0,Gs.checkReportMissingProp)(t,h)}function u(){let h=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>y(h,f)),t.ok(f)}else e.if((0,Gs.checkMissingProp)(t,r,h)),(0,Gs.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,Gs.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function y(h,f){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(f,(0,Gs.propertyInData)(e,o,h,a.ownProperties)),e.if((0,Ws.not)(f),()=>{t.error(),e.break()})},Ws.nil)}}};ch.default=Yz});var px=U(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var Js=ae(),Xz={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Js.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Js._)`{limit: ${t}}`},Qz={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Xz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Js.operators.GT:Js.operators.LT;t.fail$data((0,Js._)`${r}.length ${o} ${n}`)}};lh.default=Qz});var uc=U(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var fx=Cf();fx.code='require("ajv/dist/runtime/equal").default';uh.default=fx});var hx=U(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var dh=js(),ot=ae(),eN=be(),tN=uc(),rN={message:({params:{i:t,j:e}})=>(0,ot.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ot._)`{i: ${t}, j: ${e}}`},nN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:rN,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),l=s.items?(0,dh.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,ot._)`${i} === false`),t.ok(c);function u(){let f=e.let("i",(0,ot._)`${r}.length`),g=e.let("j");t.setParams({i:f,j:g}),e.assign(c,!0),e.if((0,ot._)`${f} > 1`,()=>(d()?y:h)(f,g))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function y(f,g){let w=e.name("item"),E=(0,dh.checkDataTypes)(l,w,a.opts.strictNumbers,dh.DataType.Wrong),R=e.const("indices",(0,ot._)`{}`);e.for((0,ot._)`;${f}--;`,()=>{e.let(w,(0,ot._)`${r}[${f}]`),e.if(E,(0,ot._)`continue`),l.length>1&&e.if((0,ot._)`typeof ${w} == "string"`,(0,ot._)`${w} += "_"`),e.if((0,ot._)`typeof ${R}[${w}] == "number"`,()=>{e.assign(g,(0,ot._)`${R}[${w}]`),t.error(),e.assign(c,!1).break()}).code((0,ot._)`${R}[${w}] = ${f}`)})}function h(f,g){let w=(0,eN.useFunc)(e,tN.default),E=e.name("outer");e.label(E).for((0,ot._)`;${f}--;`,()=>e.for((0,ot._)`${g} = ${f}; ${g}--;`,()=>e.if((0,ot._)`${w}(${r}[${f}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};ph.default=nN});var mx=U(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var fh=ae(),oN=be(),sN=uc(),iN={message:"must be equal to constant",params:({schemaCode:t})=>(0,fh._)`{allowedValue: ${t}}`},aN={keyword:"const",$data:!0,error:iN,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,fh._)`!${(0,oN.useFunc)(e,sN.default)}(${r}, ${o})`):t.fail((0,fh._)`${s} !== ${r}`)}};hh.default=aN});var gx=U(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var Ys=ae(),cN=be(),lN=uc(),uN={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ys._)`{allowedValues: ${t}}`},dN={keyword:"enum",schemaType:"array",$data:!0,error:uN,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,cN.useFunc)(e,lN.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let h=e.const("vSchema",s);u=(0,Ys.or)(...o.map((f,g)=>y(h,g)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,h=>e.if((0,Ys._)`${l()}(${r}, ${h})`,()=>e.assign(u,!0).break()))}function y(h,f){let g=o[f];return typeof g=="object"&&g!==null?(0,Ys._)`${l()}(${r}, ${h}[${f}])`:(0,Ys._)`${r} === ${g}`}}};mh.default=dN});var yx=U(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});var pN=ox(),fN=sx(),hN=cx(),mN=lx(),gN=ux(),yN=dx(),bN=px(),_N=hx(),wN=mx(),vN=gx(),xN=[pN.default,fN.default,hN.default,mN.default,gN.default,yN.default,bN.default,_N.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},wN.default,vN.default];gh.default=xN});var bh=U(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.validateAdditionalItems=void 0;var Ln=ae(),yh=be(),$N={message:({params:{len:t}})=>(0,Ln.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ln._)`{limit: ${t}}`},kN={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:$N,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,yh.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}bx(t,n)}};function bx(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Ln._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ln._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,yh.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Ln._)`${a} <= ${e.length}`);r.if((0,Ln.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:yh.Type.Num},l),i.allErrors||r.if((0,Ln.not)(l),()=>r.break())})}}Xs.validateAdditionalItems=bx;Xs.default=kN});var _h=U(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.validateTuple=void 0;var _x=ae(),dc=be(),SN=Zt(),TN={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return wx(t,"additionalItems",e);r.items=!0,!(0,dc.alwaysValidSchema)(r,e)&&t.ok((0,SN.validateArray)(t))}};function wx(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=dc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,_x._)`${s}.length`);r.forEach((d,y)=>{(0,dc.alwaysValidSchema)(a,d)||(n.if((0,_x._)`${l} > ${y}`,()=>t.subschema({keyword:i,schemaProp:y,dataProp:y},c)),t.ok(c))});function u(d){let{opts:y,errSchemaPath:h}=a,f=r.length,g=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(y.strictTuples&&!g){let w=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,dc.checkStrictMode)(a,w,y.strictTuples)}}}Qs.validateTuple=wx;Qs.default=TN});var vx=U(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});var EN=_h(),RN={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,EN.validateTuple)(t,"items")};wh.default=RN});var $x=U(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var xx=ae(),PN=be(),AN=Zt(),IN=bh(),ON={message:({params:{len:t}})=>(0,xx.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xx._)`{limit: ${t}}`},CN={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:ON,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,PN.alwaysValidSchema)(n,e)&&(o?(0,IN.validateAdditionalItems)(t,o):t.ok((0,AN.validateArray)(t)))}};vh.default=CN});var kx=U(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});var Ft=ae(),pc=be(),zN={message:({params:{min:t,max:e}})=>e===void 0?(0,Ft.str)`must contain at least ${t} valid item(s)`:(0,Ft.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ft._)`{minContains: ${t}}`:(0,Ft._)`{minContains: ${t}, maxContains: ${e}}`},NN={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:zN,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=e.const("len",(0,Ft._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,pc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,pc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,pc.alwaysValidSchema)(s,r)){let g=(0,Ft._)`${u} >= ${i}`;a!==void 0&&(g=(0,Ft._)`${g} && ${u} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?h(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Ft._)`${o}.length > 0`,y)):(e.let(d,!1),y()),t.result(d,()=>t.reset());function y(){let g=e.name("_valid"),w=e.let("count",0);h(g,()=>e.if(g,()=>f(w)))}function h(g,w){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:pc.Type.Num,compositeRule:!0},g),w()})}function f(g){e.code((0,Ft._)`${g}++`),a===void 0?e.if((0,Ft._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Ft._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Ft._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};xh.default=NN});var Ex=U(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.validateSchemaDeps=ur.validatePropertyDeps=ur.error=void 0;var $h=ae(),jN=be(),ei=Zt();ur.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,$h.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,$h._)`{property: ${t},
985
+ ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Np,Kt,tI,za=O(()=>{Vr();Kt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Np===void 0&&(Np=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Np),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};tI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Na(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===M.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:ee(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??qe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ee(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===M.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ca(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===M.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===M.ZodBranded&&t.keyType._def.type._def.typeName===M.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ia(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var ja=O(()=>{ts();Ge();za();Oa();Dt()});function a_(t,e){if(e.mapStrategy==="record")return Na(t,e);let r=ee(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||qe(e),n=ee(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||qe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Lp=O(()=>{Ge();ja();Dt()});function c_(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var Mp=O(()=>{});function l_(t){return t.target==="openAi"?void 0:{not:qe({...t,currentPath:[...t.currentPath,"not"]})}}var Dp=O(()=>{Dt()});function u_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Up=O(()=>{});function p_(t,e){if(e.target==="openApi3")return d_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Es&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Es[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return d_(t,e)}var Es,d_,La=O(()=>{Ge();Es={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};d_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ee(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function f_(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Es[t.innerType._def.typeName],nullable:!0}:{type:[Es[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ee(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ee(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Zp=O(()=>{Ge();La()});function h_(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",$p(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?be(r,"minimum",n.value,n.message,e):be(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),be(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?be(r,"maximum",n.value,n.message,e):be(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),be(r,"maximum",n.value,n.message,e));break;case"multipleOf":be(r,"multipleOf",n.value,n.message,e);break}return r}var qp=O(()=>{Vr()});function m_(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let l=oI(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ee(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,l||o.push(a))}o.length&&(n.required=o);let i=nI(t,e);return i!==void 0&&(n.additionalProperties=i),n}function nI(t,e){if(t.catchall._def.typeName!=="ZodNever")return ee(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function oI(t){try{return t.isOptional()}catch{return!0}}var Fp=O(()=>{Ge()});var g_,Bp=O(()=>{Ge();Dt();g_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ee(t.innerType._def,e);let r=ee(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:qe(e)},r]}:qe(e)}});var y_,Vp=O(()=>{Ge();y_=(t,e)=>{if(e.pipeStrategy==="input")return ee(t.in._def,e);if(e.pipeStrategy==="output")return ee(t.out._def,e);let r=ee(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ee(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function b_(t,e){return ee(t.type._def,e)}var Hp=O(()=>{Ge()});function w_(t,e){let n={type:"array",uniqueItems:!0,items:ee(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&be(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&be(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Kp=O(()=>{Vr();Ge()});function __(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ee(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ee(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ee(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Gp=O(()=>{Ge()});function v_(t){return{not:qe(t)}}var Wp=O(()=>{Dt()});function x_(t){return qe(t)}var Jp=O(()=>{Dt()});var $_,Yp=O(()=>{Ge();$_=(t,e)=>ee(t.innerType._def,e)});var k_,Xp=O(()=>{ts();Dt();kp();Sp();Tp();Oa();Ep();Pp();Ap();Ip();Op();Cp();zp();Lp();Mp();Dp();Up();Zp();qp();Fp();Bp();Vp();Hp();ja();Kp();za();Gp();Wp();La();Jp();Yp();k_=(t,e,r)=>{switch(e){case M.ZodString:return Ca(t,r);case M.ZodNumber:return h_(t,r);case M.ZodObject:return m_(t,r);case M.ZodBigInt:return Xw(t,r);case M.ZodBoolean:return Qw();case M.ZodDate:return Rp(t,r);case M.ZodUndefined:return v_(r);case M.ZodNull:return u_(r);case M.ZodArray:return Yw(t,r);case M.ZodUnion:case M.ZodDiscriminatedUnion:return p_(t,r);case M.ZodIntersection:return o_(t,r);case M.ZodTuple:return __(t,r);case M.ZodRecord:return Na(t,r);case M.ZodLiteral:return s_(t,r);case M.ZodEnum:return n_(t);case M.ZodNativeEnum:return c_(t);case M.ZodNullable:return f_(t,r);case M.ZodOptional:return g_(t,r);case M.ZodMap:return a_(t,r);case M.ZodSet:return w_(t,r);case M.ZodLazy:return()=>t.getter()._def;case M.ZodPromise:return b_(t,r);case M.ZodNaN:case M.ZodNever:return l_(r);case M.ZodEffects:return r_(t,r);case M.ZodAny:return qe(r);case M.ZodUnknown:return x_(r);case M.ZodDefault:return t_(t,r);case M.ZodBranded:return Ia(t,r);case M.ZodReadonly:return $_(t,r);case M.ZodCatch:return e_(t,r);case M.ZodPipeline:return y_(t,r);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(n=>{})(e)}}});function ee(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Gw)return a}if(n&&!r){let a=sI(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=k_(t,t.typeName,e),i=typeof s=="function"?ee(s(),e):s;if(i&&iI(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var sI,iI,Ge=O(()=>{Ra();Xp();Aa();Dt();sI=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Pa(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),qe(e)):e.$refStrategy==="seen"?qe(e):void 0}},iI=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var S_=O(()=>{});var Qp,ef=O(()=>{Ge();xp();Dt();Qp=(t,e)=>{let r=Jw(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ee(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??qe(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ee(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??qe(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var T_=O(()=>{Ra();xp();Vr();Aa();Ge();S_();Dt();kp();Sp();Tp();Oa();Ep();Pp();Ap();Ip();Op();Cp();zp();Lp();Mp();Dp();Up();Zp();qp();Fp();Bp();Vp();Hp();Yp();ja();Kp();za();Gp();Wp();La();Jp();Xp();ef();ef()});function aI(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function tf(t,e){return ar(t)?qd(t,{target:aI(e?.target),io:e?.pipeStrategy??"input"}):Qp(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function rf(t){let r=qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=co(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function nf(t,e){let r=Zr(t,e);if(!r.success)throw r.error;return r.data}var of=O(()=>{Vd();hs();T_()});function E_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function R_(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];E_(i)&&E_(s)?r[o]={...i,...s}:r[o]=s}return r}var cI,Ma,P_=O(()=>{hs();mo();Hw();of();cI=6e4,Ma=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(da,r=>{this._oncancel(r)}),this.setNotificationHandler(fa,r=>{this._onprogress(r)}),this.setRequestHandler(pa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ha,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new K(Y.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ga,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,b=new K(d.error.code,d.error.message,d.error.data);u(b)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new K(Y.InvalidParams,`Task not found: ${s}`);if(!Br(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Br(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Fr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ya,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new K(Y.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(wa,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new K(Y.InvalidParams,`Task not found: ${r.params.taskId}`);if(Br(o.status))throw new K(Y.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new K(Y.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof K?o:new K(Y.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),K.fromError(Y.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),bs(s)||Nw(s)?this._onresponse(s):cp(s)?this._onrequest(s,i):zw(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=K.fromError(Y.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Fr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:Y.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Iw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(u,d)},sendRequest:async(u,d,b)=>{if(i.signal.aborted)throw new K(Y.ConnectionClosed,"Request was cancelled");let h={...b,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let f=h.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(u,d,h)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Y.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),bs(e))n(e);else{let i=new K(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(bs(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),bs(e))o(e);else{let i=K.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof K?i:new K(Y.InternalError,String(i))}}return}let s;try{let i=await this.request(e,uo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new K(Y.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Br(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new K(Y.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new K(Y.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof K?i:new K(Y.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=R=>{u(R)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(R){d(R);return}n?.signal?.throwIfAborted();let b=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:b}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Fr]:c}});let f=R=>{this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(R)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`)));let z=R instanceof K?R:new K(Y.RequestTimeout,String(R));u(z)};this._responseHandlers.set(b,R=>{if(!n?.signal?.aborted){if(R instanceof Error)return u(R);try{let z=Zr(r,R.result);z.success?l(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let y=n?.timeout??cI,v=()=>f(K.fromError(Y.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(b,y,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let R=z=>{let V=this._responseHandlers.get(b);V?V(z):this._onerror(new Error(`Response handler missing for side-channeled request ${b}`))};this._requestResolvers.set(b,R),this._enqueueTaskMessage(E,{type:"request",message:h,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(b),u(z)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(R=>{this._cleanupTimeout(b),u(R)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ma,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ba,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Mw,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Fr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Fr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Fr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=rf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=nf(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=rf(e);this._notificationHandlers.set(n,o=>{let s=nf(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&cp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new K(Y.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new K(Y.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new K(Y.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new K(Y.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=$s.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Br(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new K(Y.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Br(a.status))throw new K(Y.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=$s.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Br(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var As=Z(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.regexpCode=ke.getEsmExportName=ke.getProperty=ke.safeStringify=ke.stringify=ke.strConcat=ke.addCodeArg=ke.str=ke._=ke.nil=ke._Code=ke.Name=ke.IDENTIFIER=ke._CodeOrName=void 0;var Rs=class{};ke._CodeOrName=Rs;ke.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Rn=class extends Rs{constructor(e){if(super(),!ke.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ke.Name=Rn;var Ut=class extends Rs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Rn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ke._Code=Ut;ke.nil=new Ut("");function A_(t,...e){let r=[t[0]],n=0;for(;n<e.length;)af(r,e[n]),r.push(t[++n]);return new Ut(r)}ke._=A_;var sf=new Ut("+");function I_(t,...e){let r=[Ps(t[0])],n=0;for(;n<e.length;)r.push(sf),af(r,e[n]),r.push(sf,Ps(t[++n]));return lI(r),new Ut(r)}ke.str=I_;function af(t,e){e instanceof Ut?t.push(...e._items):e instanceof Rn?t.push(e):t.push(pI(e))}ke.addCodeArg=af;function lI(t){let e=1;for(;e<t.length-1;){if(t[e]===sf){let r=uI(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function uI(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Rn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Rn))return`"${t}${e.slice(1)}`}function dI(t,e){return e.emptyStr()?t:t.emptyStr()?e:I_`${t}${e}`}ke.strConcat=dI;function pI(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ps(Array.isArray(t)?t.join(","):t)}function fI(t){return new Ut(Ps(t))}ke.stringify=fI;function Ps(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ke.safeStringify=Ps;function hI(t){return typeof t=="string"&&ke.IDENTIFIER.test(t)?new Ut(`.${t}`):A_`[${t}]`}ke.getProperty=hI;function mI(t){if(typeof t=="string"&&ke.IDENTIFIER.test(t))return new Ut(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ke.getEsmExportName=mI;function gI(t){return new Ut(t.toString())}ke.regexpCode=gI});var uf=Z(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.ValueScope=xt.ValueScopeName=xt.Scope=xt.varKinds=xt.UsedValueState=void 0;var vt=As(),cf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Da;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Da||(xt.UsedValueState=Da={}));xt.varKinds={const:new vt.Name("const"),let:new vt.Name("let"),var:new vt.Name("var")};var Ua=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof vt.Name?e:this.name(e)}name(e){return new vt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};xt.Scope=Ua;var Za=class extends vt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,vt._)`.${new vt.Name(r)}[${n}]`}};xt.ValueScopeName=Za;var yI=(0,vt._)`\n`,lf=class extends Ua{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?yI:vt.nil}}get(){return this._scope}name(e){return new Za(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,itemIndex:l}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,vt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=vt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Da.Started);let u=r(l);if(u){let d=this.opts.es5?xt.varKinds.var:xt.varKinds.const;s=(0,vt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,vt._)`${s}${u}${this.opts._n}`;else throw new cf(l);c.set(l,Da.Completed)})}return s}};xt.ValueScope=lf});var le=Z(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.or=ue.and=ue.not=ue.CodeGen=ue.operators=ue.varKinds=ue.ValueScopeName=ue.ValueScope=ue.Scope=ue.Name=ue.regexpCode=ue.stringify=ue.getProperty=ue.nil=ue.strConcat=ue.str=ue._=void 0;var we=As(),Wt=uf(),Hr=As();Object.defineProperty(ue,"_",{enumerable:!0,get:function(){return Hr._}});Object.defineProperty(ue,"str",{enumerable:!0,get:function(){return Hr.str}});Object.defineProperty(ue,"strConcat",{enumerable:!0,get:function(){return Hr.strConcat}});Object.defineProperty(ue,"nil",{enumerable:!0,get:function(){return Hr.nil}});Object.defineProperty(ue,"getProperty",{enumerable:!0,get:function(){return Hr.getProperty}});Object.defineProperty(ue,"stringify",{enumerable:!0,get:function(){return Hr.stringify}});Object.defineProperty(ue,"regexpCode",{enumerable:!0,get:function(){return Hr.regexpCode}});Object.defineProperty(ue,"Name",{enumerable:!0,get:function(){return Hr.Name}});var Va=uf();Object.defineProperty(ue,"Scope",{enumerable:!0,get:function(){return Va.Scope}});Object.defineProperty(ue,"ValueScope",{enumerable:!0,get:function(){return Va.ValueScope}});Object.defineProperty(ue,"ValueScopeName",{enumerable:!0,get:function(){return Va.ValueScopeName}});Object.defineProperty(ue,"varKinds",{enumerable:!0,get:function(){return Va.varKinds}});ue.operators={GT:new we._Code(">"),GTE:new we._Code(">="),LT:new we._Code("<"),LTE:new we._Code("<="),EQ:new we._Code("==="),NEQ:new we._Code("!=="),NOT:new we._Code("!"),OR:new we._Code("||"),AND:new we._Code("&&"),ADD:new we._Code("+")};var kr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},df=class extends kr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Wt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=yo(this.rhs,e,r)),this}get names(){return this.rhs instanceof we._CodeOrName?this.rhs.names:{}}},qa=class extends kr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof we.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=yo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof we.Name?{}:{...this.lhs.names};return Ba(e,this.rhs)}},pf=class extends qa{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ff=class extends kr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},hf=class extends kr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},mf=class extends kr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},gf=class extends kr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=yo(this.code,e,r),this}get names(){return this.code instanceof we._CodeOrName?this.code.names:{}}},Is=class extends kr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(bI(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>In(e,r.names),{})}},Sr=class extends Is{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},yf=class extends Is{},go=class extends Sr{};go.kind="else";var Pn=class t extends Sr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new go(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(O_(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=yo(this.condition,e,r),this}get names(){let e=super.names;return Ba(e,this.condition),this.else&&In(e,this.else.names),e}};Pn.kind="if";var An=class extends Sr{};An.kind="for";var bf=class extends An{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=yo(this.iteration,e,r),this}get names(){return In(super.names,this.iteration.names)}},wf=class extends An{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Wt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ba(super.names,this.from);return Ba(e,this.to)}},Fa=class extends An{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=yo(this.iterable,e,r),this}get names(){return In(super.names,this.iterable.names)}},Os=class extends Sr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Os.kind="func";var Cs=class extends Is{render(e){return"return "+super.render(e)}};Cs.kind="return";var _f=class extends Sr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&In(e,this.catch.names),this.finally&&In(e,this.finally.names),e}},zs=class extends Sr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};zs.kind="catch";var Ns=class extends Sr{render(e){return"finally"+super.render(e)}};Ns.kind="finally";var vf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
986
+ `:""},this._extScope=e,this._scope=new Wt.Scope({parent:e}),this._nodes=[new yf]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new df(e,s,n)),s}const(e,r,n){return this._def(Wt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Wt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Wt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new qa(e,r,n))}add(e,r){return this._leafNode(new pf(e,ue.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==we.nil&&this._leafNode(new gf(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,we.addCodeArg)(r,o));return r.push("}"),new we._Code(r)}if(e,r,n){if(this._blockNode(new Pn(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Pn(e))}else(){return this._elseNode(new go)}endIf(){return this._endBlockNode(Pn,go)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new bf(e),r)}forRange(e,r,n,o,s=this.opts.es5?Wt.varKinds.var:Wt.varKinds.let){let i=this._scope.toName(e);return this._for(new wf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Wt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof we.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,we._)`${i}.length`,a=>{this.var(s,(0,we._)`${i}[${a}]`),n(s)})}return this._for(new Fa("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Wt.varKinds.var:Wt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,we._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Fa("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(An)}label(e){return this._leafNode(new ff(e))}break(e){return this._leafNode(new hf(e))}return(e){let r=new Cs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Cs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new _f;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new zs(s),r(s)}return n&&(this._currNode=o.finally=new Ns,this.code(n)),this._endBlockNode(zs,Ns)}throw(e){return this._leafNode(new mf(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=we.nil,n,o){return this._blockNode(new Os(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Os)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Pn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};ue.CodeGen=vf;function In(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ba(t,e){return e instanceof we._CodeOrName?In(t,e.names):t}function yo(t,e,r){if(t instanceof we.Name)return n(t);if(!o(t))return t;return new we._Code(t._items.reduce((s,i)=>(i instanceof we.Name&&(i=n(i)),i instanceof we._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof we._Code&&s._items.some(i=>i instanceof we.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function bI(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function O_(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,we._)`!${xf(t)}`}ue.not=O_;var wI=C_(ue.operators.AND);function _I(...t){return t.reduce(wI)}ue.and=_I;var vI=C_(ue.operators.OR);function xI(...t){return t.reduce(vI)}ue.or=xI;function C_(t){return(e,r)=>e===we.nil?r:r===we.nil?e:(0,we._)`${xf(e)} ${t} ${xf(r)}`}function xf(t){return t instanceof we.Name?t:(0,we._)`(${t})`}});var ve=Z(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.checkStrictMode=pe.getErrorPath=pe.Type=pe.useFunc=pe.setEvaluated=pe.evaluatedPropsToName=pe.mergeEvaluated=pe.eachItem=pe.unescapeJsonPointer=pe.escapeJsonPointer=pe.escapeFragment=pe.unescapeFragment=pe.schemaRefOrVal=pe.schemaHasRulesButRef=pe.schemaHasRules=pe.checkUnknownRules=pe.alwaysValidSchema=pe.toHash=void 0;var Ie=le(),$I=As();function kI(t){let e={};for(let r of t)e[r]=!0;return e}pe.toHash=kI;function SI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(j_(t,e),!L_(e,t.self.RULES.all))}pe.alwaysValidSchema=SI;function j_(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||U_(t,`unknown keyword: "${s}"`)}pe.checkUnknownRules=j_;function L_(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}pe.schemaHasRules=L_;function TI(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}pe.schemaHasRulesButRef=TI;function EI({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ie._)`${r}`}return(0,Ie._)`${t}${e}${(0,Ie.getProperty)(n)}`}pe.schemaRefOrVal=EI;function RI(t){return M_(decodeURIComponent(t))}pe.unescapeFragment=RI;function PI(t){return encodeURIComponent(kf(t))}pe.escapeFragment=PI;function kf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}pe.escapeJsonPointer=kf;function M_(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}pe.unescapeJsonPointer=M_;function AI(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}pe.eachItem=AI;function z_({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ie.Name?(s instanceof Ie.Name?t(o,s,i):e(o,s,i),i):s instanceof Ie.Name?(e(o,i,s),s):r(s,i);return a===Ie.Name&&!(c instanceof Ie.Name)?n(o,c):c}}pe.mergeEvaluated={props:z_({mergeNames:(t,e,r)=>t.if((0,Ie._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ie._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ie._)`${r} || {}`).code((0,Ie._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ie._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ie._)`${r} || {}`),Sf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:D_}),items:z_({mergeNames:(t,e,r)=>t.if((0,Ie._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ie._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ie._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ie._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function D_(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ie._)`{}`);return e!==void 0&&Sf(t,r,e),r}pe.evaluatedPropsToName=D_;function Sf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ie._)`${e}${(0,Ie.getProperty)(n)}`,!0))}pe.setEvaluated=Sf;var N_={};function II(t,e){return t.scopeValue("func",{ref:e,code:N_[e.code]||(N_[e.code]=new $I._Code(e.code))})}pe.useFunc=II;var $f;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})($f||(pe.Type=$f={}));function OI(t,e,r){if(t instanceof Ie.Name){let n=e===$f.Num;return r?n?(0,Ie._)`"[" + ${t} + "]"`:(0,Ie._)`"['" + ${t} + "']"`:n?(0,Ie._)`"/" + ${t}`:(0,Ie._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ie.getProperty)(t).toString():"/"+kf(t)}pe.getErrorPath=OI;function U_(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}pe.checkStrictMode=U_});var Tr=Z(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var it=le(),CI={data:new it.Name("data"),valCxt:new it.Name("valCxt"),instancePath:new it.Name("instancePath"),parentData:new it.Name("parentData"),parentDataProperty:new it.Name("parentDataProperty"),rootData:new it.Name("rootData"),dynamicAnchors:new it.Name("dynamicAnchors"),vErrors:new it.Name("vErrors"),errors:new it.Name("errors"),this:new it.Name("this"),self:new it.Name("self"),scope:new it.Name("scope"),json:new it.Name("json"),jsonPos:new it.Name("jsonPos"),jsonLen:new it.Name("jsonLen"),jsonPart:new it.Name("jsonPart")};Tf.default=CI});var js=Z(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.extendErrors=at.resetErrorsCount=at.reportExtraError=at.reportError=at.keyword$DataError=at.keywordError=void 0;var xe=le(),Ha=ve(),ft=Tr();at.keywordError={message:({keyword:t})=>(0,xe.str)`must pass "${t}" keyword validation`};at.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,xe.str)`"${t}" keyword must be ${e} ($data)`:(0,xe.str)`"${t}" keyword is invalid ($data)`};function zI(t,e=at.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=F_(t,e,r);n??(i||a)?Z_(s,c):q_(o,(0,xe._)`[${c}]`)}at.reportError=zI;function NI(t,e=at.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=F_(t,e,r);Z_(o,a),s||i||q_(n,ft.default.vErrors)}at.reportExtraError=NI;function jI(t,e){t.assign(ft.default.errors,e),t.if((0,xe._)`${ft.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,xe._)`${ft.default.vErrors}.length`,e),()=>t.assign(ft.default.vErrors,null)))}at.resetErrorsCount=jI;function LI({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,ft.default.errors,a=>{t.const(i,(0,xe._)`${ft.default.vErrors}[${a}]`),t.if((0,xe._)`${i}.instancePath === undefined`,()=>t.assign((0,xe._)`${i}.instancePath`,(0,xe.strConcat)(ft.default.instancePath,s.errorPath))),t.assign((0,xe._)`${i}.schemaPath`,(0,xe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,xe._)`${i}.schema`,r),t.assign((0,xe._)`${i}.data`,n))})}at.extendErrors=LI;function Z_(t,e){let r=t.const("err",e);t.if((0,xe._)`${ft.default.vErrors} === null`,()=>t.assign(ft.default.vErrors,(0,xe._)`[${r}]`),(0,xe._)`${ft.default.vErrors}.push(${r})`),t.code((0,xe._)`${ft.default.errors}++`)}function q_(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,xe._)`new ${t.ValidationError}(${e})`):(r.assign((0,xe._)`${n}.errors`,e),r.return(!1))}var On={keyword:new xe.Name("keyword"),schemaPath:new xe.Name("schemaPath"),params:new xe.Name("params"),propertyName:new xe.Name("propertyName"),message:new xe.Name("message"),schema:new xe.Name("schema"),parentSchema:new xe.Name("parentSchema")};function F_(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,xe._)`{}`:MI(t,e,r)}function MI(t,e,r={}){let{gen:n,it:o}=t,s=[DI(o,r),UI(t,r)];return ZI(t,e,s),n.object(...s)}function DI({errorPath:t},{instancePath:e}){let r=e?(0,xe.str)`${t}${(0,Ha.getErrorPath)(e,Ha.Type.Str)}`:t;return[ft.default.instancePath,(0,xe.strConcat)(ft.default.instancePath,r)]}function UI({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,xe.str)`${e}/${t}`;return r&&(o=(0,xe.str)`${o}${(0,Ha.getErrorPath)(r,Ha.Type.Str)}`),[On.schemaPath,o]}function ZI(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([On.keyword,o],[On.params,typeof e=="function"?e(t):e||(0,xe._)`{}`]),c.messages&&n.push([On.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([On.schema,i],[On.parentSchema,(0,xe._)`${u}${d}`],[ft.default.data,s]),l&&n.push([On.propertyName,l])}});var V_=Z(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.boolOrEmptySchema=bo.topBoolOrEmptySchema=void 0;var qI=js(),FI=le(),BI=Tr(),VI={message:"boolean schema is false"};function HI(t){let{gen:e,schema:r,validateName:n}=t;r===!1?B_(t,!1):typeof r=="object"&&r.$async===!0?e.return(BI.default.data):(e.assign((0,FI._)`${n}.errors`,null),e.return(!0))}bo.topBoolOrEmptySchema=HI;function KI(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),B_(t)):r.var(e,!0)}bo.boolOrEmptySchema=KI;function B_(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,qI.reportError)(o,VI,void 0,e)}});var Ef=Z(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.getRules=wo.isJSONType=void 0;var GI=["string","number","integer","boolean","null","object","array"],WI=new Set(GI);function JI(t){return typeof t=="string"&&WI.has(t)}wo.isJSONType=JI;function YI(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}wo.getRules=YI});var Rf=Z(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.shouldUseRule=Kr.shouldUseGroup=Kr.schemaHasRulesForType=void 0;function XI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&H_(t,n)}Kr.schemaHasRulesForType=XI;function H_(t,e){return e.rules.some(r=>K_(t,r))}Kr.shouldUseGroup=H_;function K_(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Kr.shouldUseRule=K_});var Ls=Z(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.reportTypeError=ct.checkDataTypes=ct.checkDataType=ct.coerceAndCheckDataType=ct.getJSONTypes=ct.getSchemaTypes=ct.DataType=void 0;var QI=Ef(),eO=Rf(),tO=js(),ae=le(),G_=ve(),_o;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(_o||(ct.DataType=_o={}));function rO(t){let e=W_(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ct.getSchemaTypes=rO;function W_(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(QI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ct.getJSONTypes=W_;function nO(t,e){let{gen:r,data:n,opts:o}=t,s=oO(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,eO.schemaHasRulesForType)(t,e[0]));if(i){let a=Af(e,n,o.strictNumbers,_o.Wrong);r.if(a,()=>{s.length?sO(t,e,s):If(t)})}return i}ct.coerceAndCheckDataType=nO;var J_=new Set(["string","number","integer","boolean","null"]);function oO(t,e){return e?t.filter(r=>J_.has(r)||e==="array"&&r==="array"):[]}function sO(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,ae._)`typeof ${o}`),a=n.let("coerced",(0,ae._)`undefined`);s.coerceTypes==="array"&&n.if((0,ae._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,ae._)`${o}[0]`).assign(i,(0,ae._)`typeof ${o}`).if(Af(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ae._)`${a} !== undefined`);for(let l of r)(J_.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),If(t),n.endIf(),n.if((0,ae._)`${a} !== undefined`,()=>{n.assign(o,a),iO(t,a)});function c(l){switch(l){case"string":n.elseIf((0,ae._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ae._)`"" + ${o}`).elseIf((0,ae._)`${o} === null`).assign(a,(0,ae._)`""`);return;case"number":n.elseIf((0,ae._)`${i} == "boolean" || ${o} === null
987
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ae._)`+${o}`);return;case"integer":n.elseIf((0,ae._)`${i} === "boolean" || ${o} === null
988
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ae._)`+${o}`);return;case"boolean":n.elseIf((0,ae._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ae._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ae._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ae._)`${i} === "string" || ${i} === "number"
989
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,ae._)`[${o}]`)}}}function iO({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ae._)`${e} !== undefined`,()=>t.assign((0,ae._)`${e}[${r}]`,n))}function Pf(t,e,r,n=_o.Correct){let o=n===_o.Correct?ae.operators.EQ:ae.operators.NEQ,s;switch(t){case"null":return(0,ae._)`${e} ${o} null`;case"array":s=(0,ae._)`Array.isArray(${e})`;break;case"object":s=(0,ae._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ae._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ae._)`typeof ${e} ${o} ${t}`}return n===_o.Correct?s:(0,ae.not)(s);function i(a=ae.nil){return(0,ae.and)((0,ae._)`typeof ${e} == "number"`,a,r?(0,ae._)`isFinite(${e})`:ae.nil)}}ct.checkDataType=Pf;function Af(t,e,r,n){if(t.length===1)return Pf(t[0],e,r,n);let o,s=(0,G_.toHash)(t);if(s.array&&s.object){let i=(0,ae._)`typeof ${e} != "object"`;o=s.null?i:(0,ae._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ae.nil;s.number&&delete s.integer;for(let i in s)o=(0,ae.and)(o,Pf(i,e,r,n));return o}ct.checkDataTypes=Af;var aO={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ae._)`{type: ${t}}`:(0,ae._)`{type: ${e}}`};function If(t){let e=cO(t);(0,tO.reportError)(e,aO)}ct.reportTypeError=If;function cO(t){let{gen:e,data:r,schema:n}=t,o=(0,G_.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var X_=Z(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.assignDefaults=void 0;var vo=le(),lO=ve();function uO(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Y_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Y_(t,s,o.default))}Ka.assignDefaults=uO;function Y_(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,vo._)`${s}${(0,vo.getProperty)(e)}`;if(o){(0,lO.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,vo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,vo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,vo._)`${a} = ${(0,vo.stringify)(r)}`)}});var Zt=Z(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.validateUnion=Pe.validateArray=Pe.usePattern=Pe.callValidateCode=Pe.schemaProperties=Pe.allSchemaProperties=Pe.noPropertyInData=Pe.propertyInData=Pe.isOwnProperty=Pe.hasPropFunc=Pe.reportMissingProp=Pe.checkMissingProp=Pe.checkReportMissingProp=void 0;var je=le(),Of=ve(),Gr=Tr(),dO=ve();function pO(t,e){let{gen:r,data:n,it:o}=t;r.if(zf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,je._)`${e}`},!0),t.error()})}Pe.checkReportMissingProp=pO;function fO({gen:t,data:e,it:{opts:r}},n,o){return(0,je.or)(...n.map(s=>(0,je.and)(zf(t,e,s,r.ownProperties),(0,je._)`${o} = ${s}`)))}Pe.checkMissingProp=fO;function hO(t,e){t.setParams({missingProperty:e},!0),t.error()}Pe.reportMissingProp=hO;function Q_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,je._)`Object.prototype.hasOwnProperty`})}Pe.hasPropFunc=Q_;function Cf(t,e,r){return(0,je._)`${Q_(t)}.call(${e}, ${r})`}Pe.isOwnProperty=Cf;function mO(t,e,r,n){let o=(0,je._)`${e}${(0,je.getProperty)(r)} !== undefined`;return n?(0,je._)`${o} && ${Cf(t,e,r)}`:o}Pe.propertyInData=mO;function zf(t,e,r,n){let o=(0,je._)`${e}${(0,je.getProperty)(r)} === undefined`;return n?(0,je.or)(o,(0,je.not)(Cf(t,e,r))):o}Pe.noPropertyInData=zf;function ev(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Pe.allSchemaProperties=ev;function gO(t,e){return ev(e).filter(r=>!(0,Of.alwaysValidSchema)(t,e[r]))}Pe.schemaProperties=gO;function yO({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,je._)`${t}, ${e}, ${n}${o}`:e,d=[[Gr.default.instancePath,(0,je.strConcat)(Gr.default.instancePath,s)],[Gr.default.parentData,i.parentData],[Gr.default.parentDataProperty,i.parentDataProperty],[Gr.default.rootData,Gr.default.rootData]];i.opts.dynamicRef&&d.push([Gr.default.dynamicAnchors,Gr.default.dynamicAnchors]);let b=(0,je._)`${u}, ${r.object(...d)}`;return c!==je.nil?(0,je._)`${a}.call(${c}, ${b})`:(0,je._)`${a}(${b})`}Pe.callValidateCode=yO;var bO=(0,je._)`new RegExp`;function wO({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,je._)`${o.code==="new RegExp"?bO:(0,dO.useFunc)(t,o)}(${r}, ${n})`})}Pe.usePattern=wO;function _O(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,je._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:Of.Type.Num},s),e.if((0,je.not)(s),a)})}}Pe.validateArray=_O;function vO(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Of.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(i,(0,je._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,je.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Pe.validateUnion=vO});var nv=Z(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.validateKeywordUsage=cr.validSchemaType=cr.funcKeywordCode=cr.macroKeywordCode=void 0;var ht=le(),Cn=Tr(),xO=Zt(),$O=js();function kO(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=rv(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:ht.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}cr.macroKeywordCode=kO;function SO(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;EO(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=rv(n,o,l),d=n.let("valid");t.block$data(d,b),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function b(){if(e.errors===!1)y(),e.modifying&&tv(t),v(()=>t.error());else{let E=e.async?h():f();e.modifying&&tv(t),v(()=>TO(t,E))}}function h(){let E=n.let("ruleErrs",null);return n.try(()=>y((0,ht._)`await `),R=>n.assign(d,!1).if((0,ht._)`${R} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,ht._)`${R}.errors`),()=>n.throw(R))),E}function f(){let E=(0,ht._)`${u}.errors`;return n.assign(E,null),y(ht.nil),E}function y(E=e.async?(0,ht._)`await `:ht.nil){let R=c.opts.passContext?Cn.default.this:Cn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ht._)`${E}${(0,xO.callValidateCode)(t,u,R,z)}`,e.modifying)}function v(E){var R;n.if((0,ht.not)((R=e.valid)!==null&&R!==void 0?R:d),E)}}cr.funcKeywordCode=SO;function tv(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function TO(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(Cn.default.vErrors,(0,ht._)`${Cn.default.vErrors} === null ? ${e} : ${Cn.default.vErrors}.concat(${e})`).assign(Cn.default.errors,(0,ht._)`${Cn.default.vErrors}.length`),(0,$O.extendErrors)(t)},()=>t.error())}function EO({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function rv(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,ht.stringify)(r)})}function RO(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}cr.validSchemaType=RO;function PO({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}cr.validateKeywordUsage=PO});var sv=Z(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.extendSubschemaMode=Wr.extendSubschemaData=Wr.getSubschema=void 0;var lr=le(),ov=ve();function AO(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,lr._)`${t.schemaPath}${(0,lr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,lr._)`${t.schemaPath}${(0,lr.getProperty)(e)}${(0,lr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,ov.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Wr.getSubschema=AO;function IO(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,b=a.let("data",(0,lr._)`${e.data}${(0,lr.getProperty)(r)}`,!0);c(b),t.errorPath=(0,lr.str)`${l}${(0,ov.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,lr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof lr.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Wr.extendSubschemaData=IO;function OO(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Wr.extendSubschemaMode=OO});var Nf=Z((G4,iv)=>{"use strict";iv.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var cv=Z((W4,av)=>{"use strict";var Jr=av.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Ga(e,n,o,t,"",t)};Jr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Jr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Jr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Jr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Ga(t,e,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in Jr.arrayKeywords)for(var b=0;b<d.length;b++)Ga(t,e,r,d[b],o+"/"+u+"/"+b,s,o,u,n,b)}else if(u in Jr.propsKeywords){if(d&&typeof d=="object")for(var h in d)Ga(t,e,r,d[h],o+"/"+u+"/"+CO(h),s,o,u,n,h)}else(u in Jr.keywords||t.allKeys&&!(u in Jr.skipKeywords))&&Ga(t,e,r,d,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function CO(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ms=Z($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getSchemaRefs=$t.resolveUrl=$t.normalizeId=$t._getFullPath=$t.getFullPath=$t.inlineRef=void 0;var zO=ve(),NO=Nf(),jO=cv(),LO=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function MO(t,e=!0){return typeof t=="boolean"?!0:e===!0?!jf(t):e?lv(t)<=e:!1}$t.inlineRef=MO;var DO=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function jf(t){for(let e in t){if(DO.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(jf)||typeof r=="object"&&jf(r))return!0}return!1}function lv(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!LO.has(r)&&(typeof t[r]=="object"&&(0,zO.eachItem)(t[r],n=>e+=lv(n)),e===1/0))return 1/0}return e}function uv(t,e="",r){r!==!1&&(e=xo(e));let n=t.parse(e);return dv(t,n)}$t.getFullPath=uv;function dv(t,e){return t.serialize(e).split("#")[0]+"#"}$t._getFullPath=dv;var UO=/#\/?$/;function xo(t){return t?t.replace(UO,""):""}$t.normalizeId=xo;function ZO(t,e,r){return r=xo(r),t.resolve(e,r)}$t.resolveUrl=ZO;var qO=/^[a-z_][-a-z0-9._]*$/i;function FO(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=xo(t[r]||e),s={"":o},i=uv(n,o,!1),a={},c=new Set;return jO(t,{allKeys:!0},(d,b,h,f)=>{if(f===void 0)return;let y=i+b,v=s[f];typeof d[r]=="string"&&(v=E.call(this,d[r])),R.call(this,d.$anchor),R.call(this,d.$dynamicAnchor),s[b]=v;function E(z){let V=this.opts.uriResolver.resolve;if(z=xo(v?V(v,z):z),c.has(z))throw u(z);c.add(z);let J=this.refs[z];return typeof J=="string"&&(J=this.refs[J]),typeof J=="object"?l(d,J.schema,z):z!==xo(y)&&(z[0]==="#"?(l(d,a[z],z),a[z]=d):this.refs[z]=y),z}function R(z){if(typeof z=="string"){if(!qO.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function l(d,b,h){if(b!==void 0&&!NO(d,b))throw u(h)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}$t.getSchemaRefs=FO});var Zs=Z(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.getData=Yr.KeywordCxt=Yr.validateFunctionCode=void 0;var gv=V_(),pv=Ls(),Mf=Rf(),Wa=Ls(),BO=X_(),Us=nv(),Lf=sv(),W=le(),re=Tr(),VO=Ms(),Er=ve(),Ds=js();function HO(t){if(wv(t)&&(_v(t),bv(t))){WO(t);return}yv(t,()=>(0,gv.topBoolOrEmptySchema)(t))}Yr.validateFunctionCode=HO;function yv({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,W._)`${re.default.data}, ${re.default.valCxt}`,n.$async,()=>{t.code((0,W._)`"use strict"; ${fv(r,o)}`),GO(t,o),t.code(s)}):t.func(e,(0,W._)`${re.default.data}, ${KO(o)}`,n.$async,()=>t.code(fv(r,o)).code(s))}function KO(t){return(0,W._)`{${re.default.instancePath}="", ${re.default.parentData}, ${re.default.parentDataProperty}, ${re.default.rootData}=${re.default.data}${t.dynamicRef?(0,W._)`, ${re.default.dynamicAnchors}={}`:W.nil}}={}`}function GO(t,e){t.if(re.default.valCxt,()=>{t.var(re.default.instancePath,(0,W._)`${re.default.valCxt}.${re.default.instancePath}`),t.var(re.default.parentData,(0,W._)`${re.default.valCxt}.${re.default.parentData}`),t.var(re.default.parentDataProperty,(0,W._)`${re.default.valCxt}.${re.default.parentDataProperty}`),t.var(re.default.rootData,(0,W._)`${re.default.valCxt}.${re.default.rootData}`),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,W._)`${re.default.valCxt}.${re.default.dynamicAnchors}`)},()=>{t.var(re.default.instancePath,(0,W._)`""`),t.var(re.default.parentData,(0,W._)`undefined`),t.var(re.default.parentDataProperty,(0,W._)`undefined`),t.var(re.default.rootData,re.default.data),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,W._)`{}`)})}function WO(t){let{schema:e,opts:r,gen:n}=t;yv(t,()=>{r.$comment&&e.$comment&&xv(t),eC(t),n.let(re.default.vErrors,null),n.let(re.default.errors,0),r.unevaluated&&JO(t),vv(t),nC(t)})}function JO(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,W._)`${r}.evaluated`),e.if((0,W._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,W._)`${t.evaluated}.props`,(0,W._)`undefined`)),e.if((0,W._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,W._)`${t.evaluated}.items`,(0,W._)`undefined`))}function fv(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,W._)`/*# sourceURL=${r} */`:W.nil}function YO(t,e){if(wv(t)&&(_v(t),bv(t))){XO(t,e);return}(0,gv.boolOrEmptySchema)(t,e)}function bv({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function wv(t){return typeof t.schema!="boolean"}function XO(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&xv(t),tC(t),rC(t);let s=n.const("_errs",re.default.errors);vv(t,s),n.var(e,(0,W._)`${s} === ${re.default.errors}`)}function _v(t){(0,Er.checkUnknownRules)(t),QO(t)}function vv(t,e){if(t.opts.jtd)return hv(t,[],!1,e);let r=(0,pv.getSchemaTypes)(t.schema),n=(0,pv.coerceAndCheckDataType)(t,r);hv(t,r,!n,e)}function QO(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Er.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function eC(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Er.checkStrictMode)(t,"default is ignored in the schema root")}function tC(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,VO.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function rC(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function xv({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,W._)`${re.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,W.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,W._)`${re.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function nC(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,W._)`${re.default.errors} === 0`,()=>e.return(re.default.data),()=>e.throw((0,W._)`new ${o}(${re.default.vErrors})`)):(e.assign((0,W._)`${n}.errors`,re.default.vErrors),s.unevaluated&&oC(t),e.return((0,W._)`${re.default.errors} === 0`))}function oC({gen:t,evaluated:e,props:r,items:n}){r instanceof W.Name&&t.assign((0,W._)`${e}.props`,r),n instanceof W.Name&&t.assign((0,W._)`${e}.items`,n)}function hv(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Er.schemaHasRulesButRef)(s,u))){o.block(()=>kv(t,"$ref",u.all.$ref.definition));return}c.jtd||sC(t,e),o.block(()=>{for(let b of u.rules)d(b);d(u.post)});function d(b){(0,Mf.shouldUseGroup)(s,b)&&(b.type?(o.if((0,Wa.checkDataType)(b.type,i,c.strictNumbers)),mv(t,b),e.length===1&&e[0]===b.type&&r&&(o.else(),(0,Wa.reportTypeError)(t)),o.endIf()):mv(t,b),a||o.if((0,W._)`${re.default.errors} === ${n||0}`))}}function mv(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,BO.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Mf.shouldUseRule)(n,s)&&kv(t,s.keyword,s.definition,e.type)})}function sC(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(iC(t,e),t.opts.allowUnionTypes||aC(t,e),cC(t,t.dataTypes))}function iC(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{$v(t.dataTypes,r)||Df(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),uC(t,e)}}function aC(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Df(t,"use allowUnionTypes to allow union type keyword")}function cC(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Mf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>lC(e,i))&&Df(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function lC(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function $v(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function uC(t,e){let r=[];for(let n of t.dataTypes)$v(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Df(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Er.checkStrictMode)(t,e,t.opts.strictTypes)}var Ja=class{constructor(e,r,n){if((0,Us.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Er.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Sv(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Us.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",re.default.errors))}result(e,r,n){this.failResult((0,W.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,W.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,W._)`${r} !== undefined && (${(0,W.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Ds.reportExtraError:Ds.reportError)(this,this.def.error,r)}$dataError(){(0,Ds.reportError)(this,this.def.$dataError||Ds.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ds.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=W.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=W.nil,r=W.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,W.or)((0,W._)`${o} === undefined`,r)),e!==W.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==W.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,W.or)(i(),a());function i(){if(n.length){if(!(r instanceof W.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,W._)`${(0,Wa.checkDataTypes)(c,r,s.opts.strictNumbers,Wa.DataType.Wrong)}`}return W.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,W._)`!${c}(${r})`}return W.nil}}subschema(e,r){let n=(0,Lf.getSubschema)(this.it,e);(0,Lf.extendSubschemaData)(n,this.it,e),(0,Lf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return YO(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Er.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Er.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,W.Name)),!0}};Yr.KeywordCxt=Ja;function kv(t,e,r,n){let o=new Ja(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Us.funcKeywordCode)(o,r):"macro"in r?(0,Us.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Us.funcKeywordCode)(o,r)}var dC=/^\/(?:[^~]|~0|~1)*$/,pC=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Sv(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return re.default.rootData;if(t[0]==="/"){if(!dC.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=re.default.rootData}else{let l=pC.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=r[e-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,W._)`${s}${(0,W.getProperty)((0,Er.unescapeJsonPointer)(l))}`,i=(0,W._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Yr.getData=Sv});var Ya=Z(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var Uf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Zf.default=Uf});var qs=Z(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var qf=Ms(),Ff=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,qf.resolveUrl)(e,r,n),this.missingSchema=(0,qf.normalizeId)((0,qf.getFullPath)(e,this.missingRef))}};Bf.default=Ff});var Qa=Z(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.resolveSchema=qt.getCompilingSchema=qt.resolveRef=qt.compileSchema=qt.SchemaEnv=void 0;var Jt=le(),fC=Ya(),zn=Tr(),Yt=Ms(),Tv=ve(),hC=Zs(),$o=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Yt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};qt.SchemaEnv=$o;function Hf(t){let e=Ev.call(this,t);if(e)return e;let r=(0,Yt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Jt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:fC.default,code:(0,Jt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:zn.default.data,parentData:zn.default.parentData,parentDataProperty:zn.default.parentDataProperty,dataNames:[zn.default.data],dataPathArr:[Jt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Jt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Jt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Jt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,hC.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(zn.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let h=new Function(`${zn.default.self}`,`${zn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:y}=l;h.evaluated={props:f instanceof Jt.Name?void 0:f,items:y instanceof Jt.Name?void 0:y,dynamicProps:f instanceof Jt.Name,dynamicItems:y instanceof Jt.Name},h.source&&(h.source.evaluated=(0,Jt.stringify)(h.evaluated))}return t.validate=h,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}qt.compileSchema=Hf;function mC(t,e,r){var n;r=(0,Yt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=bC.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new $o({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=gC.call(this,s)}qt.resolveRef=mC;function gC(t){return(0,Yt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Hf.call(this,t)}function Ev(t){for(let e of this._compilations)if(yC(e,t))return e}qt.getCompilingSchema=Ev;function yC(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function bC(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Xa.call(this,t,e)}function Xa(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Yt._getFullPath)(this.opts.uriResolver,r),o=(0,Yt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Vf.call(this,r,t);let s=(0,Yt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Xa.call(this,t,i);return typeof a?.schema!="object"?void 0:Vf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Hf.call(this,i),s===(0,Yt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Yt.resolveUrl)(this.opts.uriResolver,o,l)),new $o({schema:a,schemaId:c,root:t,baseId:o})}return Vf.call(this,r,i)}}qt.resolveSchema=Xa;var wC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Vf(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Tv.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!wC.has(a)&&l&&(e=(0,Yt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Tv.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Yt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Xa.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new $o({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Rv=Z((tB,_C)=>{_C.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Wf=Z((rB,zv)=>{"use strict";var vC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Av=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Kf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Iv=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),xC=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Gf(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var $C=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Pv(t){return t.length=0,!0}function kC(t,e,r){if(t.length){let n=Gf(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function SC(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=kC;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=Pv}else{o.push(l);continue}}return o.length&&(a===Pv?r.zone=o.join(""):i?n.push(o.join("")):n.push(Gf(o))),r.address=n.join(""),r}function Ov(t){if(TC(t,":")<2)return{host:t,isIPV6:!1};let e=SC(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function TC(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function EC(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var RC={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},PC=/[@/?#:]/g,AC=/[@/?#]/g;function Cv(t,e){let r=e?AC:PC;return r.lastIndex=0,t.replace(r,n=>RC[n])}function IC(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Kf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Iv(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function OC(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Kf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Iv(s)?e+=s:e+="%"+o,r+=2;continue}}xC(t[r])?e+=t[r]:e+=escape(t[r])}return e}function CC(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Kf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function zC(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Av(r)){let n=Ov(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Cv(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}zv.exports={nonSimpleDomain:$C,recomposeAuthority:zC,reescapeHostDelimiters:Cv,normalizePercentEncoding:IC,normalizePathEncoding:OC,escapePreservingEscapes:CC,removeDotSegments:EC,isIPv4:Av,isUUID:vC,normalizeIPv6:Ov,stringArrayToHexStripped:Gf}});var Dv=Z((nB,Mv)=>{"use strict";var{isUUID:NC}=Wf(),jC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,LC=["http","https","ws","wss","urn","urn:uuid"];function MC(t){return LC.indexOf(t)!==-1}function Jf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Nv(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function jv(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function DC(t){return t.secure=Jf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function UC(t){if((t.port===(Jf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function ZC(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(jC);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Yf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function qC(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Yf(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function FC(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!NC(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function BC(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Lv={scheme:"http",domainHost:!0,parse:Nv,serialize:jv},VC={scheme:"https",domainHost:Lv.domainHost,parse:Nv,serialize:jv},ec={scheme:"ws",domainHost:!0,parse:DC,serialize:UC},HC={scheme:"wss",domainHost:ec.domainHost,parse:ec.parse,serialize:ec.serialize},KC={scheme:"urn",parse:ZC,serialize:qC,skipNormalize:!0},GC={scheme:"urn:uuid",parse:FC,serialize:BC,skipNormalize:!0},tc={http:Lv,https:VC,ws:ec,wss:HC,urn:KC,"urn:uuid":GC};Object.setPrototypeOf(tc,null);function Yf(t){return t&&(tc[t]||tc[t.toLowerCase()])||void 0}Mv.exports={wsIsSecure:Jf,SCHEMES:tc,isValidSchemeName:MC,getSchemeHandler:Yf}});var Bv=Z((oB,oc)=>{"use strict";var{normalizeIPv6:WC,removeDotSegments:Fs,recomposeAuthority:JC,normalizePercentEncoding:YC,normalizePathEncoding:XC,escapePreservingEscapes:QC,reescapeHostDelimiters:ez,isIPv4:tz,nonSimpleDomain:rz}=Wf(),{SCHEMES:nz,getSchemeHandler:Zv}=Dv();function oz(t,e){return typeof t=="string"?t=dz(t,e):typeof t=="object"&&(t=nc(Nn(t,e),e)),t}function sz(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=rc(t,n),{parsed:i,malformedAuthorityOrPort:a}=rc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=qv(o,i,n,!0);return n.skipEscape=!0,Nn(c,n)}function qv(t,e,r,n){let o={};return n||(t=nc(Nn(t,r),r),e=nc(Nn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Fs(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Fs(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Fs(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Fs(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function iz(t,e,r){let n=Uv(t,r),o=Uv(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Nn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=Zv(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=YC(r.path):(r.path=QC(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=JC(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Fs(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var az=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,cz=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,lz=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function uz(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function rc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(cz);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(lz);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):l.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match(az);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=uz(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(tz(n.host)===!1){let b=WC(n.host);n.host=b.host.toLowerCase(),s=b.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=Zv(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&rz(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(d){n.error=n.error||"Host's domain name can not be converted to ASCII: "+d}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=ez(unescape(n.host),s))),n.path&&(n.path=XC(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function nc(t,e){return rc(t,e).parsed}function dz(t,e){return Fv(t,e).normalized}function Fv(t,e){let{parsed:r,malformedAuthorityOrPort:n}=rc(t,e);return{normalized:n?t:Nn(r,e),malformedAuthorityOrPort:n}}function Uv(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Fv(t,e);return n?void 0:r}if(typeof t=="object")return Nn(t,e)}var Xf={SCHEMES:nz,normalize:oz,resolve:sz,resolveComponent:qv,equal:iz,serialize:Nn,parse:nc};oc.exports=Xf;oc.exports.default=Xf;oc.exports.fastUri=Xf});var Hv=Z(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var Vv=Bv();Vv.code='require("ajv/dist/runtime/uri").default';Qf.default=Vv});var ex=Z(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.CodeGen=nt.Name=nt.nil=nt.stringify=nt.str=nt._=nt.KeywordCxt=void 0;var pz=Zs();Object.defineProperty(nt,"KeywordCxt",{enumerable:!0,get:function(){return pz.KeywordCxt}});var ko=le();Object.defineProperty(nt,"_",{enumerable:!0,get:function(){return ko._}});Object.defineProperty(nt,"str",{enumerable:!0,get:function(){return ko.str}});Object.defineProperty(nt,"stringify",{enumerable:!0,get:function(){return ko.stringify}});Object.defineProperty(nt,"nil",{enumerable:!0,get:function(){return ko.nil}});Object.defineProperty(nt,"Name",{enumerable:!0,get:function(){return ko.Name}});Object.defineProperty(nt,"CodeGen",{enumerable:!0,get:function(){return ko.CodeGen}});var fz=Ya(),Yv=qs(),hz=Ef(),Bs=Qa(),mz=le(),Vs=Ms(),sc=Ls(),th=ve(),Kv=Rv(),gz=Hv(),Xv=(t,e)=>new RegExp(t,e);Xv.code="new RegExp";var yz=["removeAdditional","useDefaults","coerceTypes"],bz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),wz={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},_z={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Gv=200;function vz(t){var e,r,n,o,s,i,a,c,l,u,d,b,h,f,y,v,E,R,z,V,J,He,Xe,Rr,er;let tn=t.strict,fr=(e=t.code)===null||e===void 0?void 0:e.optimize,Dn=fr===!0||fr===void 0?1:fr||0,Un=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Xv,si=(o=t.uriResolver)!==null&&o!==void 0?o:gz.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:tn)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:tn)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:tn)!==null&&u!==void 0?u:"log",strictTuples:(b=(d=t.strictTuples)!==null&&d!==void 0?d:tn)!==null&&b!==void 0?b:"log",strictRequired:(f=(h=t.strictRequired)!==null&&h!==void 0?h:tn)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Dn,regExp:Un}:{optimize:Dn,regExp:Un},loopRequired:(y=t.loopRequired)!==null&&y!==void 0?y:Gv,loopEnum:(v=t.loopEnum)!==null&&v!==void 0?v:Gv,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(R=t.messages)!==null&&R!==void 0?R:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(V=t.schemaId)!==null&&V!==void 0?V:"$id",addUsedSchema:(J=t.addUsedSchema)!==null&&J!==void 0?J:!0,validateSchema:(He=t.validateSchema)!==null&&He!==void 0?He:!0,validateFormats:(Xe=t.validateFormats)!==null&&Xe!==void 0?Xe:!0,unicodeRegExp:(Rr=t.unicodeRegExp)!==null&&Rr!==void 0?Rr:!0,int32range:(er=t.int32range)!==null&&er!==void 0?er:!0,uriResolver:si}}var Hs=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...vz(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new mz.ValueScope({scope:{},prefixes:bz,es5:r,lines:n}),this.logger=Ez(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,hz.getRules)(),Wv.call(this,wz,e,"NOT SUPPORTED"),Wv.call(this,_z,e,"DEPRECATED","warn"),this._metaOpts=Sz.call(this),e.formats&&$z.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&kz.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),xz.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Kv;n==="id"&&(o={...Kv},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(u,d){await s.call(this,u.$schema);let b=this._addSchema(u,d);return b.validate||i.call(this,b)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Yv.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Vs.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Jv.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Bs.SchemaEnv({schema:{},schemaId:n});if(r=Bs.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Jv.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Vs.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Pz.call(this,n,r),!r)return(0,th.eachItem)(n,s=>eh.call(this,s)),this;Iz.call(this,r);let o={...r,type:(0,sc.getJSONTypes)(r.type),schemaType:(0,sc.getJSONTypes)(r.schemaType)};return(0,th.eachItem)(n,o.type.length===0?s=>eh.call(this,s,o):s=>o.type.forEach(i=>eh.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=i[a];l&&u&&(i[a]=Qv(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Vs.normalizeId)(i||n);let l=Vs.getSchemaRefs.call(this,e,n);return c=new Bs.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Bs.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Bs.compileSchema.call(this,e)}finally{this.opts=r}}};Hs.ValidationError=fz.default;Hs.MissingRefError=Yv.default;nt.default=Hs;function Wv(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Jv(t){return t=(0,Vs.normalizeId)(t),this.schemas[t]||this.refs[t]}function xz(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function $z(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function kz(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function Sz(){let t={...this.opts};for(let e of yz)delete t[e];return t}var Tz={log(){},warn(){},error(){}};function Ez(t){if(t===!1)return Tz;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Rz=/^[a-z_$][a-z0-9_$:-]*$/i;function Pz(t,e){let{RULES:r}=this;if((0,th.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Rz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function eh(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,sc.getJSONTypes)(e.type),schemaType:(0,sc.getJSONTypes)(e.schemaType)}};e.before?Az.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Az(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Iz(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Qv(e)),t.validateSchema=this.compile(e,!0))}var Oz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Qv(t){return{anyOf:[t,Oz]}}});var tx=Z(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var Cz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};rh.default=Cz});var sx=Z(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.callRef=jn.getValidate=void 0;var zz=qs(),rx=Zt(),kt=le(),So=Tr(),nx=Qa(),ic=ve(),Nz={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=nx.resolveRef.call(c,l,o,r);if(u===void 0)throw new zz.default(n.opts.uriResolver,o,r);if(u instanceof nx.SchemaEnv)return b(u);return h(u);function d(){if(s===l)return ac(t,i,s,s.$async);let f=e.scopeValue("root",{ref:l});return ac(t,(0,kt._)`${f}.validate`,l,l.$async)}function b(f){let y=ox(t,f);ac(t,y,f,f.$async)}function h(f){let y=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,kt.stringify)(f)}:{ref:f}),v=e.name("valid"),E=t.subschema({schema:f,dataTypes:[],schemaPath:kt.nil,topSchemaRef:y,errSchemaPath:r},v);t.mergeEvaluated(E),t.ok(v)}}};function ox(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,kt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}jn.getValidate=ox;function ac(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?So.default.this:kt.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,kt._)`await ${(0,rx.callValidateCode)(t,e,l)}`),h(e),i||o.assign(f,!0)},y=>{o.if((0,kt._)`!(${y} instanceof ${s.ValidationError})`,()=>o.throw(y)),b(y),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,rx.callValidateCode)(t,e,l),()=>h(e),()=>b(e))}function b(f){let y=(0,kt._)`${f}.errors`;o.assign(So.default.vErrors,(0,kt._)`${So.default.vErrors} === null ? ${y} : ${So.default.vErrors}.concat(${y})`),o.assign(So.default.errors,(0,kt._)`${So.default.vErrors}.length`)}function h(f){var y;if(!s.opts.unevaluated)return;let v=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(s.props=ic.mergeEvaluated.props(o,v.props,s.props));else{let E=o.var("props",(0,kt._)`${f}.evaluated.props`);s.props=ic.mergeEvaluated.props(o,E,s.props,kt.Name)}if(s.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(s.items=ic.mergeEvaluated.items(o,v.items,s.items));else{let E=o.var("items",(0,kt._)`${f}.evaluated.items`);s.items=ic.mergeEvaluated.items(o,E,s.items,kt.Name)}}}jn.callRef=ac;jn.default=Nz});var ix=Z(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var jz=tx(),Lz=sx(),Mz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",jz.default,Lz.default];nh.default=Mz});var ax=Z(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var cc=le(),Xr=cc.operators,lc={maximum:{okStr:"<=",ok:Xr.LTE,fail:Xr.GT},minimum:{okStr:">=",ok:Xr.GTE,fail:Xr.LT},exclusiveMaximum:{okStr:"<",ok:Xr.LT,fail:Xr.GTE},exclusiveMinimum:{okStr:">",ok:Xr.GT,fail:Xr.LTE}},Dz={message:({keyword:t,schemaCode:e})=>(0,cc.str)`must be ${lc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,cc._)`{comparison: ${lc[t].okStr}, limit: ${e}}`},Uz={keyword:Object.keys(lc),type:"number",schemaType:"number",$data:!0,error:Dz,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,cc._)`${r} ${lc[e].fail} ${n} || isNaN(${r})`)}};oh.default=Uz});var cx=Z(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var Ks=le(),Zz={message:({schemaCode:t})=>(0,Ks.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ks._)`{multipleOf: ${t}}`},qz={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Zz,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ks._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ks._)`${i} !== parseInt(${i})`;t.fail$data((0,Ks._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};sh.default=qz});var ux=Z(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});function lx(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}ih.default=lx;lx.code='require("ajv/dist/runtime/ucs2length").default'});var dx=Z(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var Ln=le(),Fz=ve(),Bz=ux(),Vz={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Ln.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Ln._)`{limit: ${t}}`},Hz={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Vz,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Ln.operators.GT:Ln.operators.LT,i=o.opts.unicode===!1?(0,Ln._)`${r}.length`:(0,Ln._)`${(0,Fz.useFunc)(t.gen,Bz.default)}(${r})`;t.fail$data((0,Ln._)`${i} ${s} ${n}`)}};ah.default=Hz});var px=Z(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var Kz=Zt(),Gz=ve(),To=le(),Wz={message:({schemaCode:t})=>(0,To.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,To._)`{pattern: ${t}}`},Jz={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Wz,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,To._)`new RegExp`:(0,Gz.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,To._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,To._)`!${u}`)}else{let c=(0,Kz.usePattern)(t,o);t.fail$data((0,To._)`!${c}.test(${r})`)}}};ch.default=Jz});var fx=Z(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var Gs=le(),Yz={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Gs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Gs._)`{limit: ${t}}`},Xz={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Yz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Gs.operators.GT:Gs.operators.LT;t.fail$data((0,Gs._)`Object.keys(${r}).length ${o} ${n}`)}};lh.default=Xz});var hx=Z(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var Ws=Zt(),Js=le(),Qz=ve(),eN={message:({params:{missingProperty:t}})=>(0,Js.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Js._)`{missingProperty: ${t}}`},tN={keyword:"required",type:"object",schemaType:"array",$data:!0,error:eN,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:f}=t.it;for(let y of r)if(h?.[y]===void 0&&!f.has(y)){let v=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${y}" is not defined at "${v}" (strictRequired)`;(0,Qz.checkStrictMode)(i,E,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(Js.nil,d);else for(let h of r)(0,Ws.checkReportMissingProp)(t,h)}function u(){let h=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>b(h,f)),t.ok(f)}else e.if((0,Ws.checkMissingProp)(t,r,h)),(0,Ws.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,Ws.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function b(h,f){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(f,(0,Ws.propertyInData)(e,o,h,a.ownProperties)),e.if((0,Js.not)(f),()=>{t.error(),e.break()})},Js.nil)}}};uh.default=tN});var mx=Z(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var Ys=le(),rN={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ys.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ys._)`{limit: ${t}}`},nN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:rN,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ys.operators.GT:Ys.operators.LT;t.fail$data((0,Ys._)`${r}.length ${o} ${n}`)}};dh.default=nN});var uc=Z(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var gx=Nf();gx.code='require("ajv/dist/runtime/equal").default';ph.default=gx});var yx=Z(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var fh=Ls(),ot=le(),oN=ve(),sN=uc(),iN={message:({params:{i:t,j:e}})=>(0,ot.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ot._)`{i: ${t}, j: ${e}}`},aN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:iN,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),l=s.items?(0,fh.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,ot._)`${i} === false`),t.ok(c);function u(){let f=e.let("i",(0,ot._)`${r}.length`),y=e.let("j");t.setParams({i:f,j:y}),e.assign(c,!0),e.if((0,ot._)`${f} > 1`,()=>(d()?b:h)(f,y))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function b(f,y){let v=e.name("item"),E=(0,fh.checkDataTypes)(l,v,a.opts.strictNumbers,fh.DataType.Wrong),R=e.const("indices",(0,ot._)`{}`);e.for((0,ot._)`;${f}--;`,()=>{e.let(v,(0,ot._)`${r}[${f}]`),e.if(E,(0,ot._)`continue`),l.length>1&&e.if((0,ot._)`typeof ${v} == "string"`,(0,ot._)`${v} += "_"`),e.if((0,ot._)`typeof ${R}[${v}] == "number"`,()=>{e.assign(y,(0,ot._)`${R}[${v}]`),t.error(),e.assign(c,!1).break()}).code((0,ot._)`${R}[${v}] = ${f}`)})}function h(f,y){let v=(0,oN.useFunc)(e,sN.default),E=e.name("outer");e.label(E).for((0,ot._)`;${f}--;`,()=>e.for((0,ot._)`${y} = ${f}; ${y}--;`,()=>e.if((0,ot._)`${v}(${r}[${f}], ${r}[${y}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};hh.default=aN});var bx=Z(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});var mh=le(),cN=ve(),lN=uc(),uN={message:"must be equal to constant",params:({schemaCode:t})=>(0,mh._)`{allowedValue: ${t}}`},dN={keyword:"const",$data:!0,error:uN,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,mh._)`!${(0,cN.useFunc)(e,lN.default)}(${r}, ${o})`):t.fail((0,mh._)`${s} !== ${r}`)}};gh.default=dN});var wx=Z(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});var Xs=le(),pN=ve(),fN=uc(),hN={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Xs._)`{allowedValues: ${t}}`},mN={keyword:"enum",schemaType:"array",$data:!0,error:hN,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,pN.useFunc)(e,fN.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let h=e.const("vSchema",s);u=(0,Xs.or)(...o.map((f,y)=>b(h,y)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,h=>e.if((0,Xs._)`${l()}(${r}, ${h})`,()=>e.assign(u,!0).break()))}function b(h,f){let y=o[f];return typeof y=="object"&&y!==null?(0,Xs._)`${l()}(${r}, ${h}[${f}])`:(0,Xs._)`${r} === ${y}`}}};yh.default=mN});var _x=Z(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var gN=ax(),yN=cx(),bN=dx(),wN=px(),_N=fx(),vN=hx(),xN=mx(),$N=yx(),kN=bx(),SN=wx(),TN=[gN.default,yN.default,bN.default,wN.default,_N.default,vN.default,xN.default,$N.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},kN.default,SN.default];bh.default=TN});var _h=Z(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.validateAdditionalItems=void 0;var Mn=le(),wh=ve(),EN={message:({params:{len:t}})=>(0,Mn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Mn._)`{limit: ${t}}`},RN={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:EN,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,wh.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}vx(t,n)}};function vx(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Mn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Mn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,wh.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Mn._)`${a} <= ${e.length}`);r.if((0,Mn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:wh.Type.Num},l),i.allErrors||r.if((0,Mn.not)(l),()=>r.break())})}}Qs.validateAdditionalItems=vx;Qs.default=RN});var vh=Z(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.validateTuple=void 0;var xx=le(),dc=ve(),PN=Zt(),AN={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return $x(t,"additionalItems",e);r.items=!0,!(0,dc.alwaysValidSchema)(r,e)&&t.ok((0,PN.validateArray)(t))}};function $x(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=dc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,xx._)`${s}.length`);r.forEach((d,b)=>{(0,dc.alwaysValidSchema)(a,d)||(n.if((0,xx._)`${l} > ${b}`,()=>t.subschema({keyword:i,schemaProp:b,dataProp:b},c)),t.ok(c))});function u(d){let{opts:b,errSchemaPath:h}=a,f=r.length,y=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(b.strictTuples&&!y){let v=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,dc.checkStrictMode)(a,v,b.strictTuples)}}}ei.validateTuple=$x;ei.default=AN});var kx=Z(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});var IN=vh(),ON={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,IN.validateTuple)(t,"items")};xh.default=ON});var Tx=Z($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});var Sx=le(),CN=ve(),zN=Zt(),NN=_h(),jN={message:({params:{len:t}})=>(0,Sx.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Sx._)`{limit: ${t}}`},LN={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:jN,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,CN.alwaysValidSchema)(n,e)&&(o?(0,NN.validateAdditionalItems)(t,o):t.ok((0,zN.validateArray)(t)))}};$h.default=LN});var Ex=Z(kh=>{"use strict";Object.defineProperty(kh,"__esModule",{value:!0});var Ft=le(),pc=ve(),MN={message:({params:{min:t,max:e}})=>e===void 0?(0,Ft.str)`must contain at least ${t} valid item(s)`:(0,Ft.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ft._)`{minContains: ${t}}`:(0,Ft._)`{minContains: ${t}, maxContains: ${e}}`},DN={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:MN,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=e.const("len",(0,Ft._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,pc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,pc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,pc.alwaysValidSchema)(s,r)){let y=(0,Ft._)`${u} >= ${i}`;a!==void 0&&(y=(0,Ft._)`${y} && ${u} <= ${a}`),t.pass(y);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?h(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Ft._)`${o}.length > 0`,b)):(e.let(d,!1),b()),t.result(d,()=>t.reset());function b(){let y=e.name("_valid"),v=e.let("count",0);h(y,()=>e.if(y,()=>f(v)))}function h(y,v){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:pc.Type.Num,compositeRule:!0},y),v()})}function f(y){e.code((0,Ft._)`${y}++`),a===void 0?e.if((0,Ft._)`${y} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Ft._)`${y} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Ft._)`${y} >= ${i}`,()=>e.assign(d,!0)))}}};kh.default=DN});var Ax=Z(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.validateSchemaDeps=ur.validatePropertyDeps=ur.error=void 0;var Sh=le(),UN=ve(),ti=Zt();ur.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Sh.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Sh._)`{property: ${t},
935
990
  missingProperty: ${n},
936
991
  depsCount: ${e},
937
- deps: ${r}}`};var LN={keyword:"dependencies",type:"object",schemaType:"object",error:ur.error,code(t){let[e,r]=MN(t);Sx(t,e),Tx(t,r)}};function MN({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Sx(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,ei.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,ei.checkReportMissingProp)(t,l)}):(r.if((0,$h._)`${c} && (${(0,ei.checkMissingProp)(t,a,s)})`),(0,ei.reportMissingProp)(t,s),r.else())}}ur.validatePropertyDeps=Sx;function Tx(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,jN.alwaysValidSchema)(s,e[a])||(r.if((0,ei.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}ur.validateSchemaDeps=Tx;ur.default=LN});var Px=U(kh=>{"use strict";Object.defineProperty(kh,"__esModule",{value:!0});var Rx=ae(),DN=be(),UN={message:"property name must be valid",params:({params:t})=>(0,Rx._)`{propertyName: ${t.propertyName}}`},ZN={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:UN,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,DN.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Rx.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};kh.default=ZN});var Th=U(Sh=>{"use strict";Object.defineProperty(Sh,"__esModule",{value:!0});var fc=Zt(),Qt=ae(),qN=Sr(),hc=be(),FN={message:"must NOT have additional properties",params:({params:t})=>(0,Qt._)`{additionalProperty: ${t.additionalProperty}}`},BN={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:FN,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,hc.alwaysValidSchema)(i,r))return;let l=(0,fc.allSchemaProperties)(n.properties),u=(0,fc.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Qt._)`${s} === ${qN.default.errors}`);function d(){e.forIn("key",o,w=>{!l.length&&!u.length?f(w):e.if(y(w),()=>f(w))})}function y(w){let E;if(l.length>8){let R=(0,hc.schemaRefOrVal)(i,n.properties,"properties");E=(0,fc.isOwnProperty)(e,R,w)}else l.length?E=(0,Qt.or)(...l.map(R=>(0,Qt._)`${w} === ${R}`)):E=Qt.nil;return u.length&&(E=(0,Qt.or)(E,...u.map(R=>(0,Qt._)`${(0,fc.usePattern)(t,R)}.test(${w})`))),(0,Qt.not)(E)}function h(w){e.code((0,Qt._)`delete ${o}[${w}]`)}function f(w){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(w);return}if(r===!1){t.setParams({additionalProperty:w}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,hc.alwaysValidSchema)(i,r)){let E=e.name("valid");c.removeAdditional==="failing"?(g(w,E,!1),e.if((0,Qt.not)(E),()=>{t.reset(),h(w)})):(g(w,E),a||e.if((0,Qt.not)(E),()=>e.break()))}}function g(w,E,R){let C={keyword:"additionalProperties",dataProp:w,dataPropType:hc.Type.Str};R===!1&&Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(C,E)}}};Sh.default=BN});var Ox=U(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});var VN=Us(),Ax=Zt(),Eh=be(),Ix=Th(),HN={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Ix.default.code(new VN.KeywordCxt(s,Ix.default,"additionalProperties"));let i=(0,Ax.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Eh.mergeEvaluated.props(e,(0,Eh.toHash)(i),s.props));let a=i.filter(d=>!(0,Eh.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,Ax.propertyInData)(e,o,d,s.opts.ownProperties)),u(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Rh.default=HN});var jx=U(Ph=>{"use strict";Object.defineProperty(Ph,"__esModule",{value:!0});var Cx=Zt(),mc=ae(),zx=be(),Nx=be(),KN={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Cx.allSchemaProperties)(r),c=a.filter(g=>(0,zx.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof mc.Name)&&(s.props=(0,Nx.evaluatedPropsToName)(e,s.props));let{props:d}=s;y();function y(){for(let g of a)l&&h(g),s.allErrors?f(g):(e.var(u,!0),f(g),e.if(u))}function h(g){for(let w in l)new RegExp(g).test(w)&&(0,zx.checkStrictMode)(s,`property ${w} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){e.forIn("key",n,w=>{e.if((0,mc._)`${(0,Cx.usePattern)(t,g)}.test(${w})`,()=>{let E=c.includes(g);E||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:w,dataPropType:Nx.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,mc._)`${d}[${w}]`,!0):!E&&!s.allErrors&&e.if((0,mc.not)(u),()=>e.break())})})}}};Ph.default=KN});var Lx=U(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});var GN=be(),WN={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,GN.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Ah.default=WN});var Mx=U(Ih=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});var JN=Zt(),YN={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:JN.validateUnion,error:{message:"must match a schema in anyOf"}};Ih.default=YN});var Dx=U(Oh=>{"use strict";Object.defineProperty(Oh,"__esModule",{value:!0});var gc=ae(),XN=be(),QN={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,gc._)`{passingSchemas: ${t.passing}}`},e1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:QN,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(i,()=>t.reset(),()=>t.error(!0));function l(){s.forEach((u,d)=>{let y;(0,XN.alwaysValidSchema)(o,u)?e.var(c,!0):y=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,gc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,gc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),y&&t.mergeEvaluated(y,gc.Name)})})}}};Oh.default=e1});var Ux=U(Ch=>{"use strict";Object.defineProperty(Ch,"__esModule",{value:!0});var t1=be(),r1={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,t1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Ch.default=r1});var Fx=U(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var yc=ae(),qx=be(),n1={message:({params:t})=>(0,yc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,yc._)`{failingKeyword: ${t.ifClause}}`},o1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:n1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,qx.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Zx(n,"then"),s=Zx(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,yc.not)(a),l("else"));t.pass(i,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let y=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(y,i),d?e.assign(d,(0,yc._)`${u}`):t.setParams({ifClause:u})}}}};function Zx(t,e){let r=t.schema[e];return r!==void 0&&!(0,qx.alwaysValidSchema)(t,r)}zh.default=o1});var Bx=U(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});var s1=be(),i1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,s1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Nh.default=i1});var Vx=U(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var a1=bh(),c1=vx(),l1=_h(),u1=$x(),d1=kx(),p1=Ex(),f1=Px(),h1=Th(),m1=Ox(),g1=jx(),y1=Lx(),b1=Mx(),_1=Dx(),w1=Ux(),v1=Fx(),x1=Bx();function $1(t=!1){let e=[y1.default,b1.default,_1.default,w1.default,v1.default,x1.default,f1.default,h1.default,p1.default,m1.default,g1.default];return t?e.push(c1.default,u1.default):e.push(a1.default,l1.default),e.push(d1.default),e}jh.default=$1});var Hx=U(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});var Be=ae(),k1={message:({schemaCode:t})=>(0,Be.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Be._)`{format: ${t}}`},S1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:k1,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?y():h();function y(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,Be._)`${f}[${i}]`),w=r.let("fType"),E=r.let("format");r.if((0,Be._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(w,(0,Be._)`${g}.type || "string"`).assign(E,(0,Be._)`${g}.validate`),()=>r.assign(w,(0,Be._)`"string"`).assign(E,g)),t.fail$data((0,Be.or)(R(),C()));function R(){return c.strictSchema===!1?Be.nil:(0,Be._)`${i} && !${E}`}function C(){let B=u.$async?(0,Be._)`(${g}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,Be._)`${E}(${n})`,W=(0,Be._)`(typeof ${E} == "function" ? ${B} : ${E}.test(${n}))`;return(0,Be._)`${E} && ${E} !== true && ${w} === ${e} && !${W}`}}function h(){let f=d.formats[s];if(!f){R();return}if(f===!0)return;let[g,w,E]=C(f);g===e&&t.pass(B());function R(){if(c.strictSchema===!1){d.logger.warn(W());return}throw new Error(W());function W(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function C(W){let He=W instanceof RegExp?(0,Be.regexpCode)(W):c.code.formats?(0,Be._)`${c.code.formats}${(0,Be.getProperty)(s)}`:void 0,Xe=r.scopeValue("formats",{key:s,ref:W,code:He});return typeof W=="object"&&!(W instanceof RegExp)?[W.type||"string",W.validate,(0,Be._)`${Xe}.validate`]:["string",W,Xe]}function B(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Be._)`await ${E}(${n})`}return typeof w=="function"?(0,Be._)`${E}(${n})`:(0,Be._)`${E}.test(${n})`}}}};Lh.default=S1});var Kx=U(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});var T1=Hx(),E1=[T1.default];Mh.default=E1});var Gx=U(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.contentVocabulary=ko.metadataVocabulary=void 0;ko.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ko.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Jx=U(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});var R1=nx(),P1=yx(),A1=Vx(),I1=Kx(),Wx=Gx(),O1=[R1.default,P1.default,(0,A1.default)(),I1.default,Wx.metadataVocabulary,Wx.contentVocabulary];Dh.default=O1});var Xx=U(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.DiscrError=void 0;var Yx;(function(t){t.Tag="tag",t.Mapping="mapping"})(Yx||(bc.DiscrError=Yx={}))});var e$=U(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});var So=ae(),Uh=Xx(),Qx=Qa(),C1=Zs(),z1=be(),N1={message:({params:{discrError:t,tagName:e}})=>t===Uh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,So._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},j1={keyword:"discriminator",type:"object",schemaType:"object",error:N1,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,So._)`${r}${(0,So.getProperty)(a)}`);e.if((0,So._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Uh.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let h=y();e.if(!1);for(let f in h)e.elseIf((0,So._)`${l} === ${f}`),e.assign(c,d(h[f]));e.else(),t.error(!1,{discrError:Uh.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(h){let f=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:h},f);return t.mergeEvaluated(g,So.Name),f}function y(){var h;let f={},g=E(o),w=!0;for(let B=0;B<i.length;B++){let W=i[B];if(W?.$ref&&!(0,z1.schemaHasRulesButRef)(W,s.self.RULES)){let Xe=W.$ref;if(W=Qx.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Xe),W instanceof Qx.SchemaEnv&&(W=W.schema),W===void 0)throw new C1.default(s.opts.uriResolver,s.baseId,Xe)}let He=(h=W?.properties)===null||h===void 0?void 0:h[a];if(typeof He!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);w=w&&(g||E(W)),R(He,B)}if(!w)throw new Error(`discriminator: "${a}" must be required`);return f;function E({required:B}){return Array.isArray(B)&&B.includes(a)}function R(B,W){if(B.const)C(B.const,W);else if(B.enum)for(let He of B.enum)C(He,W);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function C(B,W){if(typeof B!="string"||B in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[B]=W}}}};Zh.default=j1});var t$=U((qB,L1)=>{L1.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Fh=U((je,qh)=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.MissingRefError=je.ValidationError=je.CodeGen=je.Name=je.nil=je.stringify=je.str=je._=je.KeywordCxt=je.Ajv=void 0;var M1=Yv(),D1=Jx(),U1=e$(),r$=t$(),Z1=["/properties"],_c="http://json-schema.org/draft-07/schema",To=class extends M1.default{_addVocabularies(){super._addVocabularies(),D1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(U1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(r$,Z1):r$;this.addMetaSchema(e,_c,!1),this.refs["http://json-schema.org/schema"]=_c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_c)?_c:void 0)}};je.Ajv=To;qh.exports=je=To;qh.exports.Ajv=To;Object.defineProperty(je,"__esModule",{value:!0});je.default=To;var q1=Us();Object.defineProperty(je,"KeywordCxt",{enumerable:!0,get:function(){return q1.KeywordCxt}});var Eo=ae();Object.defineProperty(je,"_",{enumerable:!0,get:function(){return Eo._}});Object.defineProperty(je,"str",{enumerable:!0,get:function(){return Eo.str}});Object.defineProperty(je,"stringify",{enumerable:!0,get:function(){return Eo.stringify}});Object.defineProperty(je,"nil",{enumerable:!0,get:function(){return Eo.nil}});Object.defineProperty(je,"Name",{enumerable:!0,get:function(){return Eo.Name}});Object.defineProperty(je,"CodeGen",{enumerable:!0,get:function(){return Eo.CodeGen}});var F1=Ya();Object.defineProperty(je,"ValidationError",{enumerable:!0,get:function(){return F1.default}});var B1=Zs();Object.defineProperty(je,"MissingRefError",{enumerable:!0,get:function(){return B1.default}})});var u$=U(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.formatNames=pr.fastFormats=pr.fullFormats=void 0;function dr(t,e){return{validate:t,compare:e}}pr.fullFormats={date:dr(i$,Kh),time:dr(Vh(!0),Gh),"date-time":dr(n$(!0),c$),"iso-time":dr(Vh(),a$),"iso-date-time":dr(n$(),l$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:J1,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:nj,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:Y1,int32:{type:"number",validate:ej},int64:{type:"number",validate:tj},float:{type:"number",validate:s$},double:{type:"number",validate:s$},password:!0,binary:!0};pr.fastFormats={...pr.fullFormats,date:dr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Kh),time:dr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Gh),"date-time":dr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c$),"iso-time":dr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,a$),"iso-date-time":dr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l$),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};pr.formatNames=Object.keys(pr.fullFormats);function V1(t){return t%4===0&&(t%100!==0||t%400===0)}var H1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,K1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i$(t){let e=H1.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&V1(r)?29:K1[n])}function Kh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Bh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Vh(t){return function(r){let n=Bh.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-u*c,y=o-l*c-(d<0?1:0);return(y===23||y===-1)&&(d===59||d===-1)&&i<61}}function Gh(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function a$(t,e){if(!(t&&e))return;let r=Bh.exec(t),n=Bh.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Hh=/t|\s/i;function n$(t){let e=Vh(t);return function(n){let o=n.split(Hh);return o.length===2&&i$(o[0])&&e(o[1])}}function c$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function l$(t,e){if(!(t&&e))return;let[r,n]=t.split(Hh),[o,s]=e.split(Hh),i=Kh(r,o);if(i!==void 0)return i||Gh(n,s)}var G1=/\/|:/,W1=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function J1(t){return G1.test(t)&&W1.test(t)}var o$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Y1(t){return o$.lastIndex=0,o$.test(t)}var X1=-(2**31),Q1=2**31-1;function ej(t){return Number.isInteger(t)&&t<=Q1&&t>=X1}function tj(t){return Number.isInteger(t)}function s$(){return!0}var rj=/[^\\]\\Z/;function nj(t){if(rj.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var d$=U(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});Ro.formatLimitDefinition=void 0;var oj=Fh(),er=ae(),Xr=er.operators,wc={formatMaximum:{okStr:"<=",ok:Xr.LTE,fail:Xr.GT},formatMinimum:{okStr:">=",ok:Xr.GTE,fail:Xr.LT},formatExclusiveMaximum:{okStr:"<",ok:Xr.LT,fail:Xr.GTE},formatExclusiveMinimum:{okStr:">",ok:Xr.GT,fail:Xr.LTE}},sj={message:({keyword:t,schemaCode:e})=>(0,er.str)`should be ${wc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,er._)`{comparison: ${wc[t].okStr}, limit: ${e}}`};Ro.formatLimitDefinition={keyword:Object.keys(wc),type:"string",schemaType:"string",$data:!0,error:sj,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new oj.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let y=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,er._)`${y}[${c.schemaCode}]`);t.fail$data((0,er.or)((0,er._)`typeof ${h} != "object"`,(0,er._)`${h} instanceof RegExp`,(0,er._)`typeof ${h}.compare != "function"`,d(h)))}function u(){let y=c.schema,h=a.formats[y];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${y}" does not define "compare" function`);let f=e.scopeValue("formats",{key:y,ref:h,code:i.code.formats?(0,er._)`${i.code.formats}${(0,er.getProperty)(y)}`:void 0});t.fail$data(d(f))}function d(y){return(0,er._)`${y}.compare(${r}, ${n}) ${wc[o].fail} 0`}},dependencies:["format"]};var ij=t=>(t.addKeyword(Ro.formatLimitDefinition),t);Ro.default=ij});var m$=U((ti,h$)=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});var Po=u$(),aj=d$(),Wh=ae(),p$=new Wh.Name("fullFormats"),cj=new Wh.Name("fastFormats"),Jh=(t,e={keywords:!0})=>{if(Array.isArray(e))return f$(t,e,Po.fullFormats,p$),t;let[r,n]=e.mode==="fast"?[Po.fastFormats,cj]:[Po.fullFormats,p$],o=e.formats||Po.formatNames;return f$(t,o,r,n),e.keywords&&(0,aj.default)(t),t};Jh.get=(t,e="full")=>{let n=(e==="fast"?Po.fastFormats:Po.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function f$(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Wh._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}h$.exports=ti=Jh;Object.defineProperty(ti,"__esModule",{value:!0});ti.default=Jh});function lj(){let t=new g$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,y$.default)(t),t}var g$,y$,vc,b$=O(()=>{g$=Ac(Fh(),1),y$=Ac(m$(),1);vc=class{constructor(e){this._ajv=e??lj()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var xc,_$=O(()=>{po();xc=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(y=>y.type==="tool_use").map(y=>y.id)),d=new Set(s.filter(y=>y.type==="tool_result").map(y=>y.toolUseId));if(u.size!==d.size||![...u].every(y=>d.has(y)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ss,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},uo,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function w$(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function v$(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var x$=O(()=>{});var $c,$$=O(()=>{Tw();po();b$();fs();_$();x$();$c=class extends Ma{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ks.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new vc,this.setRequestHandler(lp,n=>this._oninitialize(n)),this.setNotificationHandler(up,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(yp,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ks.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new xc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Sw(this._capabilities,e)}setRequestHandler(e,r){let o=Zr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=so(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,l)=>{let u=Ur(lo,c);if(!u.success){let f=u.error instanceof Error?u.error.message:String(u.error);throw new H(J.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=u.data,y=await Promise.resolve(r(c,l));if(d.task){let f=Ur(ao,y);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new H(J.InvalidParams,`Invalid task creation result: ${g}`)}return f.data}let h=Ur(Ta,y);if(!h.success){let f=h.error instanceof Error?h.error.message:String(h.error);throw new H(J.InvalidParams,`Invalid tools/call result: ${f}`)}return h.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){v$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&w$(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:S_.includes(r)?r:op,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ua)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(l=>l.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(l=>l.type==="tool_use");if(s){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(l.size!==u.size||![...l].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},bp,r):this.request({method:"sampling/createMessage",params:e},Ss,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},uo,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},uo,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new H(J.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof H?i:new H(J.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},_p,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function Yh(t){return!!t&&typeof t=="object"&&S$ in t}function T$(t){return t[S$]?.complete}var S$,k$,E$=O(()=>{S$=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(k$||(k$={}))});var R$=O(()=>{});function dj(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!uj.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function pj(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Xh(t){let e=dj(t);return pj(t,e.warnings),e.isValid}var uj,P$=O(()=>{uj=/^[A-Za-z0-9._-]{1,128}$/});var kc,A$=O(()=>{kc=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});function C$(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function z$(t){return"_def"in t||"_zod"in t||C$(t)}function Qh(t){return typeof t!="object"||t===null||z$(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(C$)}function I$(t){if(t){if(Qh(t))return Tn(t);if(!z$(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function hj(t){let e=Zr(t);return e?Object.entries(e).map(([r,n])=>{let o=Jb(n),s=Yb(n);return{name:r,description:o,required:!s}}):[]}function Qr(t){let r=Zr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=so(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function O$(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Sc,fj,ri,N$=O(()=>{$$();fs();rf();po();E$();R$();P$();A$();Kn();Sc=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new $c(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new kc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Qr(Sa)),this.server.assertCanSetRequestHandler(Qr(lo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Sa,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=oo(r.inputSchema);return o?Qp(o,{strictUnions:!0,pipeStrategy:"input"}):fj})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=oo(r.outputSchema);o&&(n.outputSchema=Qp(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(lo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new H(J.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new H(J.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new H(J.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new H(J.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof H&&n.code===J.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=oo(e.inputSchema)??e.inputSchema,i=await na(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=oa(a);throw new H(J.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new H(J.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=oo(e.outputSchema),s=await na(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=oa(i);throw new H(J.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(y=>setTimeout(y,u));let d=await n.taskStore.getTask(c);if(!d)throw new H(J.InternalError,`Task ${c} not found during polling`);l=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Qr(Ea)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ea,async e=>{switch(e.params.ref.type){case"ref/prompt":return Z_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return q_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new H(J.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new H(J.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new H(J.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ri;let s=Zr(n.argsSchema)?.[e.params.argument.name];if(!Yh(s))return ri;let i=T$(s);if(!i)return ri;let a=await i(e.params.argument.value,e.params.context);return O$(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return ri;throw new H(J.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ri;let s=await o(e.params.argument.value,e.params.context);return O$(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Qr(wa)),this.server.assertCanSetRequestHandler(Qr(va)),this.server.assertCanSetRequestHandler(Qr(xa)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(wa,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(va,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(xa,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new H(J.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new H(J.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Qr($a)),this.server.assertCanSetRequestHandler(Qr(ka)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($a,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?hj(r.argsSchema):void 0}))})),this.server.setRequestHandler(ka,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new H(J.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new H(J.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=oo(n.argsSchema),s=await na(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=oa(c);throw new H(J.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Tn(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Tn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let l=c instanceof gt?c._def?.innerType:c;return Yh(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){Xh(e);let u={title:r,description:n,inputSchema:I$(o),outputSchema:I$(s),annotations:i,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&Xh(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=Tn(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=Tn(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Qh(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Qh(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},fj={type:"object",properties:{}};ri={completion:{values:[],hasMore:!1}}});function gj(t){return C_.parse(JSON.parse(t))}function j$(t){return JSON.stringify(t)+`
938
- `}var mj,Tc,L$=O(()=>{po();mj=10*1024*1024,Tc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??mj}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
939
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),gj(r)}clear(){this._buffer=void 0}}});import M$ from"node:process";var Ec,D$=O(()=>{L$();Ec=class{constructor(e=M$.stdin,r=M$.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new Tc({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=j$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var U$,Z$=O(()=>{U$=[]});var J$={};No(J$,{AUTHORING_MCP_SERVER_NAME:()=>H$,AUTHORING_MCP_SERVER_VERSION:()=>K$,AUTHORING_RESOURCES:()=>wj,AUTHORING_TOOLS:()=>_j,AUTHORING_TOOLS_PUBLIC:()=>W$,buildAuthoringMcpServer:()=>G$,runAuthoringMcpServer:()=>vj});import{promises as yj}from"node:fs";import{resolve as q$}from"node:path";function V$(){return B$??=import("../mcp/grounding.js").then(e=>e,()=>null),B$}function Ve(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function bj(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(s=>s.hookId).filter(s=>typeof s=="string"):null}catch{return null}}async function G$(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let h=await or(t.baseUrl);if(!h)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:h.baseUrl,token:h.token}}let r=t.grounding??{},n=await V$(),o=null;if(n)try{let h=await e();o={surface:"mcp-authoring",baseUrl:h.baseUrl,token:h.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],c=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{c=(await n.listRecipesForSurface(o,i)).map(h=>({id:h.id,record_type:h.record_type,intent:h.intent}))}catch{c=[]}}let l=o?await bj(o,r):null,u=new Sc({name:H$,version:K$},n?{instructions:n.renderAuthoringInstructions({baseUrl:o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(h=>h.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let h=o;for(let f of a)u.registerPrompt(f.id,{title:f.name,description:f.description},async()=>{let g=await n.getMcpPromptSkill(h,f.id,r);if(!g)throw new Error(`unknown prompt: ${f.id}`);return{description:g.description,messages:[{role:"user",content:{type:"text",text:(g.prompts??[]).join(`
992
+ deps: ${r}}`};var ZN={keyword:"dependencies",type:"object",schemaType:"object",error:ur.error,code(t){let[e,r]=qN(t);Rx(t,e),Px(t,r)}};function qN({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Rx(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,ti.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,ti.checkReportMissingProp)(t,l)}):(r.if((0,Sh._)`${c} && (${(0,ti.checkMissingProp)(t,a,s)})`),(0,ti.reportMissingProp)(t,s),r.else())}}ur.validatePropertyDeps=Rx;function Px(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,UN.alwaysValidSchema)(s,e[a])||(r.if((0,ti.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}ur.validateSchemaDeps=Px;ur.default=ZN});var Ox=Z(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});var Ix=le(),FN=ve(),BN={message:"property name must be valid",params:({params:t})=>(0,Ix._)`{propertyName: ${t.propertyName}}`},VN={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:BN,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,FN.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Ix.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Th.default=VN});var Rh=Z(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});var fc=Zt(),Xt=le(),HN=Tr(),hc=ve(),KN={message:"must NOT have additional properties",params:({params:t})=>(0,Xt._)`{additionalProperty: ${t.additionalProperty}}`},GN={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:KN,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,hc.alwaysValidSchema)(i,r))return;let l=(0,fc.allSchemaProperties)(n.properties),u=(0,fc.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Xt._)`${s} === ${HN.default.errors}`);function d(){e.forIn("key",o,v=>{!l.length&&!u.length?f(v):e.if(b(v),()=>f(v))})}function b(v){let E;if(l.length>8){let R=(0,hc.schemaRefOrVal)(i,n.properties,"properties");E=(0,fc.isOwnProperty)(e,R,v)}else l.length?E=(0,Xt.or)(...l.map(R=>(0,Xt._)`${v} === ${R}`)):E=Xt.nil;return u.length&&(E=(0,Xt.or)(E,...u.map(R=>(0,Xt._)`${(0,fc.usePattern)(t,R)}.test(${v})`))),(0,Xt.not)(E)}function h(v){e.code((0,Xt._)`delete ${o}[${v}]`)}function f(v){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(v);return}if(r===!1){t.setParams({additionalProperty:v}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,hc.alwaysValidSchema)(i,r)){let E=e.name("valid");c.removeAdditional==="failing"?(y(v,E,!1),e.if((0,Xt.not)(E),()=>{t.reset(),h(v)})):(y(v,E),a||e.if((0,Xt.not)(E),()=>e.break()))}}function y(v,E,R){let z={keyword:"additionalProperties",dataProp:v,dataPropType:hc.Type.Str};R===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};Eh.default=GN});var Nx=Z(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});var WN=Zs(),Cx=Zt(),Ph=ve(),zx=Rh(),JN={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&zx.default.code(new WN.KeywordCxt(s,zx.default,"additionalProperties"));let i=(0,Cx.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Ph.mergeEvaluated.props(e,(0,Ph.toHash)(i),s.props));let a=i.filter(d=>!(0,Ph.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,Cx.propertyInData)(e,o,d,s.opts.ownProperties)),u(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Ah.default=JN});var Dx=Z(Ih=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});var jx=Zt(),mc=le(),Lx=ve(),Mx=ve(),YN={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,jx.allSchemaProperties)(r),c=a.filter(y=>(0,Lx.alwaysValidSchema)(s,r[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof mc.Name)&&(s.props=(0,Mx.evaluatedPropsToName)(e,s.props));let{props:d}=s;b();function b(){for(let y of a)l&&h(y),s.allErrors?f(y):(e.var(u,!0),f(y),e.if(u))}function h(y){for(let v in l)new RegExp(y).test(v)&&(0,Lx.checkStrictMode)(s,`property ${v} matches pattern ${y} (use allowMatchingProperties)`)}function f(y){e.forIn("key",n,v=>{e.if((0,mc._)`${(0,jx.usePattern)(t,y)}.test(${v})`,()=>{let E=c.includes(y);E||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:v,dataPropType:Mx.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,mc._)`${d}[${v}]`,!0):!E&&!s.allErrors&&e.if((0,mc.not)(u),()=>e.break())})})}}};Ih.default=YN});var Ux=Z(Oh=>{"use strict";Object.defineProperty(Oh,"__esModule",{value:!0});var XN=ve(),QN={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,XN.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Oh.default=QN});var Zx=Z(Ch=>{"use strict";Object.defineProperty(Ch,"__esModule",{value:!0});var e1=Zt(),t1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:e1.validateUnion,error:{message:"must match a schema in anyOf"}};Ch.default=t1});var qx=Z(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var gc=le(),r1=ve(),n1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,gc._)`{passingSchemas: ${t.passing}}`},o1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:n1,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(i,()=>t.reset(),()=>t.error(!0));function l(){s.forEach((u,d)=>{let b;(0,r1.alwaysValidSchema)(o,u)?e.var(c,!0):b=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,gc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,gc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),b&&t.mergeEvaluated(b,gc.Name)})})}}};zh.default=o1});var Fx=Z(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});var s1=ve(),i1={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,s1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Nh.default=i1});var Hx=Z(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var yc=le(),Vx=ve(),a1={message:({params:t})=>(0,yc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,yc._)`{failingKeyword: ${t.ifClause}}`},c1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:a1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Vx.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Bx(n,"then"),s=Bx(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,yc.not)(a),l("else"));t.pass(i,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let b=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(b,i),d?e.assign(d,(0,yc._)`${u}`):t.setParams({ifClause:u})}}}};function Bx(t,e){let r=t.schema[e];return r!==void 0&&!(0,Vx.alwaysValidSchema)(t,r)}jh.default=c1});var Kx=Z(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});var l1=ve(),u1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,l1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Lh.default=u1});var Gx=Z(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});var d1=_h(),p1=kx(),f1=vh(),h1=Tx(),m1=Ex(),g1=Ax(),y1=Ox(),b1=Rh(),w1=Nx(),_1=Dx(),v1=Ux(),x1=Zx(),$1=qx(),k1=Fx(),S1=Hx(),T1=Kx();function E1(t=!1){let e=[v1.default,x1.default,$1.default,k1.default,S1.default,T1.default,y1.default,b1.default,g1.default,w1.default,_1.default];return t?e.push(p1.default,h1.default):e.push(d1.default,f1.default),e.push(m1.default),e}Mh.default=E1});var Wx=Z(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});var Be=le(),R1={message:({schemaCode:t})=>(0,Be.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Be._)`{format: ${t}}`},P1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:R1,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?b():h();function b(){let f=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=r.const("fDef",(0,Be._)`${f}[${i}]`),v=r.let("fType"),E=r.let("format");r.if((0,Be._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(v,(0,Be._)`${y}.type || "string"`).assign(E,(0,Be._)`${y}.validate`),()=>r.assign(v,(0,Be._)`"string"`).assign(E,y)),t.fail$data((0,Be.or)(R(),z()));function R(){return c.strictSchema===!1?Be.nil:(0,Be._)`${i} && !${E}`}function z(){let V=u.$async?(0,Be._)`(${y}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,Be._)`${E}(${n})`,J=(0,Be._)`(typeof ${E} == "function" ? ${V} : ${E}.test(${n}))`;return(0,Be._)`${E} && ${E} !== true && ${v} === ${e} && !${J}`}}function h(){let f=d.formats[s];if(!f){R();return}if(f===!0)return;let[y,v,E]=z(f);y===e&&t.pass(V());function R(){if(c.strictSchema===!1){d.logger.warn(J());return}throw new Error(J());function J(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function z(J){let He=J instanceof RegExp?(0,Be.regexpCode)(J):c.code.formats?(0,Be._)`${c.code.formats}${(0,Be.getProperty)(s)}`:void 0,Xe=r.scopeValue("formats",{key:s,ref:J,code:He});return typeof J=="object"&&!(J instanceof RegExp)?[J.type||"string",J.validate,(0,Be._)`${Xe}.validate`]:["string",J,Xe]}function V(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Be._)`await ${E}(${n})`}return typeof v=="function"?(0,Be._)`${E}(${n})`:(0,Be._)`${E}.test(${n})`}}}};Dh.default=P1});var Jx=Z(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var A1=Wx(),I1=[A1.default];Uh.default=I1});var Yx=Z(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.contentVocabulary=Eo.metadataVocabulary=void 0;Eo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Eo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Qx=Z(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});var O1=ix(),C1=_x(),z1=Gx(),N1=Jx(),Xx=Yx(),j1=[O1.default,C1.default,(0,z1.default)(),N1.default,Xx.metadataVocabulary,Xx.contentVocabulary];Zh.default=j1});var t$=Z(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.DiscrError=void 0;var e$;(function(t){t.Tag="tag",t.Mapping="mapping"})(e$||(bc.DiscrError=e$={}))});var n$=Z(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var Ro=le(),qh=t$(),r$=Qa(),L1=qs(),M1=ve(),D1={message:({params:{discrError:t,tagName:e}})=>t===qh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Ro._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},U1={keyword:"discriminator",type:"object",schemaType:"object",error:D1,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Ro._)`${r}${(0,Ro.getProperty)(a)}`);e.if((0,Ro._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:qh.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let h=b();e.if(!1);for(let f in h)e.elseIf((0,Ro._)`${l} === ${f}`),e.assign(c,d(h[f]));e.else(),t.error(!1,{discrError:qh.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(h){let f=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:h},f);return t.mergeEvaluated(y,Ro.Name),f}function b(){var h;let f={},y=E(o),v=!0;for(let V=0;V<i.length;V++){let J=i[V];if(J?.$ref&&!(0,M1.schemaHasRulesButRef)(J,s.self.RULES)){let Xe=J.$ref;if(J=r$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Xe),J instanceof r$.SchemaEnv&&(J=J.schema),J===void 0)throw new L1.default(s.opts.uriResolver,s.baseId,Xe)}let He=(h=J?.properties)===null||h===void 0?void 0:h[a];if(typeof He!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);v=v&&(y||E(J)),R(He,V)}if(!v)throw new Error(`discriminator: "${a}" must be required`);return f;function E({required:V}){return Array.isArray(V)&&V.includes(a)}function R(V,J){if(V.const)z(V.const,J);else if(V.enum)for(let He of V.enum)z(He,J);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(V,J){if(typeof V!="string"||V in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[V]=J}}}};Fh.default=U1});var o$=Z((HB,Z1)=>{Z1.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Vh=Z((Le,Bh)=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.MissingRefError=Le.ValidationError=Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=Le.Ajv=void 0;var q1=ex(),F1=Qx(),B1=n$(),s$=o$(),V1=["/properties"],wc="http://json-schema.org/draft-07/schema",Po=class extends q1.default{_addVocabularies(){super._addVocabularies(),F1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(B1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(s$,V1):s$;this.addMetaSchema(e,wc,!1),this.refs["http://json-schema.org/schema"]=wc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(wc)?wc:void 0)}};Le.Ajv=Po;Bh.exports=Le=Po;Bh.exports.Ajv=Po;Object.defineProperty(Le,"__esModule",{value:!0});Le.default=Po;var H1=Zs();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return H1.KeywordCxt}});var Ao=le();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return Ao._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return Ao.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return Ao.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return Ao.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return Ao.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return Ao.CodeGen}});var K1=Ya();Object.defineProperty(Le,"ValidationError",{enumerable:!0,get:function(){return K1.default}});var G1=qs();Object.defineProperty(Le,"MissingRefError",{enumerable:!0,get:function(){return G1.default}})});var f$=Z(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.formatNames=pr.fastFormats=pr.fullFormats=void 0;function dr(t,e){return{validate:t,compare:e}}pr.fullFormats={date:dr(l$,Wh),time:dr(Kh(!0),Jh),"date-time":dr(i$(!0),d$),"iso-time":dr(Kh(),u$),"iso-date-time":dr(i$(),p$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:ej,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:aj,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:tj,int32:{type:"number",validate:oj},int64:{type:"number",validate:sj},float:{type:"number",validate:c$},double:{type:"number",validate:c$},password:!0,binary:!0};pr.fastFormats={...pr.fullFormats,date:dr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Wh),time:dr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Jh),"date-time":dr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,d$),"iso-time":dr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u$),"iso-date-time":dr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,p$),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};pr.formatNames=Object.keys(pr.fullFormats);function W1(t){return t%4===0&&(t%100!==0||t%400===0)}var J1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Y1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function l$(t){let e=J1.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&W1(r)?29:Y1[n])}function Wh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Hh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Kh(t){return function(r){let n=Hh.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-u*c,b=o-l*c-(d<0?1:0);return(b===23||b===-1)&&(d===59||d===-1)&&i<61}}function Jh(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function u$(t,e){if(!(t&&e))return;let r=Hh.exec(t),n=Hh.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Gh=/t|\s/i;function i$(t){let e=Kh(t);return function(n){let o=n.split(Gh);return o.length===2&&l$(o[0])&&e(o[1])}}function d$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function p$(t,e){if(!(t&&e))return;let[r,n]=t.split(Gh),[o,s]=e.split(Gh),i=Wh(r,o);if(i!==void 0)return i||Jh(n,s)}var X1=/\/|:/,Q1=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function ej(t){return X1.test(t)&&Q1.test(t)}var a$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function tj(t){return a$.lastIndex=0,a$.test(t)}var rj=-(2**31),nj=2**31-1;function oj(t){return Number.isInteger(t)&&t<=nj&&t>=rj}function sj(t){return Number.isInteger(t)}function c$(){return!0}var ij=/[^\\]\\Z/;function aj(t){if(ij.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var h$=Z(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.formatLimitDefinition=void 0;var cj=Vh(),Qt=le(),Qr=Qt.operators,_c={formatMaximum:{okStr:"<=",ok:Qr.LTE,fail:Qr.GT},formatMinimum:{okStr:">=",ok:Qr.GTE,fail:Qr.LT},formatExclusiveMaximum:{okStr:"<",ok:Qr.LT,fail:Qr.GTE},formatExclusiveMinimum:{okStr:">",ok:Qr.GT,fail:Qr.LTE}},lj={message:({keyword:t,schemaCode:e})=>(0,Qt.str)`should be ${_c[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Qt._)`{comparison: ${_c[t].okStr}, limit: ${e}}`};Io.formatLimitDefinition={keyword:Object.keys(_c),type:"string",schemaType:"string",$data:!0,error:lj,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new cj.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let b=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,Qt._)`${b}[${c.schemaCode}]`);t.fail$data((0,Qt.or)((0,Qt._)`typeof ${h} != "object"`,(0,Qt._)`${h} instanceof RegExp`,(0,Qt._)`typeof ${h}.compare != "function"`,d(h)))}function u(){let b=c.schema,h=a.formats[b];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${b}" does not define "compare" function`);let f=e.scopeValue("formats",{key:b,ref:h,code:i.code.formats?(0,Qt._)`${i.code.formats}${(0,Qt.getProperty)(b)}`:void 0});t.fail$data(d(f))}function d(b){return(0,Qt._)`${b}.compare(${r}, ${n}) ${_c[o].fail} 0`}},dependencies:["format"]};var uj=t=>(t.addKeyword(Io.formatLimitDefinition),t);Io.default=uj});var b$=Z((ri,y$)=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var Oo=f$(),dj=h$(),Yh=le(),m$=new Yh.Name("fullFormats"),pj=new Yh.Name("fastFormats"),Xh=(t,e={keywords:!0})=>{if(Array.isArray(e))return g$(t,e,Oo.fullFormats,m$),t;let[r,n]=e.mode==="fast"?[Oo.fastFormats,pj]:[Oo.fullFormats,m$],o=e.formats||Oo.formatNames;return g$(t,o,r,n),e.keywords&&(0,dj.default)(t),t};Xh.get=(t,e="full")=>{let n=(e==="fast"?Oo.fastFormats:Oo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function g$(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Yh._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}y$.exports=ri=Xh;Object.defineProperty(ri,"__esModule",{value:!0});ri.default=Xh});function fj(){let t=new w$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,_$.default)(t),t}var w$,_$,vc,v$=O(()=>{w$=Ic(Vh(),1),_$=Ic(b$(),1);vc=class{constructor(e){this._ajv=e??fj()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var xc,x$=O(()=>{mo();xc=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(b=>b.type==="tool_use").map(b=>b.id)),d=new Set(s.filter(b=>b.type==="tool_result").map(b=>b.toolUseId));if(u.size!==d.size||![...u].every(b=>d.has(b)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ts,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},ho,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function $$(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function k$(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var S$=O(()=>{});var $c,T$=O(()=>{P_();mo();v$();hs();x$();S$();$c=class extends Ma{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ss.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new vc,this.setRequestHandler(dp,n=>this._oninitialize(n)),this.setNotificationHandler(pp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(wp,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ss.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new xc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=R_(this._capabilities,e)}setRequestHandler(e,r){let o=qr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=co(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,l)=>{let u=Zr(fo,c);if(!u.success){let f=u.error instanceof Error?u.error.message:String(u.error);throw new K(Y.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=u.data,b=await Promise.resolve(r(c,l));if(d.task){let f=Zr(uo,b);if(!f.success){let y=f.error instanceof Error?f.error.message:String(f.error);throw new K(Y.InvalidParams,`Invalid task creation result: ${y}`)}return f.data}let h=Zr(Ta,b);if(!h.success){let f=h.error instanceof Error?h.error.message:String(h.error);throw new K(Y.InvalidParams,`Invalid tools/call result: ${f}`)}return h.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){k$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&$$(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Rw.includes(r)?r:ip,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ua)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(l=>l.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(l=>l.type==="tool_use");if(s){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(l.size!==u.size||![...l].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},_p,r):this.request({method:"sampling/createMessage",params:e},Ts,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},ho,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},ho,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new K(Y.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof K?i:new K(Y.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},vp,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function Qh(t){return!!t&&typeof t=="object"&&R$ in t}function P$(t){return t[R$]?.complete}var R$,E$,A$=O(()=>{R$=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(E$||(E$={}))});var I$=O(()=>{});function mj(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!hj.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function gj(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function em(t){let e=mj(t);return gj(t,e.warnings),e.isValid}var hj,O$=O(()=>{hj=/^[A-Za-z0-9._-]{1,128}$/});var kc,C$=O(()=>{kc=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});function j$(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function L$(t){return"_def"in t||"_zod"in t||j$(t)}function tm(t){return typeof t!="object"||t===null||L$(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(j$)}function z$(t){if(t){if(tm(t))return En(t);if(!L$(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function bj(t){let e=qr(t);return e?Object.entries(e).map(([r,n])=>{let o=Qb(n),s=ew(n);return{name:r,description:o,required:!s}}):[]}function en(t){let r=qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=co(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function N$(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Sc,yj,ni,M$=O(()=>{T$();hs();of();mo();A$();I$();O$();C$();Jn();Sc=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new $c(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new kc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(en(Sa)),this.server.assertCanSetRequestHandler(en(fo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Sa,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=ao(r.inputSchema);return o?tf(o,{strictUnions:!0,pipeStrategy:"input"}):yj})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=ao(r.outputSchema);o&&(n.outputSchema=tf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(fo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new K(Y.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new K(Y.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new K(Y.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new K(Y.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof K&&n.code===Y.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=ao(e.inputSchema)??e.inputSchema,i=await na(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=oa(a);throw new K(Y.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new K(Y.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=ao(e.outputSchema),s=await na(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=oa(i);throw new K(Y.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(b=>setTimeout(b,u));let d=await n.taskStore.getTask(c);if(!d)throw new K(Y.InternalError,`Task ${c} not found during polling`);l=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(en(Ea)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ea,async e=>{switch(e.params.ref.type){case"ref/prompt":return Bw(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Vw(e),this.handleResourceCompletion(e,e.params.ref);default:throw new K(Y.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new K(Y.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new K(Y.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ni;let s=qr(n.argsSchema)?.[e.params.argument.name];if(!Qh(s))return ni;let i=P$(s);if(!i)return ni;let a=await i(e.params.argument.value,e.params.context);return N$(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return ni;throw new K(Y.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ni;let s=await o(e.params.argument.value,e.params.context);return N$(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(en(_a)),this.server.assertCanSetRequestHandler(en(va)),this.server.assertCanSetRequestHandler(en(xa)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_a,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(va,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(xa,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new K(Y.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new K(Y.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(en($a)),this.server.assertCanSetRequestHandler(en(ka)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($a,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?bj(r.argsSchema):void 0}))})),this.server.setRequestHandler(ka,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new K(Y.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new K(Y.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=ao(n.argsSchema),s=await na(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=oa(c);throw new K(Y.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:En(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=En(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let l=c instanceof gt?c._def?.innerType:c;return Qh(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){em(e);let u={title:r,description:n,inputSchema:z$(o),outputSchema:z$(s),annotations:i,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&em(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=En(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=En(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(tm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!tm(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},yj={type:"object",properties:{}};ni={completion:{values:[],hasMore:!1}}});function _j(t){return jw.parse(JSON.parse(t))}function D$(t){return JSON.stringify(t)+`
993
+ `}var wj,Tc,U$=O(()=>{mo();wj=10*1024*1024,Tc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??wj}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
994
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),_j(r)}clear(){this._buffer=void 0}}});import Z$ from"node:process";var Ec,q$=O(()=>{U$();Ec=class{constructor(e=Z$.stdin,r=Z$.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new Tc({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=D$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var F$,B$=O(()=>{F$=[]});var Q$={};jo(Q$,{AUTHORING_MCP_SERVER_NAME:()=>W$,AUTHORING_MCP_SERVER_VERSION:()=>J$,AUTHORING_RESOURCES:()=>kj,AUTHORING_TOOLS:()=>$j,AUTHORING_TOOLS_PUBLIC:()=>X$,buildAuthoringMcpServer:()=>Y$,runAuthoringMcpServer:()=>Sj});import{promises as vj}from"node:fs";import{resolve as V$}from"node:path";function G$(){return K$??=import("../mcp/grounding.js").then(e=>e,()=>null),K$}function Ve(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function xj(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(s=>s.hookId).filter(s=>typeof s=="string"):null}catch{return null}}async function Y$(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let h=await or(t.baseUrl);if(!h)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:h.baseUrl,token:h.token}}let r=t.grounding??{},n=await G$(),o=null;if(n)try{let h=await e();o={surface:"mcp-authoring",baseUrl:h.baseUrl,token:h.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],c=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{c=(await n.listRecipesForSurface(o,i)).map(h=>({id:h.id,record_type:h.record_type,intent:h.intent}))}catch{c=[]}}let l=o?await xj(o,r):null,u=new Sc({name:W$,version:J$},n?{instructions:n.renderAuthoringInstructions({baseUrl:o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(h=>h.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let h=o;for(let f of a)u.registerPrompt(f.id,{title:f.name,description:f.description},async()=>{let y=await n.getMcpPromptSkill(h,f.id,r);if(!y)throw new Error(`unknown prompt: ${f.id}`);return{description:y.description,messages:[{role:"user",content:{type:"text",text:(y.prompts??[]).join(`
940
995
 
941
- `)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:h,token:f}=await e(),g=await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!g.ok)throw new Error(`catalog fetch failed: ${g.status}`);return Ve(await g.json())}),u.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:z.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:z.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:h,source:f})=>{let{baseUrl:g,token:w}=await e(),E=f?`?source=${encodeURIComponent(f)}`:"",R=await fetch(`${g}/v1/catalog/records/${encodeURIComponent(h)}${E}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(R.status===404)throw new Error(`unknown record type "${h}" \u2014 list them with catalog_get.`);if(!R.ok)throw new Error(`record anatomy fetch failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:z.array(z.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:z.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:h,source:f})=>{let{baseUrl:g,token:w}=await e(),E=new URLSearchParams({types:h.join(",")});f&&E.set("source",f);let R=await fetch(`${g}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(R.status===404)throw new Error(`none of those record types resolved: ${h.join(", ")} \u2014 list them with catalog_get.`);if(!R.ok)throw new Error(`common columns fetch failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:h,token:f}=await e(),g=await fetch(`${h}/v1/catalog/census`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!g.ok)throw new Error(`catalog census failed: ${g.status}`);return Ve(await g.json())}),u.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:z.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:z.enum(F$).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:z.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:h,kind:f,limit:g})=>{let{baseUrl:w,token:E}=await e(),R=new URLSearchParams({q:h});f&&R.set("kind",f),g!==void 0&&R.set("limit",String(g));let C=await fetch(`${w}/v1/catalog/objects?${R}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!C.ok)throw new Error(`catalog object search failed: ${C.status}`);return Ve(await C.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:z.enum(F$),externalId:z.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:h,externalId:f})=>{let{baseUrl:g,token:w}=await e(),E=await fetch(`${g}/v1/catalog/objects/${encodeURIComponent(h)}/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${h}:${f} \u2014 find it with search_catalog.`);if(!E.ok)throw new Error(`catalog object fetch failed: ${E.status}`);return Ve(await E.json())}),u.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:z.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:z.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:h,limit:f})=>{let{baseUrl:g,token:w}=await e(),E=new URLSearchParams({q:h});f!==void 0&&E.set("limit",String(f));let R=await fetch(`${g}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!R.ok)throw new Error(`kb search failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:z.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:h})=>{let{baseUrl:f,token:g}=await e(),w=await fetch(`${f}/v1/kb/document/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}});if(!w.ok&&w.status!==404)throw new Error(`kb document fetch failed: ${w.status}`);return Ve(await w.json())}),u.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:z.boolean().optional()}},async({recordsOnly:h})=>{let{baseUrl:f,token:g}=await e();return{content:[{type:"text",text:await Cr({baseUrl:f,token:g,recordsOnly:h})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:z.string(),event:z.string().optional(),template:z.enum(["require-field","enforce-format","blank"]).optional(),field:z.string().optional(),regex:z.string().optional(),source:z.string().optional(),id:z.string().optional()}},async h=>{let f=Qn("hook",{recordType:h.recordType,event:h.event,template:h.template,field:h.field,regex:h.regex,source:h.source,id:h.id});return Ve({path:f.relativePath,content:f.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:z.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:z.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:z.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:z.string().optional().describe("Target record type (defaults to the trigger record type)."),event:z.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:z.string().optional()}},async h=>{let f=Qn("conduit",{recordType:h.recordType,source:h.source,to:h.to,toRecordType:h.toRecordType,event:h.event,id:h.id});return Ve({path:f.relativePath,content:f.content})}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:z.string().describe("The extension TS source."),samplesDir:z.string().optional().describe('Samples directory (default "samples").')}},async({source:h,samplesDir:f})=>{let g=q$(process.cwd(),f??"samples"),w=await Vo(g),E=await Ri(h,w.map(C=>C.fixture)),R=E.filter(C=>!C.pass).length;return Ve({total:E.length,passed:E.length-R,results:E})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:z.string(),recordType:z.string(),event:z.string(),source:z.string().describe('Adapter id or "standalone".'),sourceCode:z.string().describe("The verbatim extension TS."),extensionKind:z.string().optional()}},async h=>{let{baseUrl:f,token:g}=await e(),E=await new re({baseUrl:f,token:g}).deploy({id:h.id,recordType:h.recordType,event:h.event,source:h.source,sourceCode:h.sourceCode,extensionKind:h.extensionKind});return Ve(E)}),u.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:z.string(),limit:z.number().int().positive().optional()}},async({id:h,limit:f})=>{let{baseUrl:g,token:w}=await e(),E=new re({baseUrl:g,token:w});return Ve({id:h,logs:await E.logs(h,f)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:h,token:f}=await e(),g=new re({baseUrl:h,token:f});return Ve(await g.appsList())}),u.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:z.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:z.string().optional().describe("Display name (defaults to the slug)."),description:z.string().optional().describe("Short description.")}},async({slug:h,name:f,description:g})=>{let{baseUrl:w,token:E}=await e(),R=new re({baseUrl:w,token:E});return Ve(await R.appsCreate({slug:h,name:f,description:g}))}),u.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:z.string().describe("App slug or id.")}},async({app:h})=>{let{baseUrl:f,token:g}=await e(),w=new re({baseUrl:f,token:g});return Ve(await w.appsPull(h))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:z.string().describe("App slug or id."),files:z.record(z.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:z.string().optional().describe("Short note stored with the revision.")}},async({app:h,files:f,note:g})=>{let{baseUrl:w,token:E}=await e(),R=new re({baseUrl:w,token:E});return Ve(await R.appsPush(h,f,{note:g}))});let d=z.object({name:z.string().describe("Field name (lowercase identifier)."),type:z.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:z.boolean().optional()}),y=z.object({slug:z.string().describe("Table slug; the physical table is cr_<slug>."),displayName:z.string().optional(),fields:z.array(d).describe("At least one field."),rowLevelOwner:z.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:h,token:f}=await e(),g=new re({baseUrl:h,token:f});return Ve(await g.tablesList())}),u.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:z.array(y),claimedBy:z.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:h,claimedBy:f})=>{let{baseUrl:g,token:w}=await e(),E=new re({baseUrl:g,token:w});return Ve(await E.tablesPlan({tables:h,claimedBy:f}))}),u.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:z.array(y),claimedBy:z.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:h,claimedBy:f})=>{let{baseUrl:g,token:w}=await e(),E=new re({baseUrl:g,token:w});return Ve(await E.tablesApply({tables:h,claimedBy:f}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async h=>{let{baseUrl:f,token:g}=await e(),E=await(await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${g}`,Accept:"application/json"}})).text();return{contents:[{uri:h.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async h=>{let{baseUrl:f,token:g}=await e(),w=await Cr({baseUrl:f,token:g});return{contents:[{uri:h.href,mimeType:"text/plain",text:w}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async h=>{let f=q$(process.cwd(),"samples"),g=[];try{g=(await yj.readdir(f)).filter(E=>E.endsWith(".json"))}catch{g=[]}let w=await Vo(f);return{contents:[{uri:h.href,mimeType:"application/json",text:JSON.stringify({files:g,samples:w.map(E=>E.fixture)},null,2)}]}}),u.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async h=>{let f=await V$(),g=[];if(f){let{baseUrl:w,token:E}=await e();g=await f.listRecipesForSurface({surface:"mcp-authoring",baseUrl:w,token:E},r)}return{contents:[{uri:h.href,mimeType:"application/json",text:JSON.stringify({recipes:g})}]}}),u}async function vj(t={}){let e=await G$(t),r=new Ec;await e.connect(r)}var F$,B$,H$,K$,W$,_j,wj,Y$=O(()=>{N$();D$();Kn();al();Si();Wn();gl();$l();Z$();F$=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];H$="turbobase-authoring",K$="0.1.0";W$=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],_j=[...W$,...U$],wj=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as sm}from"node:child_process";import{promises as xe}from"node:fs";import{homedir as xj}from"node:os";import{basename as Q$,dirname as ni,join as Er,relative as Rc,resolve as ve,sep as om}from"node:path";var $m=Ac(xm(),1),{program:Fj,createCommand:Bj,createArgument:Vj,createOption:Hj,CommanderError:Kj,InvalidArgumentError:Gj,InvalidOptionArgumentError:Wj,Command:km,Argument:Jj,Option:Yj,Help:Xj}=$m.default;al();Si();Wn();gl();hl();import{promises as ag}from"node:fs";function sg(t,e){return e===t?"same-type-merge":"different-type-mint"}var cg=4;function yl(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Jn(t,"id"),r=Jn(t,"on"),n=Jn(t,"source"),o=Jn(t,"recordType"),s=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=Jn(s,"source"),a=Jn(s,"recordType"),c=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i,toRecordType:a,cycleBudget:c?Number(c[1]):cg}}function Jn(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function o0(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function lg(t,e,r="fixture"){let n=e.name??r,o=[],s;try{s=yl(t)}catch(c){return{fixtureName:n,conduit:i0(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=o0(e),a=Object.entries(e.atlasLinks??{}).map(([c,l])=>({key:c,resolved:l}));try{let c=await Ei(t),u=!!(await Bo(c,i,{member:"when",timeoutMs:200})).whenResult;o.push({name:"from.when",status:u?"passed":"failed",detail:u?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let d=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${d} vs cycleBudget=${s.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),o.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),o.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!u)return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let y=await Bo(c,i,{member:"transform",timeoutMs:200}),h=y.effects.logs,f=y.effects.result;if(!f||typeof f!="object")throw new Error(`conduit ${s.id} transform returned no result (expected { patch, createdFrom? })`);let g=f,w=sg(s.fromRecordType,s.toRecordType),{wouldWriteBindings:E,masterAction:R}=s0(s,w,e);return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,transformResult:g,applyBranch:w,wouldWriteBindings:E,masterAction:R,logs:h}}catch(c){return{fixtureName:n,conduit:s,guards:o,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}}function s0(t,e,r){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:r.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function i0(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:cg}}async function ug(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function dg(t){let e=await ag.readFile(t,"utf8");return JSON.parse(e)}function pg(t){return ag.readFile(t,"utf8")}function fg(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;let n=[];n.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),n.push(`conduit: ${r.id}`),n.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${r.toSource}.${r.toRecordType}${r.on?` on=${r.on}`:""}`),n.push(""),n.push("guards (dispatch order):");for(let o of t.guards){let s=o.status==="passed"?"\u2713":o.status==="failed"?"\u2717":"\u2298";n.push(` ${s} ${o.name} [${o.status}] \u2014 ${o.detail}`)}if(n.push(""),n.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)n.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let o of t.atlasResolutions)n.push(` ${o.key} \u2192 ${o.resolved===null?"null (no Atlas link \u2014 noted)":o.resolved}`);if(!t.whenPassed)return n.push(""),n.push("transform: SKIPPED (from.when gate did not fire)."),n.join(`
942
- `);if(n.push(""),n.push("transform \u2192 patch:"),n.push(a0(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&n.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){n.push(""),n.push("conduit logs:");for(let o of t.logs)n.push(` [${o.level}] ${o.message}${o.meta?` ${JSON.stringify(o.meta)}`:""}`)}n.push(""),n.push(`apply-branch: ${t.applyBranch}`),n.push(` ${t.masterAction}`),n.push(""),n.push("bindings that WOULD be written (txn_source_link):");for(let o of t.wouldWriteBindings)n.push(` ${o.source} role=${o.role} external_id=${o.externalId??"null"} \u2014 ${o.why}`);return n.join(`
943
- `)}function a0(t,e){return t.split(`
996
+ `)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:h,token:f}=await e(),y=await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!y.ok)throw new Error(`catalog fetch failed: ${y.status}`);return Ve(await y.json())}),u.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:N.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:N.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:h,source:f})=>{let{baseUrl:y,token:v}=await e(),E=f?`?source=${encodeURIComponent(f)}`:"",R=await fetch(`${y}/v1/catalog/records/${encodeURIComponent(h)}${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(R.status===404)throw new Error(`unknown record type "${h}" \u2014 list them with catalog_get.`);if(!R.ok)throw new Error(`record anatomy fetch failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:N.array(N.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:N.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:h,source:f})=>{let{baseUrl:y,token:v}=await e(),E=new URLSearchParams({types:h.join(",")});f&&E.set("source",f);let R=await fetch(`${y}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(R.status===404)throw new Error(`none of those record types resolved: ${h.join(", ")} \u2014 list them with catalog_get.`);if(!R.ok)throw new Error(`common columns fetch failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:h,token:f}=await e(),y=await fetch(`${h}/v1/catalog/census`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!y.ok)throw new Error(`catalog census failed: ${y.status}`);return Ve(await y.json())}),u.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:N.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:N.enum(H$).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:N.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:h,kind:f,limit:y})=>{let{baseUrl:v,token:E}=await e(),R=new URLSearchParams({q:h});f&&R.set("kind",f),y!==void 0&&R.set("limit",String(y));let z=await fetch(`${v}/v1/catalog/objects?${R}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return Ve(await z.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:N.enum(H$),externalId:N.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:h,externalId:f})=>{let{baseUrl:y,token:v}=await e(),E=await fetch(`${y}/v1/catalog/objects/${encodeURIComponent(h)}/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${h}:${f} \u2014 find it with search_catalog.`);if(!E.ok)throw new Error(`catalog object fetch failed: ${E.status}`);return Ve(await E.json())}),u.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:N.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:N.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:h,limit:f})=>{let{baseUrl:y,token:v}=await e(),E=new URLSearchParams({q:h});f!==void 0&&E.set("limit",String(f));let R=await fetch(`${y}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});if(!R.ok)throw new Error(`kb search failed: ${R.status}`);return Ve(await R.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:N.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:h})=>{let{baseUrl:f,token:y}=await e(),v=await fetch(`${f}/v1/kb/document/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}});if(!v.ok&&v.status!==404)throw new Error(`kb document fetch failed: ${v.status}`);return Ve(await v.json())}),u.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:N.boolean().optional()}},async({recordsOnly:h})=>{let{baseUrl:f,token:y}=await e();return{content:[{type:"text",text:await zr({baseUrl:f,token:y,recordsOnly:h})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:N.string(),event:N.string().optional(),template:N.enum(["require-field","enforce-format","blank"]).optional(),field:N.string().optional(),regex:N.string().optional(),source:N.string().optional(),id:N.string().optional()}},async h=>{let f=ro("hook",{recordType:h.recordType,event:h.event,template:h.template,field:h.field,regex:h.regex,source:h.source,id:h.id});return Ve({path:f.relativePath,content:f.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:N.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:N.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:N.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:N.string().optional().describe("Target record type (defaults to the trigger record type)."),event:N.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:N.string().optional()}},async h=>{let f=ro("conduit",{recordType:h.recordType,source:h.source,to:h.to,toRecordType:h.toRecordType,event:h.event,id:h.id});return Ve({path:f.relativePath,content:f.content})}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:N.string().describe("The extension TS source."),samplesDir:N.string().optional().describe('Samples directory (default "samples").')}},async({source:h,samplesDir:f})=>{let y=V$(process.cwd(),f??"samples"),v=await Ho(y),E=await Ri(h,v.map(z=>z.fixture)),R=E.filter(z=>!z.pass).length;return Ve({total:E.length,passed:E.length-R,results:E})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:N.string(),recordType:N.string(),event:N.string(),source:N.string().describe('Adapter id or "standalone".'),sourceCode:N.string().describe("The verbatim extension TS."),extensionKind:N.string().optional()}},async h=>{let{baseUrl:f,token:y}=await e(),E=await new te({baseUrl:f,token:y}).deploy({id:h.id,recordType:h.recordType,event:h.event,source:h.source,sourceCode:h.sourceCode,extensionKind:h.extensionKind});return Ve(E)}),u.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:N.string(),limit:N.number().int().positive().optional()}},async({id:h,limit:f})=>{let{baseUrl:y,token:v}=await e(),E=new te({baseUrl:y,token:v});return Ve({id:h,logs:await E.logs(h,f)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:h,token:f}=await e(),y=new te({baseUrl:h,token:f});return Ve(await y.appsList())}),u.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:N.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:N.string().optional().describe("Display name (defaults to the slug)."),description:N.string().optional().describe("Short description.")}},async({slug:h,name:f,description:y})=>{let{baseUrl:v,token:E}=await e(),R=new te({baseUrl:v,token:E});return Ve(await R.appsCreate({slug:h,name:f,description:y}))}),u.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:N.string().describe("App slug or id.")}},async({app:h})=>{let{baseUrl:f,token:y}=await e(),v=new te({baseUrl:f,token:y});return Ve(await v.appsPull(h))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:N.string().describe("App slug or id."),files:N.record(N.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:N.string().optional().describe("Short note stored with the revision.")}},async({app:h,files:f,note:y})=>{let{baseUrl:v,token:E}=await e(),R=new te({baseUrl:v,token:E});return Ve(await R.appsPush(h,f,{note:y}))});let d=N.object({name:N.string().describe("Field name (lowercase identifier)."),type:N.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:N.boolean().optional()}),b=N.object({slug:N.string().describe("Table slug; the physical table is cr_<slug>."),displayName:N.string().optional(),fields:N.array(d).describe("At least one field."),rowLevelOwner:N.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:h,token:f}=await e(),y=new te({baseUrl:h,token:f});return Ve(await y.tablesList())}),u.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:N.array(b),claimedBy:N.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:h,claimedBy:f})=>{let{baseUrl:y,token:v}=await e(),E=new te({baseUrl:y,token:v});return Ve(await E.tablesPlan({tables:h,claimedBy:f}))}),u.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:N.array(b),claimedBy:N.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:h,claimedBy:f})=>{let{baseUrl:y,token:v}=await e(),E=new te({baseUrl:y,token:v});return Ve(await E.tablesApply({tables:h,claimedBy:f}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async h=>{let{baseUrl:f,token:y}=await e(),E=await(await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}})).text();return{contents:[{uri:h.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async h=>{let{baseUrl:f,token:y}=await e(),v=await zr({baseUrl:f,token:y});return{contents:[{uri:h.href,mimeType:"text/plain",text:v}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async h=>{let f=V$(process.cwd(),"samples"),y=[];try{y=(await vj.readdir(f)).filter(E=>E.endsWith(".json"))}catch{y=[]}let v=await Ho(f);return{contents:[{uri:h.href,mimeType:"application/json",text:JSON.stringify({files:y,samples:v.map(E=>E.fixture)},null,2)}]}}),u.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async h=>{let f=await G$(),y=[];if(f){let{baseUrl:v,token:E}=await e();y=await f.listRecipesForSurface({surface:"mcp-authoring",baseUrl:v,token:E},r)}return{contents:[{uri:h.href,mimeType:"application/json",text:JSON.stringify({recipes:y})}]}}),u}async function Sj(t={}){let e=await Y$(t),r=new Ec;await e.connect(r)}var H$,K$,W$,J$,X$,$j,kj,ek=O(()=>{M$();q$();Jn();ll();Si();Xn();bl();Sl();B$();H$=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];W$="turbobase-authoring",J$="0.1.0";X$=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],$j=[...X$,...F$],kj=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as am}from"node:child_process";import{promises as me}from"node:fs";import{homedir as Tj}from"node:os";import{basename as rk,dirname as Co,join as Rt,relative as Rc,resolve as $e,sep as im}from"node:path";var Sm=Ic(km(),1),{program:Kj,createCommand:Gj,createArgument:Wj,createOption:Jj,CommanderError:Yj,InvalidArgumentError:Xj,InvalidOptionArgumentError:Qj,Command:Tm,Argument:eL,Option:tL,Help:rL}=Sm.default;ll();Si();Xn();bl();gl();import{promises as ug}from"node:fs";function cg(t,e){return e===t?"same-type-merge":"different-type-mint"}var dg=4;function wl(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Qn(t,"id"),r=Qn(t,"on"),n=Qn(t,"source"),o=Qn(t,"recordType"),s=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=Qn(s,"source"),a=Qn(s,"recordType"),c=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i,toRecordType:a,cycleBudget:c?Number(c[1]):dg}}function Qn(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function cT(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function pg(t,e,r="fixture"){let n=e.name??r,o=[],s;try{s=wl(t)}catch(c){return{fixtureName:n,conduit:uT(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=cT(e),a=Object.entries(e.atlasLinks??{}).map(([c,l])=>({key:c,resolved:l}));try{let c=await Ei(t),u=!!(await Vo(c,i,{member:"when",timeoutMs:200})).whenResult;o.push({name:"from.when",status:u?"passed":"failed",detail:u?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let d=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${d} vs cycleBudget=${s.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),o.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),o.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!u)return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let b=await Vo(c,i,{member:"transform",timeoutMs:200}),h=b.effects.logs,f=b.effects.result;if(!f||typeof f!="object")throw new Error(`conduit ${s.id} transform returned no result (expected { patch, createdFrom? })`);let y=f,v=cg(s.fromRecordType,s.toRecordType),{wouldWriteBindings:E,masterAction:R}=lT(s,v,e);return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,transformResult:y,applyBranch:v,wouldWriteBindings:E,masterAction:R,logs:h}}catch(c){return{fixtureName:n,conduit:s,guards:o,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}}function lT(t,e,r){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:r.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function uT(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:dg}}async function fg(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function hg(t){let e=await ug.readFile(t,"utf8");return JSON.parse(e)}function mg(t){return ug.readFile(t,"utf8")}function gg(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;let n=[];n.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),n.push(`conduit: ${r.id}`),n.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${r.toSource}.${r.toRecordType}${r.on?` on=${r.on}`:""}`),n.push(""),n.push("guards (dispatch order):");for(let o of t.guards){let s=o.status==="passed"?"\u2713":o.status==="failed"?"\u2717":"\u2298";n.push(` ${s} ${o.name} [${o.status}] \u2014 ${o.detail}`)}if(n.push(""),n.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)n.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let o of t.atlasResolutions)n.push(` ${o.key} \u2192 ${o.resolved===null?"null (no Atlas link \u2014 noted)":o.resolved}`);if(!t.whenPassed)return n.push(""),n.push("transform: SKIPPED (from.when gate did not fire)."),n.join(`
997
+ `);if(n.push(""),n.push("transform \u2192 patch:"),n.push(dT(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&n.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){n.push(""),n.push("conduit logs:");for(let o of t.logs)n.push(` [${o.level}] ${o.message}${o.meta?` ${JSON.stringify(o.meta)}`:""}`)}n.push(""),n.push(`apply-branch: ${t.applyBranch}`),n.push(` ${t.masterAction}`),n.push(""),n.push("bindings that WOULD be written (txn_source_link):");for(let o of t.wouldWriteBindings)n.push(` ${o.source} role=${o.role} external_id=${o.externalId??"null"} \u2014 ${o.why}`);return n.join(`
998
+ `)}function dT(t,e){return t.split(`
944
999
  `).map(r=>e+r).join(`
945
- `)}var c0="2026-01-01",hg="2026-01-01T00:00:00.000Z";function l0(t,e){let r=t.trim().toLowerCase();return r==="boolean"||r==="bool"?!1:r==="smallint"||r==="integer"||r==="int"||r==="int2"||r==="int4"||r==="int8"||r==="bigint"||r==="serial"||r==="bigserial"?1:r==="numeric"||r==="decimal"||r==="real"||r==="double precision"||r==="float4"||r==="float8"||r==="money"?0:r==="date"?c0:r.startsWith("timestamp")?hg:r.startsWith("time")?"00:00:00":r==="json"||r==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:hg}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function u0(t){let e={};for(let r of t.columns)e[r.name]=l0(r.pgType,r.name);return e}function d0(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:u0(t)},expect:e.expect??"pass"}}function mg(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:d0(r,e)}))}import{promises as gg}from"node:fs";import{join as yg,relative as p0,sep as f0}from"node:path";var h0=67324752,m0=33639248,g0=101010256,y0=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function b0(t){let e=4294967295;for(let r=0;r<t.length;r++)e=y0[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function _0(t){let e=[];async function r(n){let o=await gg.readdir(n,{withFileTypes:!0});for(let s of o){let i=yg(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(p0(t,i).split(f0).join("/"))}}return await r(t),e.sort(),e}async function bg(t){let e=await _0(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await gg.readFile(yg(t,a)),u=b0(l),d=Buffer.alloc(30+c.length);d.writeUInt32LE(h0,0),d.writeUInt16LE(20,4),d.writeUInt16LE(0,6),d.writeUInt16LE(0,8),d.writeUInt32LE(u,14),d.writeUInt32LE(l.length,18),d.writeUInt32LE(l.length,22),d.writeUInt16LE(c.length,26),c.copy(d,30),r.push(d,l);let y=Buffer.alloc(46+c.length);y.writeUInt32LE(m0,0),y.writeUInt16LE(20,4),y.writeUInt16LE(20,6),y.writeUInt16LE(0,10),y.writeUInt32LE(u,16),y.writeUInt32LE(l.length,20),y.writeUInt32LE(l.length,24),y.writeUInt16LE(c.length,28),y.writeUInt32LE(o,42),c.copy(y,46),n.push(y),o+=d.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(g0,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:e.length}}function w0(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function Pi(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function v0(t){let e=_g(t,"from"),r=_g(t,"to");return{fromSource:e?Pi(e,"source"):void 0,fromRecordType:e?Pi(e,"recordType"):void 0,toSource:r?Pi(r,"source"):void 0,toRecordType:r?Pi(r,"recordType"):void 0}}function _g(t,e){let r=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!r)return null;let n=0,o=r.index+r[0].length-1;for(let s=o;s<t.length;s+=1){let i=t[s];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return t.slice(o+1,s)}return null}function x0(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,o=null,s=r;for(;s<t.length;s+=1){let c=t[s];if(o){c==="\\"?s+=1:c===o&&(o=null);continue}if(c==="'"||c==='"'||c==="`"){o=c;continue}if(c==="("||c==="{"||c==="[")n+=1;else if(c===")"||c==="}"||c==="]"){if(n===0)break;n-=1}else if(c===","&&n===0)break}let i=t.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function $0(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function k0(t){return/\bcreatedFrom\b/.test(t)}function wg(t){let e=w0(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:o,fromRecordType:s,toRecordType:i}=v0(t);n&&o&&n===o&&r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${s??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});let a=x0(t);if(a!==null){let l=/\bexternalId\b/.test(a),u=/\bfromSource\b/.test(a);!l&&!u&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}s&&i&&s!==i&&!k0(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${i}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${i} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let c=$0(t,"cycleBudget");return c!==void 0&&(c<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${c} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):c>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${c} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:r}}function vg(t,e,r={}){let n=r.warn??(a=>a),o=r.ok??(a=>a),s=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${o("ok")} \u2014 no warnings.`),i.join(`
1000
+ `)}var pT="2026-01-01",yg="2026-01-01T00:00:00.000Z";function fT(t,e){let r=t.trim().toLowerCase();return r==="boolean"||r==="bool"?!1:r==="smallint"||r==="integer"||r==="int"||r==="int2"||r==="int4"||r==="int8"||r==="bigint"||r==="serial"||r==="bigserial"?1:r==="numeric"||r==="decimal"||r==="real"||r==="double precision"||r==="float4"||r==="float8"||r==="money"?0:r==="date"?pT:r.startsWith("timestamp")?yg:r.startsWith("time")?"00:00:00":r==="json"||r==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:yg}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function hT(t){let e={};for(let r of t.columns)e[r.name]=fT(r.pgType,r.name);return e}function mT(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:hT(t)},expect:e.expect??"pass"}}function bg(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:mT(r,e)}))}import{promises as wg}from"node:fs";import{join as _g,relative as gT,sep as yT}from"node:path";var bT=67324752,wT=33639248,_T=101010256,vT=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function xT(t){let e=4294967295;for(let r=0;r<t.length;r++)e=vT[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function $T(t){let e=[];async function r(n){let o=await wg.readdir(n,{withFileTypes:!0});for(let s of o){let i=_g(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(gT(t,i).split(yT).join("/"))}}return await r(t),e.sort(),e}async function vg(t){let e=await $T(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await wg.readFile(_g(t,a)),u=xT(l),d=Buffer.alloc(30+c.length);d.writeUInt32LE(bT,0),d.writeUInt16LE(20,4),d.writeUInt16LE(0,6),d.writeUInt16LE(0,8),d.writeUInt32LE(u,14),d.writeUInt32LE(l.length,18),d.writeUInt32LE(l.length,22),d.writeUInt16LE(c.length,26),c.copy(d,30),r.push(d,l);let b=Buffer.alloc(46+c.length);b.writeUInt32LE(wT,0),b.writeUInt16LE(20,4),b.writeUInt16LE(20,6),b.writeUInt16LE(0,10),b.writeUInt32LE(u,16),b.writeUInt32LE(l.length,20),b.writeUInt32LE(l.length,24),b.writeUInt16LE(c.length,28),b.writeUInt32LE(o,42),c.copy(b,46),n.push(b),o+=d.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(_T,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:e.length}}function kT(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function Pi(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function ST(t){let e=xg(t,"from"),r=xg(t,"to");return{fromSource:e?Pi(e,"source"):void 0,fromRecordType:e?Pi(e,"recordType"):void 0,toSource:r?Pi(r,"source"):void 0,toRecordType:r?Pi(r,"recordType"):void 0}}function xg(t,e){let r=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!r)return null;let n=0,o=r.index+r[0].length-1;for(let s=o;s<t.length;s+=1){let i=t[s];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return t.slice(o+1,s)}return null}function TT(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,o=null,s=r;for(;s<t.length;s+=1){let c=t[s];if(o){c==="\\"?s+=1:c===o&&(o=null);continue}if(c==="'"||c==='"'||c==="`"){o=c;continue}if(c==="("||c==="{"||c==="[")n+=1;else if(c===")"||c==="}"||c==="]"){if(n===0)break;n-=1}else if(c===","&&n===0)break}let i=t.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function ET(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function RT(t){return/\bcreatedFrom\b/.test(t)}function $g(t){let e=kT(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:o,fromRecordType:s,toRecordType:i}=ST(t);n&&o&&n===o&&r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${s??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});let a=TT(t);if(a!==null){let l=/\bexternalId\b/.test(a),u=/\bfromSource\b/.test(a);!l&&!u&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}s&&i&&s!==i&&!RT(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${i}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${i} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let c=ET(t,"cycleBudget");return c!==void 0&&(c<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${c} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):c>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${c} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:r}}function kg(t,e,r={}){let n=r.warn??(a=>a),o=r.ok??(a=>a),s=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${o("ok")} \u2014 no warnings.`),i.join(`
946
1001
  `);for(let a of e.warnings)i.push(` ${n("WARN")} ${s(`[${a.rule}]`)} ${a.message}`),i.push(` ${s("\u2192 fix:")} ${a.fix}`);return i.push(`
947
1002
  lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
948
- `)}function xg(t){return t.cases.filter(e=>e.status==="failed").length}function Ko(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function S0(t){let e=xg(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${Ko(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${Ko(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${Ko(n.type)}"`:"";r.push(` <failure${i} message="${Ko(s)}">${Ko(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
1003
+ `)}function Sg(t){return t.cases.filter(e=>e.status==="failed").length}function Go(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function PT(t){let e=Sg(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${Go(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${Go(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${Go(n.type)}"`:"";r.push(` <failure${i} message="${Go(s)}">${Go(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
949
1004
  `)}
950
- `}function T0(t){let e={suite:t.name,tests:t.cases.length,failures:xg(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
951
- `}function Ai(t,e){return e==="junit"?S0(t):T0(t)}var bt={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",invert:"\x1B[7m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",grey:"\x1B[90m"},Ke={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},Yn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ct={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},$g=/\x1b\[[0-9;]*m/g;function br(t){return t.replace($g,"").length}function bl(t,e){return e<=0?1:Math.max(1,Math.ceil(br(t)/e))}function E0(){return process.env.NO_COLOR!=null&&process.env.NO_COLOR!==""?!1:process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0"?!0:process.env.TERM==="dumb"?!1:process.stdout.isTTY===!0}var _l=E0();function _t(){return _l}function wl(t){_l=t}function _r(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function zt(t,e){return _l?`${t}${e}${bt.reset}`:e}var k={bold:t=>zt(bt.bold,t),dim:t=>zt(bt.dim,t),red:t=>zt(bt.red,t),green:t=>zt(bt.green,t),yellow:t=>zt(bt.yellow,t),blue:t=>zt(bt.blue,t),magenta:t=>zt(bt.magenta,t),cyan:t=>zt(bt.cyan,t),grey:t=>zt(bt.grey,t)};var lt={success:t=>`${k.green("\u2713")} ${t}`,error:t=>`${k.red("\u2716")} ${t}`,warn:t=>`${k.yellow("\u26A0")} ${t}`,info:t=>`${k.dim("\xB7")} ${t}`,step:t=>`${k.cyan("\u25B8")} ${t}`},Nr={add:t=>k.green(`+ ${t}`),change:t=>k.yellow(`~ ${t}`),destroy:t=>k.red(`- ${t}`)},R0=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),P0=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),A0=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Xn(t){let e=t.toLowerCase();return R0.has(e)?k.green(t):P0.has(e)?k.red(t):A0.has(e)?k.yellow(t):t}function jr(t,e=[]){let r=Math.max(br(t),...e.map(br),0),n=r+2,o=k.cyan(Ct.v),s=a=>` ${a}${" ".repeat(r-br(a))} `,i=[k.cyan(`${Ct.tl}${Ct.h.repeat(n)}${Ct.tr}`),`${o}${k.bold(s(t))}${o}`];if(e.length){i.push(`${k.cyan(Ct.ml)}${k.dim(Ct.h.repeat(n))}${k.cyan(Ct.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(k.cyan(`${Ct.bl}${Ct.h.repeat(n)}${Ct.br}`)),i.join(`
952
- `)}function bn(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(l=>l.length)),i=[];for(let l=0;l<s;l+=1)i[l]=Math.max(0,...o.map(u=>br(u[l]??"")));let a=l=>{let u=l.map((d,y)=>{let h=d??"";return y===l.length-1?h:h+" ".repeat(Math.max(0,i[y]-br(h)))});return r+u.join(n)},c=[];e.head&&(c.push(a(e.head.map(l=>k.bold(l)))),c.push(a(e.head.map((l,u)=>k.dim("\u2500".repeat(i[u]??br(l)))))));for(let l of t)c.push(a(l));return c.join(`
953
- `)}function vl(t="the CLI for your Turbobase instance"){let e=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"];return`${_t()?e.map(n=>zt(bt.cyan,n)).join(`
1005
+ `}function AT(t){let e={suite:t.name,tests:t.cases.length,failures:Sg(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
1006
+ `}function Ai(t,e){return e==="junit"?PT(t):AT(t)}var bt={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",invert:"\x1B[7m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",grey:"\x1B[90m"},Ke={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},eo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ct={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Tg=/\x1b\[[0-9;]*m/g;function wr(t){return t.replace(Tg,"").length}function _l(t,e){return e<=0?1:Math.max(1,Math.ceil(wr(t)/e))}function IT(){return process.env.NO_COLOR!=null&&process.env.NO_COLOR!==""?!1:process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0"?!0:process.env.TERM==="dumb"?!1:process.stdout.isTTY===!0}var vl=IT();function wt(){return vl}function xl(t){vl=t}function _r(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function zt(t,e){return vl?`${t}${e}${bt.reset}`:e}var T={bold:t=>zt(bt.bold,t),dim:t=>zt(bt.dim,t),red:t=>zt(bt.red,t),green:t=>zt(bt.green,t),yellow:t=>zt(bt.yellow,t),blue:t=>zt(bt.blue,t),magenta:t=>zt(bt.magenta,t),cyan:t=>zt(bt.cyan,t),grey:t=>zt(bt.grey,t)};var lt={success:t=>`${T.green("\u2713")} ${t}`,error:t=>`${T.red("\u2716")} ${t}`,warn:t=>`${T.yellow("\u26A0")} ${t}`,info:t=>`${T.dim("\xB7")} ${t}`,step:t=>`${T.cyan("\u25B8")} ${t}`},jr={add:t=>T.green(`+ ${t}`),change:t=>T.yellow(`~ ${t}`),destroy:t=>T.red(`- ${t}`)},OT=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),CT=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),zT=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function to(t){let e=t.toLowerCase();return OT.has(e)?T.green(t):CT.has(e)?T.red(t):zT.has(e)?T.yellow(t):t}function Lr(t,e=[]){let r=Math.max(wr(t),...e.map(wr),0),n=r+2,o=T.cyan(Ct.v),s=a=>` ${a}${" ".repeat(r-wr(a))} `,i=[T.cyan(`${Ct.tl}${Ct.h.repeat(n)}${Ct.tr}`),`${o}${T.bold(s(t))}${o}`];if(e.length){i.push(`${T.cyan(Ct.ml)}${T.dim(Ct.h.repeat(n))}${T.cyan(Ct.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(T.cyan(`${Ct.bl}${Ct.h.repeat(n)}${Ct.br}`)),i.join(`
1007
+ `)}function wn(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(l=>l.length)),i=[];for(let l=0;l<s;l+=1)i[l]=Math.max(0,...o.map(u=>wr(u[l]??"")));let a=l=>{let u=l.map((d,b)=>{let h=d??"";return b===l.length-1?h:h+" ".repeat(Math.max(0,i[b]-wr(h)))});return r+u.join(n)},c=[];e.head&&(c.push(a(e.head.map(l=>T.bold(l)))),c.push(a(e.head.map((l,u)=>T.dim("\u2500".repeat(i[u]??wr(l)))))));for(let l of t)c.push(a(l));return c.join(`
1008
+ `)}function $l(t="the CLI for your Turbobase instance"){let e=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"];return`${wt()?e.map(n=>zt(bt.cyan,n)).join(`
954
1009
  `):e.join(`
955
1010
  `)}
956
- ${k.dim(` ${t}`)}`}var Nt=t=>{process.stderr.write(t)};function Ii(){return _t()&&process.stderr.isTTY===!0}function kg(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${k.dim("\u2591".repeat(e-n))}`}async function $e(t,e){let r=Ii(),n=0,o;r&&(Nt(Ke.hideCursor),o=setInterval(()=>{Nt(`${Ke.col0}${Ke.clearLine}${k.magenta(Yn[n++%Yn.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Nt(`${Ke.col0}${Ke.clearLine}${Ke.showCursor}`)};try{let i=await e();return s(),r&&Nt(`${lt.success(t)}
1011
+ ${T.dim(` ${t}`)}`}var Nt=t=>{process.stderr.write(t)};function Ii(){return wt()&&process.stderr.isTTY===!0}function Eg(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${T.dim("\u2591".repeat(e-n))}`}async function Se(t,e){let r=Ii(),n=0,o;r&&(Nt(Ke.hideCursor),o=setInterval(()=>{Nt(`${Ke.col0}${Ke.clearLine}${T.magenta(eo[n++%eo.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Nt(`${Ke.col0}${Ke.clearLine}${Ke.showCursor}`)};try{let i=await e();return s(),r&&Nt(`${lt.success(t)}
957
1012
  `),i}catch(i){throw s(),r&&Nt(`${lt.error(t)}
958
- `),i}}function xl(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=k.magenta(Yn[e%Yn.length]),l=k.cyan(r.stage),u=r.runStatus?` ${k.dim(`(${r.runStatus})`)}`:"",d=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${c} ${t} ${k.dim("\u25B8")} ${l}${u} ${kg(r.percent)} ${d}`},s=()=>{Nt(`${Ke.col0}${Ke.clearLine}${o()}`),n=!0},i=()=>{n&&Nt(`${Ke.col0}${Ke.clearLine}`),n=!1};Nt(Ke.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Nt(`${c}
959
- `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Nt(Ke.showCursor);let l=c.stage!=="failed",u=`${t} ${k.dim("\u25B8")} ${I0(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Nt(`${l?lt.success(u):lt.error(u)}
960
- `)},stop(){clearInterval(a),i(),Nt(Ke.showCursor)}}}function I0(t){return t==="completed"?k.green(t):t==="failed"?k.red(t):k.cyan(t)}function wr(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(g=>!g.disabled);if(s===-1){o(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:s,a=g=>{process.stderr.write(g)},c=process.stdin,l=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${k.bold(k.cyan("?"))} ${k.bold(t)}
961
- `),a(`${k.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
962
- `),a(Ke.hideCursor);let u=0,d=()=>{let g=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Ke.cursorUp(u)),a(Ke.clearToEnd));let w=0;for(let E=0;E<e.length;E+=1){let R=e[E],C=E===i,B=C?k.cyan("\u25B6"):" ",W=R.disabled?k.grey(R.label):C?k.bold(k.cyan(R.label)):R.label,He=R.description?` ${k.dim(R.description)}`:"",Xe=` ${B} ${W}${He}`;a(`\r${Xe}
963
- `),w+=bl(Xe,g)}u=w},y=()=>{c.removeListener("data",f),c.setRawMode?.(l??!1),c.pause(),a(Ke.showCursor)},h=g=>{let w=i;for(let E=0;E<e.length;E+=1)if(w=(w+g+e.length)%e.length,!e[w].disabled){i=w;return}},f=g=>{let w=g.toString("utf8");if(w===""||w==="q"){y(),a(`
964
- `),o(new Error("aborted"));return}if(w==="\r"||w===`
965
- `){let R=e[i];if(R.disabled)return;y(),n(R.value);return}if(w==="\x1B[A"||w==="k"){h(-1),d();return}if(w==="\x1B[B"||w==="j"){h(1),d();return}let E=Number(w);Number.isFinite(E)&&E>=1&&E<=e.length&&!e[E-1].disabled&&(i=E-1,d())};c.on("data",f),d()})}function Tg(t,e){return`${Xn(t)}${" ".repeat(Math.max(0,e-t.length))}`}var O0=t=>new Promise(e=>setTimeout(e,t));function Sg(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${Tg(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function Eg(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
966
- `)}),o=r.sleep??O0,s=r.intervalMs??2e3,i=await t.conduitEvents(e,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${e}.`),0;let a=0,c="";for(let u of[...i].reverse())n(Sg(u)),a+=1,u.updatedAt>c&&(c=u.updatedAt);if(!r.follow)return a;let l=r.maxPolls??Number.POSITIVE_INFINITY;for(let u=0;u<l;u+=1){await o(s);let d=await t.conduitEvents(e,{since:c||void 0,limit:200});for(let y of[...d].reverse())n(Sg(y)),a+=1,y.updatedAt>c&&(c=y.updatedAt)}return a}function C0(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Tg(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function Rg(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
967
- `)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(C0(o));return r(`
968
- binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}$l();function Ag(t){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var kl=".github/workflows/turbobase-release-deploy.yml",L0=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1013
+ `),i}}function kl(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=T.magenta(eo[e%eo.length]),l=T.cyan(r.stage),u=r.runStatus?` ${T.dim(`(${r.runStatus})`)}`:"",d=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${c} ${t} ${T.dim("\u25B8")} ${l}${u} ${Eg(r.percent)} ${d}`},s=()=>{Nt(`${Ke.col0}${Ke.clearLine}${o()}`),n=!0},i=()=>{n&&Nt(`${Ke.col0}${Ke.clearLine}`),n=!1};Nt(Ke.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Nt(`${c}
1014
+ `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Nt(Ke.showCursor);let l=c.stage!=="failed",u=`${t} ${T.dim("\u25B8")} ${NT(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Nt(`${l?lt.success(u):lt.error(u)}
1015
+ `)},stop(){clearInterval(a),i(),Nt(Ke.showCursor)}}}function NT(t){return t==="completed"?T.green(t):t==="failed"?T.red(t):T.cyan(t)}function vr(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(y=>!y.disabled);if(s===-1){o(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:s,a=y=>{process.stderr.write(y)},c=process.stdin,l=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${T.bold(T.cyan("?"))} ${T.bold(t)}
1016
+ `),a(`${T.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
1017
+ `),a(Ke.hideCursor);let u=0,d=()=>{let y=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Ke.cursorUp(u)),a(Ke.clearToEnd));let v=0;for(let E=0;E<e.length;E+=1){let R=e[E],z=E===i,V=z?T.cyan("\u25B6"):" ",J=R.disabled?T.grey(R.label):z?T.bold(T.cyan(R.label)):R.label,He=R.description?` ${T.dim(R.description)}`:"",Xe=` ${V} ${J}${He}`;a(`\r${Xe}
1018
+ `),v+=_l(Xe,y)}u=v},b=()=>{c.removeListener("data",f),c.setRawMode?.(l??!1),c.pause(),a(Ke.showCursor)},h=y=>{let v=i;for(let E=0;E<e.length;E+=1)if(v=(v+y+e.length)%e.length,!e[v].disabled){i=v;return}},f=y=>{let v=y.toString("utf8");if(v===""||v==="q"){b(),a(`
1019
+ `),o(new Error("aborted"));return}if(v==="\r"||v===`
1020
+ `){let R=e[i];if(R.disabled)return;b(),n(R.value);return}if(v==="\x1B[A"||v==="k"){h(-1),d();return}if(v==="\x1B[B"||v==="j"){h(1),d();return}let E=Number(v);Number.isFinite(E)&&E>=1&&E<=e.length&&!e[E-1].disabled&&(i=E-1,d())};c.on("data",f),d()})}function Pg(t,e){return`${to(t)}${" ".repeat(Math.max(0,e-t.length))}`}var jT=t=>new Promise(e=>setTimeout(e,t));function Rg(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${Pg(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function Ag(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
1021
+ `)}),o=r.sleep??jT,s=r.intervalMs??2e3,i=await t.conduitEvents(e,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${e}.`),0;let a=0,c="";for(let u of[...i].reverse())n(Rg(u)),a+=1,u.updatedAt>c&&(c=u.updatedAt);if(!r.follow)return a;let l=r.maxPolls??Number.POSITIVE_INFINITY;for(let u=0;u<l;u+=1){await o(s);let d=await t.conduitEvents(e,{since:c||void 0,limit:200});for(let b of[...d].reverse())n(Rg(b)),a+=1,b.updatedAt>c&&(c=b.updatedAt)}return a}function LT(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Pg(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function Ig(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
1022
+ `)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(LT(o));return r(`
1023
+ binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}Sl();function Cg(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var Tl=".github/workflows/turbobase-release-deploy.yml",ZT=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
969
1024
  # Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
970
1025
  #
971
1026
  # Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
@@ -1067,7 +1122,7 @@ jobs:
1067
1122
  --ref "\${{ github.sha }}" \\
1068
1123
  --project . \\
1069
1124
  --follow
1070
- `,M0=".github/workflows/turbobase-tables-plan.yml",D0=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1125
+ `,qT=".github/workflows/turbobase-tables-plan.yml",FT=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1071
1126
  # Turbobase table check \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
1072
1127
  #
1073
1128
  # Runs \`turbobase tables plan\` against your instance on every pull request. It
@@ -1142,14 +1197,14 @@ jobs:
1142
1197
  # field and at what type. Writes nothing to the instance either way.
1143
1198
  - name: Plan the declared tables
1144
1199
  run: turbobase tables plan .
1145
- `;function Ig(){return[{path:kl,content:L0}]}function Og(){return[{path:M0,content:D0}]}var U0=[".mcp.json"];function zg(t,e=U0){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
1200
+ `;function zg(){return[{path:Tl,content:ZT}]}function Ng(){return[{path:qT,content:FT}]}var BT=[".mcp.json"];function Lg(t,e=BT){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
1146
1201
  `).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(r)),o=e.filter(i=>!n.has(r(i)));return o.length===0?null:`${t===""||t.endsWith(`
1147
1202
  `)?t:`${t}
1148
1203
  `}
1149
1204
  # Added by the Turbobase scaffold.
1150
1205
  ${o.join(`
1151
1206
  `)}
1152
- `}var Z0=`# Turbobase Extensions \u2014 extension project
1207
+ `}var VT=`# Turbobase Extensions \u2014 extension project
1153
1208
 
1154
1209
  This directory authors **Turbobase extensions** (hooks today; conduits later)
1155
1210
  against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
@@ -1218,8 +1273,8 @@ order is the signal, and it is the part the product team reads first.
1218
1273
 
1219
1274
  Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
1220
1275
  updating a test. It is checked into the repo so the whole team sees it.
1221
- `,q0=JSON.stringify({mcpServers:{"turbobase-authoring":{type:"http",url:"__BASE_URL__/mcp/authoring",headers:{Authorization:"Bearer __PAT__"}},turbobase:{type:"http",url:"__BASE_URL__/mcp"}}},null,2)+`
1222
- `;function F0(t){return`---
1276
+ `,HT=JSON.stringify({mcpServers:{"turbobase-authoring":{type:"http",url:"__BASE_URL__/mcp/authoring",headers:{Authorization:"Bearer __PAT__"}},turbobase:{type:"http",url:"__BASE_URL__/mcp"}}},null,2)+`
1277
+ `;function KT(t){return`---
1223
1278
  name: generate-types
1224
1279
  description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
1225
1280
  ---
@@ -1230,7 +1285,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
1230
1285
 
1231
1286
  The OpenAPI half is cookie-session-gated, so a headless run with a stored token
1232
1287
  degrades to record shapes only and says so \u2014 that is expected, not a failure.
1233
- `}var B0=`---
1288
+ `}var GT=`---
1234
1289
  name: mock-test
1235
1290
  description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
1236
1291
  ---
@@ -1239,7 +1294,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
1239
1294
  self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
1240
1295
  against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
1241
1296
  fixture for each branch (a passing record and a rejecting record).
1242
- `,V0=`---
1297
+ `,WT=`---
1243
1298
  name: deploy
1244
1299
  description: Deploy a hook to your instance. Use only after mock-test is green.
1245
1300
  ---
@@ -1247,7 +1302,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
1247
1302
  Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
1248
1303
  /v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
1249
1304
  the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
1250
- `;function H0(t){return`# ${t} \u2014 Turbobase app
1305
+ `;function JT(t){return`# ${t} \u2014 Turbobase app
1251
1306
 
1252
1307
  This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
1253
1308
  same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
@@ -1432,7 +1487,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
1432
1487
  review, so what you write reaches the knowledge base and the product team instead
1433
1488
  of evaporating at the end of the session. Keep the section headings exactly as
1434
1489
  they are \u2014 the ingest finds entries by heading, not by filename.
1435
- `}var K0="---\nname: preview-app\ndescription: Run the app locally against the instance and check it in a browser. Use after editing the app, before pushing.\n---\n\nStart the dev server NON-BLOCKING (`npm run dev` detached) \u2014 a foreground dev\nserver hangs the session. It proxies `/rest`, `/realtime`, `/v1`, `/auth`,\n`/login` and `/_app` to the instance, so localhost behaves same-origin and the\nsession cookie applies.\n\n**The app is at `http://localhost:3000/a/<slug>/`, not `/`.** Vite serves under\n`base` in dev too; `/` 302s there. Probing `/` and reading the 302 as \"broken\" is\nthe easy mistake here.\n\nThen actually look at it. A build that compiles and a lint that passes prove the\ncode is well-formed, not that it runs: a guard that throws during render, a\nPostgREST embed that 400s because the FK doesn't exist on this instance, an empty\nstate standing in for a failed query \u2014 none of those move the build signal.\n\n- Unauthenticated `/a/<slug>/` returns 200 with the SPA shell, and so does a deep\n client route like `/a/<slug>/customers/42` (Vite's SPA fallback). A 500 means a\n component threw \u2014 fix it, don't ship it.\n- `/login` returns the INSTANCE's sign-in page through the proxy. The app itself\n has no login route and should never grow one.\n- If a list renders empty, check the network tab before assuming there's no data:\n a 400 from PostgREST and a genuinely empty table look identical on screen.\n- `permission denied for table <x>` (SQLSTATE `42501`) usually means NOT SIGNED\n IN, not a role problem: with no session cookie PostgREST answers as the\n anonymous role and every table denies. Load `/login` through the proxy and\n sign in before reading the error as an RLS grant issue.\n\nVite reads `vite.config.ts` and `.env` only at boot \u2014 restart after changing either.\n",G0=`---
1490
+ `}var YT="---\nname: preview-app\ndescription: Run the app locally against the instance and check it in a browser. Use after editing the app, before pushing.\n---\n\nStart the dev server NON-BLOCKING (`npm run dev` detached) \u2014 a foreground dev\nserver hangs the session. It proxies `/rest`, `/realtime`, `/v1`, `/auth`,\n`/login` and `/_app` to the instance, so localhost behaves same-origin and the\nsession cookie applies.\n\n**The app is at `http://localhost:3000/a/<slug>/`, not `/`.** Vite serves under\n`base` in dev too; `/` 302s there. Probing `/` and reading the 302 as \"broken\" is\nthe easy mistake here.\n\nThen actually look at it. A build that compiles and a lint that passes prove the\ncode is well-formed, not that it runs: a guard that throws during render, a\nPostgREST embed that 400s because the FK doesn't exist on this instance, an empty\nstate standing in for a failed query \u2014 none of those move the build signal.\n\n- Unauthenticated `/a/<slug>/` returns 200 with the SPA shell, and so does a deep\n client route like `/a/<slug>/customers/42` (Vite's SPA fallback). A 500 means a\n component threw \u2014 fix it, don't ship it.\n- `/login` returns the INSTANCE's sign-in page through the proxy. The app itself\n has no login route and should never grow one.\n- If a list renders empty, check the network tab before assuming there's no data:\n a 400 from PostgREST and a genuinely empty table look identical on screen.\n- `permission denied for table <x>` (SQLSTATE `42501`) usually means NOT SIGNED\n IN, not a role problem: with no session cookie PostgREST answers as the\n anonymous role and every table denies. Load `/login` through the proxy and\n sign in before reading the error as an RLS grant issue.\n\nVite reads `vite.config.ts` and `.env` only at boot \u2014 restart after changing either.\n",XT=`---
1436
1491
  name: ship-app
1437
1492
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
1438
1493
  ---
@@ -1475,7 +1530,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
1475
1530
  non-text, so images and fonts belong in the build pipeline or object storage, not
1476
1531
  the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
1477
1532
  project root and DO travel \u2014 deploy reads them.
1478
- `;function W0(t){return`---
1533
+ `;function QT(t){return`---
1479
1534
  name: record-learning
1480
1535
  description: Append to INSTANCE-LEARNINGS.md or TURBOBASE-FEEDBACK.md. Use the MOMENT you establish a fact about how this instance is set up, or the platform costs you time \u2014 in the same change, not at the end of the task and not when asked.
1481
1536
  ---
@@ -1520,7 +1575,7 @@ the product team acts on first, so it is maintained with the entries.
1520
1575
 
1521
1576
  Do not reword the three headings. The deploy-side ingest recognises entries by
1522
1577
  heading, not by filename, so a renamed section is a finding nobody receives.
1523
- `}function J0(t){return`# What this instance's source system actually does
1578
+ `}function e0(t){return`# What this instance's source system actually does
1524
1579
 
1525
1580
  Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
1526
1581
  Written for the knowledge base, and **everything here is verified against real
@@ -1616,7 +1671,7 @@ finding has not been handed to the knowledge base yet.
1616
1671
  \`turbobase skills push\` writes these as DRAFT rules. Nothing is injected
1617
1672
  until an admin publishes them. -->
1618
1673
 
1619
- `}function Y0(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
1674
+ `}function t0(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
1620
1675
 
1621
1676
  Everything below cost time or produced a wrong result. Not speculation, and not
1622
1677
  a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
@@ -1672,7 +1727,7 @@ Expected / happened / cost / fix.
1672
1727
 
1673
1728
  <!-- Rank the findings above by how much time each would have saved. Position is
1674
1729
  the signal \u2014 1 is the biggest win. -->
1675
- `}function X0(t,e){let r=e?`
1730
+ `}function r0(t,e){let r=e?`
1676
1731
  # INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
1677
1732
  # --records focus a previous run stamped into the file, so a refresh never
1678
1733
  # narrows what an agent deliberately widened.
@@ -1685,35 +1740,35 @@ turbobase project grounding \${records:+--records "$records"} --query ${JSON.str
1685
1740
  # session still starts (types just won't refresh).
1686
1741
  set -euo pipefail
1687
1742
  turbobase project types -o ${t} >/dev/null 2>&1 || echo "turbobase: types refresh skipped (not signed in?)" >&2
1688
- ${r}`}var Q0=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
1689
- `,Cg="",eT=t=>`node_modules/
1743
+ ${r}`}var n0=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
1744
+ `,jg="",o0=t=>`node_modules/
1690
1745
 
1691
1746
  # Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
1692
1747
  .mcp.json
1693
1748
 
1694
1749
  .DS_Store
1695
- `;function Sl(t={}){let e=q0.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),r=!!t.appSlug,n=r?"src/types.ts":"types.ts",o=r?{slug:t.appSlug}:void 0,s=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:eT(r)},{path:"INSTANCE-LEARNINGS.md",content:J0(o)},{path:"TURBOBASE-FEEDBACK.md",content:Y0(o)},{path:".claude/settings.json",content:Q0},{path:".claude/skills/generate-types/SKILL.md",content:F0(n)},{path:".claude/skills/record-learning/SKILL.md",content:W0(o)},{path:".claude/hooks/session-start-refresh-types.sh",content:X0(n,o),executable:!0}];return r?[{path:"CLAUDE.md",content:H0(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:K0},{path:".claude/skills/ship-app/SKILL.md",content:G0},...Og()]:[{path:"CLAUDE.md",content:Z0},...s,{path:".claude/skills/mock-test/SKILL.md",content:B0},{path:".claude/skills/deploy/SKILL.md",content:V0},{path:"hooks/.gitkeep",content:Cg},{path:"samples/.gitkeep",content:Cg}]}import{promises as Lg}from"node:fs";import{resolve as oT}from"node:path";Si();Wn();var tT=t=>new Promise(e=>setTimeout(e,t));function Ng(t){return t.stage==="completed"||t.stage==="failed"}function rT(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function nT(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let s=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
1696
- `))r(i)}return n}async function Tl(t,e={}){let r=e.sink??(y=>{process.stdout.write(`${y}
1697
- `)}),n=e.sleep??tT,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(y=>r(rT(y))),a=e.onPoll,c="",l="",u=y=>{a?.(y),y.stage!==l&&i(y),c=nT(y,c,r),l=y.stage},d=await t();if(u(d),Ng(d))return d;for(let y=0;y<s;y+=1)if(await n(o),d=await t(),u(d),Ng(d))return d;return d}var S=t=>{process.stdout.write(`${t}
1750
+ `;function El(t={}){let e=HT.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),r=!!t.appSlug,n=r?"src/types.ts":"types.ts",o=r?{slug:t.appSlug}:void 0,s=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:o0(r)},{path:"INSTANCE-LEARNINGS.md",content:e0(o)},{path:"TURBOBASE-FEEDBACK.md",content:t0(o)},{path:".claude/settings.json",content:n0},{path:".claude/skills/generate-types/SKILL.md",content:KT(n)},{path:".claude/skills/record-learning/SKILL.md",content:QT(o)},{path:".claude/hooks/session-start-refresh-types.sh",content:r0(n,o),executable:!0}];return r?[{path:"CLAUDE.md",content:JT(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:YT},{path:".claude/skills/ship-app/SKILL.md",content:XT},...Ng()]:[{path:"CLAUDE.md",content:VT},...s,{path:".claude/skills/mock-test/SKILL.md",content:GT},{path:".claude/skills/deploy/SKILL.md",content:WT},{path:"hooks/.gitkeep",content:jg},{path:"samples/.gitkeep",content:jg}]}import{promises as Ug}from"node:fs";import{resolve as c0}from"node:path";Si();Xn();var s0=t=>new Promise(e=>setTimeout(e,t));function Mg(t){return t.stage==="completed"||t.stage==="failed"}function i0(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function a0(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let s=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
1751
+ `))r(i)}return n}async function Rl(t,e={}){let r=e.sink??(b=>{process.stdout.write(`${b}
1752
+ `)}),n=e.sleep??s0,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(b=>r(i0(b))),a=e.onPoll,c="",l="",u=b=>{a?.(b),b.stage!==l&&i(b),c=a0(b,c,r),l=b.stage},d=await t();if(u(d),Mg(d))return d;for(let b=0;b<s;b+=1)if(await n(o),d=await t(),u(d),Mg(d))return d;return d}var S=t=>{process.stdout.write(`${t}
1698
1753
  `)},Ee=t=>{process.stderr.write(`${t}
1699
- `)};function T(t){Ee(k.red(`turbobase: ${t}`)),process.exit(1)}var Go=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function jg(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&wl(!1)}async function oe(t){let e=await or(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await zr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";T(`not signed in to ${Ot(t)}.${n} Run \`turbobase auth login --base-url ${Ot(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&T("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),_r())try{let n=await wr("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await ki(n);let o=await or();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}T(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function Me(t,e,r){if(!(t instanceof Te)||t.status!==403)return;t.body?.error==="approval_required"&&T(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),T(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function El(t,e,r){let n=r?Number(r):void 0;if(Ii()){let s=xl(e),i;try{i=await Tl(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),T(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await Tl(t,{sink:S,intervalMs:n})}catch(s){T(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&T(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),S(`${e} ${o.stage}.`)}var sT=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function iT(t){try{let e=await Lg.readFile(t,"utf8");return sT.exec(e)?.[1]??null}catch{return null}}function Mg(t){t.command("adopt").description("Write the instance's app-developer adopt notes (what changed that this project must act on) to a file.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--since <version>","Only notes newer than this version. Defaults to the version recorded in ADOPT.md; omit both to get everything.").option("-o, --out <file>","Output file","ADOPT.md").action(async e=>{let{baseUrl:r,token:n}=await oe(e.baseUrl),o=oT(process.cwd(),e.out),s=e.since?.trim()||await iT(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),c=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});c.ok||T(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){S(`${r} ships no release notes to adopt from (nothing written).`);return}let u=l.releases.reduce((h,f)=>h+f.items.length,0);if(u===0){S(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${l.currentVersion?` (instance is on v${l.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let d=l.currentVersion??l.releases[0]?.version??"",y=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${d}. Re-run to refresh; delete this file once every line is done. -->
1700
-
1701
- `;await Lg.writeFile(o,y+l.markdown,"utf8"),S(`wrote ${o} \u2014 ${u} item(s) across ${l.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}.`)})}Wn();var Wo=["suggested_kb_edit","kb_correction"];var aT=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function cT(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var pD=new Map(aT.map(t=>[cT(t.heading),t]));function lT(t){return t.diff??!!t.dryRun}var uT={update_page:"append to the existing page",new_page:"create a NEW page"},vr=(t,e)=>` ${k.dim(t.padEnd(11))}${e}`,Ug=t=>t.ownerEmail??t.ownerId,Oi=t=>k.green(t?` + ${t}`:" +"),dT=t=>k.red(t?` - ${t}`:" -"),_n=t=>k.dim(` ${t}`),pT=` ${k.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Rl=80;function fT(t){let e=[pT];t.target?(e.push(_n(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(dT(`visibility: ${t.target.visibility}`)),e.push(Oi("visibility: admin"))):e.push(_n(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(_n("title, slug, evidence: untouched")),e.push(_n("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(_n("turbobase.document \xB7 new")),e.push(Oi(`title: ${t.pageTitle}`)),e.push(Oi("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(_n('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(_n('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
1702
- `);for(let n of r.slice(0,Rl))e.push(Oi(n?` ${n}`:""));return r.length>Rl&&e.push(k.yellow(` \u2026 ${r.length-Rl} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function hT(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${k.bold(n.pageTitle)}`),r.push(vr("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:k.dim("new \u2014 no existing page matches"))),r.push(vr("action",n.needsPageRef?k.red("SKIP \u2014 nothing is written"):uT[n.action])),n.needsPageRef){let a=[...new Set(i.map(c=>c.kb_page_ref?.trim()).filter(c=>!!c))];r.push(vr("unresolved",k.red((a.length>0?`no page matches ${a.map(c=>`"${c}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(r.push(vr("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let c=a.verdict?` ${k.dim(`\xB7 ${a.verdict}`)}`:"",l=a.kb_page_ref?` ${k.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${k.dim("\xB7")} ${a.title.trim()}${l}${c}`)}),r.push(vr("confidence",n.withdraws?k.red("WITHDRAWN from readers (text untouched)"):k.dim("untouched"))),n.supersedes&&r.push(vr("supersedes",k.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(vr("blocked",k.red(`unpublished work on this page belongs to ${Ug(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(vr("ambiguous",k.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),(n.similarTo?.length??0)>0){let a=(n.similarTo??[]).map(c=>{let l=t.findIndex(d=>d.key===c),u=l>=0?t[l]:void 0;return u?`#${l+1} "${u.pageTitle}"`:c});r.push(vr("similar",k.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&!n.needsPageRef&&r.push(...fT(n)),r.push("")}),r}function mT(t){let e=l=>t.filter(l).length,r=t.reduce((l,u)=>l+u.entries.length,0),n=e(l=>l.withdraws),o=e(l=>l.blockedBy!=null),s=e(l=>l.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${t.length-s} page(s)`,`${e(l=>l.action==="update_page"&&!l.needsPageRef)} appended`,`${e(l=>l.action==="new_page"&&!l.needsPageRef)} created (unpublished)`,...s>0?[k.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?k.red(`${n} page(s) WITHDRAWN from readers`):k.dim("no page withdrawn"),c=o>0?` \xB7 ${k.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${c}`}function gT(t,e){let r=new Map(e.map(o=>[o.key,o])),n=[];for(let o of t){let s=r.get(o.key),i=o.pageTitle||s?.pageTitle||o.key;if(o.skipped==="blocked_by_draft_owner"){n.push(`${k.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?Ug(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let c=[...new Set((s?.entries??[]).map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];n.push(`${k.yellow("skipped")} ${i} \u2014 `+(c.length>0?`no page matches ${c.map(l=>`"${l}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${k.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?k.green("created "):k.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${k.bold(o.documentId??"?")}`+(o.created?k.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${k.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${k.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${k.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Dg(t){if(t instanceof Te){let e=t.body;t.status===403&&e?.reason==="admin_required"&&T("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&T("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}Me(t,"extensions:deploy","learnings push-kb")}async function Zg(t,e=r=>new re(r)){t.section&&!Wo.includes(t.section.trim())&&T(`unknown --section "${t.section}" \u2014 expected one of ${Wo.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&T("--limit must be a positive integer.");let r=await oe(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s;try{s=await $e("reading the pending queue",()=>n.learningsPending(o))}catch(c){Dg(c),T(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(s.items.length===0){Ee(s.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${s.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(S(hT(s.items,{diff:lT(t)}).join(`
1703
- `)),S(mT(s.items)),t.dryRun){Ee(k.dim("dry run \u2014 nothing was written."));return}let i=s.items.filter(c=>!c.needsPageRef);if(i.length===0){Ee(k.yellow(`nothing to write \u2014 all ${s.items.length} group(s) are corrections with no page to correct. Fix the refs above (or write the pages) and re-run; the findings stay pending.`));return}let a=i.reduce((c,l)=>c+l.entries.length,0);if(!t.yes){if(!_r()){Ee(k.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await wr(`Push ${a} finding(s) into the knowledge base as ${i.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){Ee("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let c=await $e("writing pages",()=>n.learningsPushKb(s.planToken,o));S(gT(c.applied,s.items).join(`
1704
- `))}catch(c){if(c instanceof Te&&c.status===409){Ee(k.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),Ee(`re-run \`${Go} kb push\` to review the current plan.`),process.exitCode=2;return}Dg(c),Ee(k.red(`turbobase: ${c instanceof Error?c.message:String(c)}`)),process.exitCode=2}}Wn();function yT(t){return t.diff??!!t.dryRun}function bT(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?k.green("new rule"):k.yellow("amend rule"),i=n.targetPublished?` ${k.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${k.bold(n.slug)}${i}`),r.push(` ${n.name}`);for(let a of n.entries)r.push(` ${k.dim("\xB7")} ${k.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
1705
- `))r.push(` ${k.dim("|")} ${a}`)}r.push("")}),r}function _T(t){let e=t.reduce((o,s)=>o+s.entries.length,0),r=t.filter(o=>o.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(k.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function qg(t,e=r=>new re(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&T("--limit must be a positive integer.");let r=await oe(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{}},s;try{s=await $e("reading the pending rules",()=>n.rulesPending(o))}catch(a){Me(a,"extensions:deploy","read the pending rules"),T(`could not read the pending queue: ${a instanceof Error?a.message:String(a)}`)}if(s.items.length===0){Ee(s.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${s.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(S(bT(s.items,{diff:yT(t)}).join(`
1706
- `)),S(_T(s.items)),t.dryRun){Ee(k.dim("dry run \u2014 nothing was written."));return}let i=s.items.reduce((a,c)=>a+c.entries.length,0);if(!t.yes){if(!_r()){Ee(k.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await wr(`Push ${i} finding(s) as ${s.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land DISABLED; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){Ee("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await $e("writing the rules",()=>n.rulesPush(s.planToken,o))}catch(a){a instanceof Te&&a.status===409&&T("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),T(`push failed: ${a instanceof Error?a.message:String(a)}`)}S(k.green(`wrote ${s.items.length} draft rule(s).`)),Ee(k.dim("They are DRAFT and DISABLED \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{promises as Fg}from"node:fs";import{join as wT,relative as vT,resolve as xT,sep as $T}from"node:path";var kT=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),ST=new Set([".mcp.json",".env"]);function TT(t){return ST.has(t)||t.startsWith(".env.")&&t!==".env.example"}function ET(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function RT(t){return t.includes(0)}async function Bg(t){let e=xT(t),r={},n=[],o=[],s=[];async function i(a){let c=await Fg.readdir(a,{withFileTypes:!0});for(let l of c){let u=wT(a,l.name);if(l.isDirectory()){if(kT.has(l.name))continue;await i(u);continue}if(!l.isFile())continue;let d=vT(e,u).split($T).join("/");if(TT(l.name)){o.push(d);continue}let y=await Fg.readFile(u);if(!ET(y)){n.push(d);continue}RT(y)&&s.push(d),r[d]=y.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as PT}from"node:crypto";var AT="/_tb/app-assets",IT=16,OT=/^[0-9a-f]{32}$/;function Vg(){return PT(IT).toString("hex")}function CT(t){return OT.test(t)}function Hg(t){if(!CT(t))throw new Error(`not a build id: ${t}`);return`${AT}/${t}/`}var Kg=7;import Ci from"node:fs/promises";import Jo from"node:path";var Pl={esbuild:"0.28.1","isolated-vm":"6.1.2"},Al="@turbobase/isolated-vm-prebuilds";function Il(t,e){return`${t}-${e}`}function Ol(t=process.versions){return`abi${t.modules}`}var Gg=["darwin-x64","win32-arm64"];async function Wg(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Il(e,r),o=Jo.join(t.home,"node_modules"),s=Jo.join(o,...Al.split("/"),"prebuilds",n),i=Jo.join(o,"isolated-vm","prebuilds",n),a;try{a=await Ci.readdir(s)}catch{return[]}let c=[];await Ci.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=Jo.join(i,l);try{await Ci.copyFile(Jo.join(s,l),u,Ci.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as zT}from"node:os";import{join as Jg}from"node:path";import{promises as Cl}from"node:fs";function Xg(){let t=process.env.TURBOBASE_HOME??Jg(zT(),".turbobase");return{dir:t,file:Jg(t,"sandboxes.json")}}var NT={s:1e3,m:6e4,h:36e5,d:864e5};function jT(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*NT[e[2]]}function LT(t,e=Date.now()){return new Date(e+jT(t)).toISOString()}function MT(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function DT(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function UT(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var ZT="[REDACTED]",Yo=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},zl=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function qT(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new zl(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:ZT:n[o]=s}return n}function FT(t,e,r){return e.map(n=>qT(t,n,r))}var Yg=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),BT=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function VT(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Nl(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of BT)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=VT(t);if(!Yg.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Yg].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function HT(t,e=KT){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function KT(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function GT(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function WT(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function jl(){let{file:t}=Xg();try{let e=await Cl.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Qg(t){let{dir:e,file:r}=Xg();await Cl.mkdir(e,{recursive:!0}),await Cl.writeFile(r,`${JSON.stringify(t,null,2)}
1707
- `,{mode:384})}async function JT(t){let e=await jl();e.push(t),await Qg(e)}async function ey(t){let e=await jl(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Qg(e),n??null}async function zi(){return jl()}function Ll(t,e=Date.now()){let r=[],n=[];for(let o of t)MT(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function ty(t,e){Nl(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Yo(r);let n=DT(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>HT(l)))(e.fromTenant),i=GT(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=UT(l.rows,n),d=FT(l.table,u,l.classification);d.length>0&&await t.copyRows(i,l.table,d)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:LT(e.ttl,o),sampleFraction:n,url:WT(s,e.baseUrl)};return await JT(c),c}async function ry(t,e){Nl(t.target());let n=(await zi()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await ey(e),n):null}async function Ml(t,e=Date.now()){Nl(t.target());let r=await zi(),{expired:n}=Ll(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await ey(s.name),o.push(s)}return o}var Xo={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},ND=Object.keys(Xo).filter(t=>Xo[t].mintable);var MD=Xo.pat.prefix,YT=Object.entries(Xo).map(([t,e])=>[e.prefix,t]),XT=/^[A-Za-z0-9_-]{20,}$/;function QT(t){if(typeof t!="string")return null;for(let[e,r]of YT)if(t.startsWith(e)&&XT.test(t.slice(e.length)))return r;return null}function ny(t){return QT(t)==="pat"}var Qo="bundle.json",Ni="turbobase";function sy(t){let e;try{e=JSON.parse(t)}catch(c){throw new Error(`bundle.json is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=c=>Array.isArray(c)?c:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return eE(a)}function eE(t){let e=r=>(n,o)=>r(n)<r(o)?-1:r(n)>r(o)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(r=>r.id)),conduits:[...t.conduits].sort(e(r=>r.id)),sync:{fields:[...t.sync.fields].sort(e(oy)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(oy)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function oy(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function iy(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}async function $j(t,e){try{let r=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;let n=await r.json();return typeof n.token=="string"&&n.token.length>0?n.token:null}catch{return null}}async function kj(t){let e=await zr();e.length===0&&T("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),_r()||T("this command needs an explicit <base-url> in a non-interactive shell.");try{return await wr(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{T("cancelled.")}}async function Sj(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}async function Tj(t,e,r){let n=await tg({baseUrl:t,token:e}),o=(await zr()).length-1;if(S(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),!r)return;let s=await Sj(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(Ee(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),Ee(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),Ee(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?Ee(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):Ee(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function Ej(t){let e=await Ho(t),r=c=>{let l=new RegExp(`${c}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return l?l[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(e),o=r("id");if(n){let c=r("on"),l=r("recordType"),u=r("source");return(!o||!l||!c||!u)&&T(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:o,recordType:l,event:c,source:u,sourceCode:e,extensionKind:"conduit"}}let s=r("recordType"),i=r("event"),a=r("source")??"standalone";return(!o||!s||!i)&&T(`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`),{id:o,recordType:s,event:i,source:a,sourceCode:e,extensionKind:"hook"}}async function Ao(t,e,r,n){try{return await xe.access(t),"skipped"}catch{}return await xe.mkdir(ni(t),{recursive:!0}),await xe.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await xe.chmod(t,n),"wrote"}async function X$(t,e){if(Q$(t)!==".gitignore")return Ao(t,e.content,e.executable,e.mode);let r=await xe.readFile(t,"utf8").catch(()=>null);if(r===null)return Ao(t,e.content,e.executable,e.mode);let n=zg(r);return n===null?"skipped":(await xe.writeFile(t,n,"utf8"),"merged")}function em(t){if(t!==void 0){if(t==="junit"||t==="json")return t;T(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Rj(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function Pj(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function Aj(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function im({includeInternal:t=!0}={}){let e=new km;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.1.12").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",p=>p.command.parent?"":`${vl()}
1708
- `),e.hook("preAction",(p,m)=>{jg(e.opts(),m.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async p=>{let m=Ot(p.baseUrl);p.token||T(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
1709
- ${Go} auth login --base-url ${m} --token tb_pat_\u2026`),ny(p.token)||T("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await Tj(m,p.token,p.verify)}),r.command("status").description("Show the active instance (the no-`--base-url` default) and every stored sign-in.").action(async()=>{let p=await zr();if(p.length===0){S("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`.");return}let m=await or(),_=v=>!!m&&v.baseUrl===m.baseUrl;if(_t())S(bn(p.map(v=>[_(v)?k.green("*"):" ",k.bold(v.baseUrl),k.dim(v.updatedAt)]),{head:["","instance","updated"]}));else for(let v of p)S(`${_(v)?"* ":" "}${v.baseUrl} (updated ${v.updatedAt})`);m||Ee("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async p=>{let m=p??await kj("Pick the active instance:"),_=await ki(m);if(!_){let v=await zr();T(`no stored sign-in for ${Ot(m)}.`+(v.length?` Stored: ${v.map($=>$.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Ot(m)} --token tb_pat_\u2026\`.`)}S(`active instance \u2192 ${_.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async p=>{if(p.all){let v=await zr();for(let $ of v)await ul($.baseUrl);S(`removed ${v.length} stored sign-in${v.length===1?"":"s"}.`);return}let m=await ul(p.baseUrl);m||T(p.baseUrl?`no stored sign-in for ${Ot(p.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let _=await or();S(`signed out of ${m}.`+(_?` Active instance \u2192 ${_.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async p=>{let{baseUrl:m,token:_}=await oe(p.baseUrl),v;try{v=await Cr({baseUrl:m,token:_,recordsOnly:p.recordsOnly})}catch(b){let x=b instanceof Error?b.message:String(b);if(!p.recordsOnly&&/openapi\.json failed \(401/.test(x)){let I=await $j(m,_);if(I)try{v=await Cr({baseUrl:m,token:I,recordsOnly:!1});let j=ve(process.cwd(),p.out);await xe.writeFile(j,v,"utf8"),S(`wrote ${j} (${v.split(`
1710
- `).length} lines).`);return}catch{}Ee("types-gen: /v1/catalog/openapi.json needs a session \u2014 emitting record shapes only. To get the OpenAPI half headlessly, mint a PAT with the `data:read` scope (Settings \u203A Tokens); the CLI then exchanges it for a short-lived session automatically.");try{v=await Cr({baseUrl:m,token:_,recordsOnly:!0})}catch(j){T(`types generation failed: ${j instanceof Error?j.message:String(j)}`)}}else T(`types generation failed: ${x}`)}let $=ve(process.cwd(),p.out);await xe.writeFile($,v,"utf8"),S(`wrote ${$} (${v.split(`
1711
- `).length} lines).`)}),Mg(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async p=>{let{baseUrl:m,token:_}=await oe(p.baseUrl),v=new URLSearchParams;p.records&&v.set("records",p.records),p.query&&v.set("query",p.query);let $=v.toString(),b=await fetch(`${m}/v1/catalog/grounding${$?`?${$}`:""}`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});b.ok||T(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${b.status}`);let I=((await b.json()).markdown??"").trim(),j=ve(process.cwd(),p.out),M=p.records?` records=${p.records}`:"",D=`<!-- GENERATED by \`turbobase project grounding\` against ${m}${M} \u2014 do not edit; re-run to refresh. -->
1712
-
1713
- `;await xe.writeFile(j,D+(I?`${I}
1754
+ `)};function k(t){Ee(T.red(`turbobase: ${t}`)),process.exit(1)}var Wo=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Dg(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&xl(!1)}async function oe(t){let e=await or(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Nr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";k(`not signed in to ${Ot(t)}.${n} Run \`turbobase auth login --base-url ${Ot(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&k("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),_r())try{let n=await vr("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await ki(n);let o=await or();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}k(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function Ae(t,e,r){if(!(t instanceof _e)||t.status!==403)return;t.body?.error==="approval_required"&&k(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),k(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Pl(t,e,r){let n=r?Number(r):void 0;if(Ii()){let s=kl(e),i;try{i=await Rl(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),k(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await Rl(t,{sink:S,intervalMs:n})}catch(s){k(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&k(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),S(`${e} ${o.stage}.`)}var l0=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function u0(t){try{let e=await Ug.readFile(t,"utf8");return l0.exec(e)?.[1]??null}catch{return null}}function Zg(t){t.command("adopt").description("Write the instance's app-developer adopt notes (what changed that this project must act on) to a file.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--since <version>","Only notes newer than this version. Defaults to the version recorded in ADOPT.md; omit both to get everything.").option("-o, --out <file>","Output file","ADOPT.md").action(async e=>{let{baseUrl:r,token:n}=await oe(e.baseUrl),o=c0(process.cwd(),e.out),s=e.since?.trim()||await u0(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),c=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});c.ok||k(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){S(`${r} ships no release notes to adopt from (nothing written).`);return}let u=l.releases.reduce((h,f)=>h+f.items.length,0);if(u===0){S(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${l.currentVersion?` (instance is on v${l.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let d=l.currentVersion??l.releases[0]?.version??"",b=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${d}. Re-run to refresh; delete this file once every line is done. -->
1755
+
1756
+ `;await Ug.writeFile(o,b+l.markdown,"utf8"),S(`wrote ${o} \u2014 ${u} item(s) across ${l.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}.`)})}Xn();var Jo=["suggested_kb_edit","kb_correction"];var d0=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function p0(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var gD=new Map(d0.map(t=>[p0(t.heading),t]));function f0(t){return t.diff??!!t.dryRun}var h0={update_page:"append to the existing page",new_page:"create a NEW page"},xr=(t,e)=>` ${T.dim(t.padEnd(11))}${e}`,Fg=t=>t.ownerEmail??t.ownerId,Oi=t=>T.green(t?` + ${t}`:" +"),m0=t=>T.red(t?` - ${t}`:" -"),_n=t=>T.dim(` ${t}`),g0=` ${T.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Al=80;function y0(t){let e=[g0];t.target?(e.push(_n(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(m0(`visibility: ${t.target.visibility}`)),e.push(Oi("visibility: admin"))):e.push(_n(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(_n("title, slug, evidence: untouched")),e.push(_n("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(_n("turbobase.document \xB7 new")),e.push(Oi(`title: ${t.pageTitle}`)),e.push(Oi("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(_n('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(_n('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
1757
+ `);for(let n of r.slice(0,Al))e.push(Oi(n?` ${n}`:""));return r.length>Al&&e.push(T.yellow(` \u2026 ${r.length-Al} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function b0(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${T.bold(n.pageTitle)}`),r.push(xr("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:T.dim("new \u2014 no existing page matches"))),r.push(xr("action",n.needsPageRef?T.red("SKIP \u2014 nothing is written"):h0[n.action])),n.needsPageRef){let a=[...new Set(i.map(c=>c.kb_page_ref?.trim()).filter(c=>!!c))];r.push(xr("unresolved",T.red((a.length>0?`no page matches ${a.map(c=>`"${c}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(r.push(xr("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let c=a.verdict?` ${T.dim(`\xB7 ${a.verdict}`)}`:"",l=a.kb_page_ref?` ${T.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${T.dim("\xB7")} ${a.title.trim()}${l}${c}`)}),r.push(xr("confidence",n.withdraws?T.red("WITHDRAWN from readers (text untouched)"):T.dim("untouched"))),n.supersedes&&r.push(xr("supersedes",T.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(xr("blocked",T.red(`unpublished work on this page belongs to ${Fg(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(xr("ambiguous",T.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),(n.similarTo?.length??0)>0){let a=(n.similarTo??[]).map(c=>{let l=t.findIndex(d=>d.key===c),u=l>=0?t[l]:void 0;return u?`#${l+1} "${u.pageTitle}"`:c});r.push(xr("similar",T.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&!n.needsPageRef&&r.push(...y0(n)),r.push("")}),r}function w0(t){let e=l=>t.filter(l).length,r=t.reduce((l,u)=>l+u.entries.length,0),n=e(l=>l.withdraws),o=e(l=>l.blockedBy!=null),s=e(l=>l.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${t.length-s} page(s)`,`${e(l=>l.action==="update_page"&&!l.needsPageRef)} appended`,`${e(l=>l.action==="new_page"&&!l.needsPageRef)} created (unpublished)`,...s>0?[T.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?T.red(`${n} page(s) WITHDRAWN from readers`):T.dim("no page withdrawn"),c=o>0?` \xB7 ${T.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${c}`}function _0(t,e){let r=new Map(e.map(o=>[o.key,o])),n=[];for(let o of t){let s=r.get(o.key),i=o.pageTitle||s?.pageTitle||o.key;if(o.skipped==="blocked_by_draft_owner"){n.push(`${T.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?Fg(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let c=[...new Set((s?.entries??[]).map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];n.push(`${T.yellow("skipped")} ${i} \u2014 `+(c.length>0?`no page matches ${c.map(l=>`"${l}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${T.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?T.green("created "):T.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${T.bold(o.documentId??"?")}`+(o.created?T.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${T.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${T.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${T.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function qg(t){if(t instanceof _e){let e=t.body;t.status===403&&e?.reason==="admin_required"&&k("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&k("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}Ae(t,"extensions:deploy","learnings push-kb")}async function Bg(t,e=r=>new te(r)){t.section&&!Jo.includes(t.section.trim())&&k(`unknown --section "${t.section}" \u2014 expected one of ${Jo.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await oe(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s;try{s=await Se("reading the pending queue",()=>n.learningsPending(o))}catch(c){qg(c),k(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(s.items.length===0){Ee(s.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${s.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(S(b0(s.items,{diff:f0(t)}).join(`
1758
+ `)),S(w0(s.items)),t.dryRun){Ee(T.dim("dry run \u2014 nothing was written."));return}let i=s.items.filter(c=>!c.needsPageRef);if(i.length===0){Ee(T.yellow(`nothing to write \u2014 all ${s.items.length} group(s) are corrections with no page to correct. Fix the refs above (or write the pages) and re-run; the findings stay pending.`));return}let a=i.reduce((c,l)=>c+l.entries.length,0);if(!t.yes){if(!_r()){Ee(T.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await vr(`Push ${a} finding(s) into the knowledge base as ${i.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){Ee("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let c=await Se("writing pages",()=>n.learningsPushKb(s.planToken,o));S(_0(c.applied,s.items).join(`
1759
+ `))}catch(c){if(c instanceof _e&&c.status===409){Ee(T.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),Ee(`re-run \`${Wo} kb push\` to review the current plan.`),process.exitCode=2;return}qg(c),Ee(T.red(`turbobase: ${c instanceof Error?c.message:String(c)}`)),process.exitCode=2}}Xn();function v0(t){return t.diff??!!t.dryRun}function x0(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?T.green("new rule"):T.yellow("amend rule"),i=n.targetPublished?` ${T.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${T.bold(n.slug)}${i}`),r.push(` ${n.name}`);for(let a of n.entries)r.push(` ${T.dim("\xB7")} ${T.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
1760
+ `))r.push(` ${T.dim("|")} ${a}`)}r.push("")}),r}function $0(t){let e=t.reduce((o,s)=>o+s.entries.length,0),r=t.filter(o=>o.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(T.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function Vg(t,e=r=>new te(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await oe(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{}},s;try{s=await Se("reading the pending rules",()=>n.rulesPending(o))}catch(a){Ae(a,"extensions:deploy","read the pending rules"),k(`could not read the pending queue: ${a instanceof Error?a.message:String(a)}`)}if(s.items.length===0){Ee(s.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${s.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(S(x0(s.items,{diff:v0(t)}).join(`
1761
+ `)),S($0(s.items)),t.dryRun){Ee(T.dim("dry run \u2014 nothing was written."));return}let i=s.items.reduce((a,c)=>a+c.entries.length,0);if(!t.yes){if(!_r()){Ee(T.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await vr(`Push ${i} finding(s) as ${s.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land DISABLED; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){Ee("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await Se("writing the rules",()=>n.rulesPush(s.planToken,o))}catch(a){a instanceof _e&&a.status===409&&k("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),k(`push failed: ${a instanceof Error?a.message:String(a)}`)}S(T.green(`wrote ${s.items.length} draft rule(s).`)),Ee(T.dim("They are DRAFT and DISABLED \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{promises as Hg}from"node:fs";import{join as k0,relative as S0,resolve as T0,sep as E0}from"node:path";var R0=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),P0=new Set([".mcp.json",".env"]);function A0(t){return P0.has(t)||t.startsWith(".env.")&&t!==".env.example"}function I0(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function O0(t){return t.includes(0)}async function Kg(t){let e=T0(t),r={},n=[],o=[],s=[];async function i(a){let c=await Hg.readdir(a,{withFileTypes:!0});for(let l of c){let u=k0(a,l.name);if(l.isDirectory()){if(R0.has(l.name))continue;await i(u);continue}if(!l.isFile())continue;let d=S0(e,u).split(E0).join("/");if(A0(l.name)){o.push(d);continue}let b=await Hg.readFile(u);if(!I0(b)){n.push(d);continue}O0(b)&&s.push(d),r[d]=b.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as C0}from"node:crypto";var z0="/_tb/app-assets",N0=16,j0=/^[0-9a-f]{32}$/;function Gg(){return C0(N0).toString("hex")}function L0(t){return j0.test(t)}function Wg(t){if(!L0(t))throw new Error(`not a build id: ${t}`);return`${z0}/${t}/`}var Jg=7;import Ci from"node:fs/promises";import Yo from"node:path";var Il={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ol="@turbobase/isolated-vm-prebuilds";function Cl(t,e){return`${t}-${e}`}function zl(t=process.versions){return`abi${t.modules}`}var Yg=["darwin-x64","win32-arm64"];async function Xg(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Cl(e,r),o=Yo.join(t.home,"node_modules"),s=Yo.join(o,...Ol.split("/"),"prebuilds",n),i=Yo.join(o,"isolated-vm","prebuilds",n),a;try{a=await Ci.readdir(s)}catch{return[]}let c=[];await Ci.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=Yo.join(i,l);try{await Ci.copyFile(Yo.join(s,l),u,Ci.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as M0}from"node:os";import{join as Qg}from"node:path";import{promises as Nl}from"node:fs";function ty(){let t=process.env.TURBOBASE_HOME??Qg(M0(),".turbobase");return{dir:t,file:Qg(t,"sandboxes.json")}}var D0={s:1e3,m:6e4,h:36e5,d:864e5};function U0(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*D0[e[2]]}function Z0(t,e=Date.now()){return new Date(e+U0(t)).toISOString()}function q0(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function F0(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function B0(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var V0="[REDACTED]",Xo=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},jl=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function H0(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new jl(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:V0:n[o]=s}return n}function K0(t,e,r){return e.map(n=>H0(t,n,r))}var ey=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),G0=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function W0(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Ll(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of G0)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=W0(t);if(!ey.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...ey].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function J0(t,e=Y0){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Y0(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function X0(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function Q0(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Ml(){let{file:t}=ty();try{let e=await Nl.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function ry(t){let{dir:e,file:r}=ty();await Nl.mkdir(e,{recursive:!0}),await Nl.writeFile(r,`${JSON.stringify(t,null,2)}
1762
+ `,{mode:384})}async function eE(t){let e=await Ml();e.push(t),await ry(e)}async function ny(t){let e=await Ml(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await ry(e),n??null}async function zi(){return Ml()}function Dl(t,e=Date.now()){let r=[],n=[];for(let o of t)q0(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function oy(t,e){Ll(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Xo(r);let n=F0(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>J0(l)))(e.fromTenant),i=X0(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=B0(l.rows,n),d=K0(l.table,u,l.classification);d.length>0&&await t.copyRows(i,l.table,d)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:Z0(e.ttl,o),sampleFraction:n,url:Q0(s,e.baseUrl)};return await eE(c),c}async function sy(t,e){Ll(t.target());let n=(await zi()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await ny(e),n):null}async function Ul(t,e=Date.now()){Ll(t.target());let r=await zi(),{expired:n}=Dl(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await ny(s.name),o.push(s)}return o}var Qo={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},DD=Object.keys(Qo).filter(t=>Qo[t].mintable);var qD=Qo.pat.prefix,tE=Object.entries(Qo).map(([t,e])=>[e.prefix,t]),rE=/^[A-Za-z0-9_-]{20,}$/;function nE(t){if(typeof t!="string")return null;for(let[e,r]of tE)if(t.startsWith(e)&&rE.test(t.slice(e.length)))return r;return null}function iy(t){return nE(t)==="pat"}var es="bundle.json",Ni="turbobase";function cy(t){let e;try{e=JSON.parse(t)}catch(c){throw new Error(`bundle.json is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=c=>Array.isArray(c)?c:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return oE(a)}function oE(t){let e=r=>(n,o)=>r(n)<r(o)?-1:r(n)>r(o)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(r=>r.id)),conduits:[...t.conduits].sort(e(r=>r.id)),sync:{fields:[...t.sync.fields].sort(e(ay)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(ay)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function ay(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function ly(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}async function Ej(t,e){try{let r=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;let n=await r.json();return typeof n.token=="string"&&n.token.length>0?n.token:null}catch{return null}}async function Rj(t){let e=await Nr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),_r()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await vr(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function Pj(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}async function Aj(t,e,r){let n=await og({baseUrl:t,token:e}),o=(await Nr()).length-1;if(S(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),!r)return;let s=await Pj(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(Ee(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),Ee(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),Ee(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?Ee(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):Ee(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function Ij(t){let e=await Ko(t),r=c=>{let l=new RegExp(`${c}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return l?l[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(e),o=r("id");if(n){let c=r("on"),l=r("recordType"),u=r("source");return(!o||!l||!c||!u)&&k(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:o,recordType:l,event:c,source:u,sourceCode:e,extensionKind:"conduit"}}let s=r("recordType"),i=r("event"),a=r("source")??"standalone";return(!o||!s||!i)&&k(`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`),{id:o,recordType:s,event:i,source:a,sourceCode:e,extensionKind:"hook"}}async function zo(t,e,r,n){try{return await me.access(t),"skipped"}catch{}return await me.mkdir(Co(t),{recursive:!0}),await me.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await me.chmod(t,n),"wrote"}async function tk(t,e){if(rk(t)!==".gitignore")return zo(t,e.content,e.executable,e.mode);let r=await me.readFile(t,"utf8").catch(()=>null);if(r===null)return zo(t,e.content,e.executable,e.mode);let n=Lg(r);return n===null?"skipped":(await me.writeFile(t,n,"utf8"),"merged")}function rm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Oj(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function Cj(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function zj(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function cm({includeInternal:t=!0}={}){let e=new Tm;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.1.14").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",p=>p.command.parent?"":`${$l()}
1763
+ `),e.hook("preAction",(p,m)=>{Dg(e.opts(),m.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async p=>{let m=Ot(p.baseUrl);p.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
1764
+ ${Wo} auth login --base-url ${m} --token tb_pat_\u2026`),iy(p.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await Aj(m,p.token,p.verify)}),r.command("status").description("Show the active instance (the no-`--base-url` default) and every stored sign-in.").action(async()=>{let p=await Nr();if(p.length===0){S("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`.");return}let m=await or(),w=_=>!!m&&_.baseUrl===m.baseUrl;if(wt())S(wn(p.map(_=>[w(_)?T.green("*"):" ",T.bold(_.baseUrl),T.dim(_.updatedAt)]),{head:["","instance","updated"]}));else for(let _ of p)S(`${w(_)?"* ":" "}${_.baseUrl} (updated ${_.updatedAt})`);m||Ee("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async p=>{let m=p??await Rj("Pick the active instance:"),w=await ki(m);if(!w){let _=await Nr();k(`no stored sign-in for ${Ot(m)}.`+(_.length?` Stored: ${_.map($=>$.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Ot(m)} --token tb_pat_\u2026\`.`)}S(`active instance \u2192 ${w.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async p=>{if(p.all){let _=await Nr();for(let $ of _)await pl($.baseUrl);S(`removed ${_.length} stored sign-in${_.length===1?"":"s"}.`);return}let m=await pl(p.baseUrl);m||k(p.baseUrl?`no stored sign-in for ${Ot(p.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await or();S(`signed out of ${m}.`+(w?` Active instance \u2192 ${w.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async p=>{let{baseUrl:m,token:w}=await oe(p.baseUrl),_;try{_=await zr({baseUrl:m,token:w,recordsOnly:p.recordsOnly})}catch(g){let x=g instanceof Error?g.message:String(g);if(!p.recordsOnly&&/openapi\.json failed \(401/.test(x)){let A=await Ej(m,w);if(A)try{_=await zr({baseUrl:m,token:A,recordsOnly:!1});let C=$e(process.cwd(),p.out);await me.writeFile(C,_,"utf8"),S(`wrote ${C} (${_.split(`
1765
+ `).length} lines).`);return}catch{}Ee("types-gen: /v1/catalog/openapi.json needs a session \u2014 emitting record shapes only. To get the OpenAPI half headlessly, mint a PAT with the `data:read` scope (Settings \u203A Tokens); the CLI then exchanges it for a short-lived session automatically.");try{_=await zr({baseUrl:m,token:w,recordsOnly:!0})}catch(C){k(`types generation failed: ${C instanceof Error?C.message:String(C)}`)}}else k(`types generation failed: ${x}`)}let $=$e(process.cwd(),p.out);await me.writeFile($,_,"utf8"),S(`wrote ${$} (${_.split(`
1766
+ `).length} lines).`)}),Zg(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async p=>{let{baseUrl:m,token:w}=await oe(p.baseUrl),_=new URLSearchParams;p.records&&_.set("records",p.records),p.query&&_.set("query",p.query);let $=_.toString(),g=await fetch(`${m}/v1/catalog/grounding${$?`?${$}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});g.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let A=((await g.json()).markdown??"").trim(),C=$e(process.cwd(),p.out),L=p.records?` records=${p.records}`:"",D=`<!-- GENERATED by \`turbobase project grounding\` against ${m}${L} \u2014 do not edit; re-run to refresh. -->
1767
+
1768
+ `;await me.writeFile(C,D+(A?`${A}
1714
1769
  `:`(no grounding available yet)
1715
- `),"utf8"),S(`wrote ${j}${I?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${Wo.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",p=>Number.parseInt(p,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(p=>Zg(p)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, one per rule. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",p=>Number.parseInt(p,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--yes","Skip the confirmation (for scripted runs).").action(p=>qg(p));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async p=>{let m;try{m=Qn("hook",{recordType:p.record,event:p.event,template:p.template,field:p.field,regex:p.regex,source:p.source,id:p.id})}catch($){T($ instanceof Error?$.message:String($))}let _=ve(process.cwd(),m.relativePath);await Ao(_,m.content)==="skipped"&&T(`refusing to overwrite existing file: ${_}`),S(`wrote ${_}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async p=>{let m;try{m=Qn("conduit",{recordType:p.record,source:p.source,to:p.to,toRecordType:p.toRecord,event:p.event,id:p.id})}catch($){T($ instanceof Error?$.message:String($))}let _=ve(process.cwd(),m.relativePath);await Ao(_,m.content)==="skipped"&&T(`refusing to overwrite existing file: ${_}`),S(`wrote ${_}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(p,m)=>{let _=em(m.reporter),v=await Ho(ve(process.cwd(),p)),$=ve(process.cwd(),m.samples),b=await Vo($);b.length===0&&!_&&S(`no samples found under ${$} \u2014 add JSON fixtures to dry-run against.`);let x;try{x=await Ri(v,b.map(M=>M.fixture))}catch(M){T(`bundle failed: ${M instanceof Error?M.message:String(M)}`)}if(_){let M=Rj(x);S(Ai(M,_)),M.cases.some(D=>D.status==="failed")&&process.exit(1);return}let I=0;for(let M of x){let D=M.pass?k.green("PASS"):k.red("FAIL");M.pass||(I+=1);let ce=M.error?` (error: ${M.error})`:M.observed!==M.expected?` (expected ${M.expected}, observed ${M.observed})`:M.rejection?` (rejected: ${M.rejection.code??"rejected"})`:"";S(` ${D} ${M.name}${ce}`)}let j=`${x.length-I}/${x.length} sample(s) passed.`;S(`
1716
- ${I===0?k.green(j):k.yellow(j)}`),I>0&&process.exit(1)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE bundle (turbobase/bundle.json) to this env (sandbox|prod).").action(async(p,m)=>{if(m.to){let x=await tm(),{baseUrl:I,token:j}=await oe(m.baseUrl),M=new re({baseUrl:I,token:j});try{let D=await $e(`applying bundle to ${m.to}`,()=>M.configApply(x));S(`applied bundle to ${m.to}: +${D.applied.add} ~${D.applied.change} -${D.applied.destroy}`+(D.backfillsQueued.length?` (${D.backfillsQueued.length} backfill(s) queued)`:""))}catch(D){D instanceof Te&&D.status===403&&T("apply forbidden (403) \u2014 the stored PAT is not for an admin."),T(`bundle apply failed: ${D instanceof Error?D.message:String(D)}`)}return}p||T("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:_,token:v}=await oe(m.baseUrl),$=await Ej(ve(process.cwd(),p)),b=new re({baseUrl:_,token:v});try{let x=await $e(`deploying ${Q$(p)}`,()=>b.deploy($));_t()?S(jr("Deployed",[`${k.bold(x.id)} ${Xn(x.status)} ${k.dim(x.outcome)}`])):S(`deployed ${x.id} \u2192 status=${x.status} (${x.outcome}).`)}catch(x){x instanceof Te&&x.status===403&&T("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),T(`deploy failed: ${x instanceof Error?x.message:String(x)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").action(async(p,m,_)=>{let v=ve(process.cwd(),m??".");await xe.mkdir(v,{recursive:!0});let $=_.proposal??await g(v),{baseUrl:b,token:x}=await oe(_.baseUrl),I=new re({baseUrl:b,token:x}),j=!1;try{j=(await I.appsList()).some(ue=>ue.slug===p||ue.id===p)}catch(ue){Me(ue,"extensions:deploy","deploy"),T(`could not reach ${b}: ${ue instanceof Error?ue.message:String(ue)}`)}if(!j){_.create||T(`no app "${p}" on ${b} \u2014 create it with \`turbobase apps create ${p}\`, or pass --create.`);let ue=await $e(`creating app ${p}`,()=>u(b,x,{slug:p},{tolerateExisting:!0}));ue.existed||S(`created ${ue.slug??p}.`)}let M=ue=>xe.stat(Er(v,ue)).then(()=>!0).catch(()=>!1),D=p,ce=v,Q=_.build!==!1;if(Q&&!await M("package.json"))if(await M("index.html"))S("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Q=!1;else if(_.pull===!1)T(`${v} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ue=await $e(`pulling ${p}`,()=>d(b,x,p));D=ue.slug??p,await y(v,ue.files,!0),S(`pulled generated source (rev ${ue.rev}).`)}let ke;if(Q){let ue=Vg();if(ke={buildId:ue,assetBase:Hg(ue)},_.install!==!1&&!await M("node_modules")){S("installing dependencies\u2026");try{await E(["install"],v)}catch(Pt){T(`npm install failed: ${Pt instanceof Error?Pt.message:String(Pt)}`)}}S("building\u2026");try{await E(["run","build"],v,{TURBOBASE_ASSET_BASE:ke.assetBase})}catch(Pt){T(`build failed: ${Pt instanceof Error?Pt.message:String(Pt)}`)}await M("dist")||T(`no dist/ after build in ${v} \u2014 check the app's build script.`),ce=Er(v,"dist")}_.preview&&!ke&&T(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${D}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let he=await W(b,x,D,ce,_.entry,$,ke,_.preview?{label:_.label}:void 0);if(_.preview){let ue=he.previewUrl??"(no url returned)",Pt=he.expiresAt?new Date(he.expiresAt).toLocaleDateString():`${Kg} days`;_t()?S(jr("Preview deployed",[`${k.bold(D)} ${k.green(`v${he.version??"?"}`)} ${k.dim("not live")}`,`${k.bold(ue)}`,k.dim(`expires ${Pt}`)])):S(`preview ${D} v${he.version??"?"} \u2192 ${ue} (expires ${Pt}; /a/${D} unchanged).`),S(`next: turbobase apps promote ${D} ${he.previewId??"<preview-id>"} # make it live`),S(` turbobase apps preview discard ${he.previewId??"<preview-id>"}`);return}_t()?S(jr("Deployed",[`${k.bold(D)} ${k.green(`v${he.version??"?"}`)} ${k.dim(he.url??`/a/${D}`)}`])):S(`deployed ${D} \u2192 v${he.version??"?"} (${he.url??`/a/${D}`}).`),He(he)}),c.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m,_)=>{let{baseUrl:v,token:$}=await oe(_.baseUrl),b=await $e(`promoting ${m}`,()=>C(v,$,p,"promote",{previewId:m}));_t()?S(jr("Promoted",[`${k.bold(p)} ${k.green(`v${b.version??"?"}`)} ${k.dim(b.url??`/a/${p}`)}`])):S(`promoted ${p} \u2192 v${b.version??"?"} is now live at ${b.url??`/a/${p}`}.`),He(b)});let l=c.command("preview").description("Inspect and manage an app's open previews.");l.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:_,token:v}=await oe(m.baseUrl),$=await B(_,v,p);if($.previews.length===0){S(`no open previews for ${p}.`);return}for(let b of $.previews){let x=b.label?` ${b.label}`:"",I=b.expiresAt?new Date(b.expiresAt).toLocaleDateString():"?";S(`v${b.version} ${b.previewId}${x} ${b.url} (expires ${I})`)}}),l.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m,_)=>{let{baseUrl:v,token:$}=await oe(_.baseUrl);await $e(`discarding ${m}`,()=>C(v,$,p,"discard",{previewId:m})),S(`discarded ${m}.`)}),c.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:_,token:v}=await oe(m.baseUrl),$=await $e(`creating ${p}`,()=>u(_,v,{slug:p,name:m.name,description:m.description})),b=$.slug??p;_t()?S(jr("Created",[`${k.bold(b)} ${k.dim($.url??`/a/${b}`)}`])):S(`created ${b} (${$.url??`/a/${b}`}).`),S(`next: turbobase apps push ${b} . # store the source`),S(` turbobase apps deploy ${b} # build + go live`)});async function u(p,m,_,v={}){let $=`${p.replace(/\/+$/,"")}/v1/apps`,b;try{b=await fetch($,{method:"POST",headers:{Authorization:`Bearer ${m}`,"content-type":"application/json"},body:JSON.stringify({slug:_.slug,name:_.name??_.slug,description:_.description})})}catch(x){T(`create request failed: ${x instanceof Error?x.message:String(x)}`)}if(b.status===401&&T("create unauthorized (401) \u2014 re-run `turbobase auth login`."),b.status===403&&T("create forbidden (403) \u2014 the PAT is not for an admin."),b.status===409){if(v.tolerateExisting)return{slug:_.slug,existed:!0};T(`an app with slug "${_.slug}" already exists.`)}return b.ok||T(`create failed: HTTP ${b.status} ${(await b.text().catch(()=>"")).slice(0,200)}`),await b.json().catch(()=>({}))}async function d(p,m,_){let v=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/pull`,$;try{$=await fetch(v,{headers:{Authorization:`Bearer ${m}`}})}catch(b){T(`pull request failed: ${b instanceof Error?b.message:String(b)}`)}return $.status===401&&T("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),$.status===403&&T("pull forbidden (403) \u2014 the PAT is not for an admin."),$.status===404&&T(`no generated source for "${_}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),$.ok||T(`pull failed: HTTP ${$.status} ${(await $.text().catch(()=>"")).slice(0,200)}`),await $.json()}async function y(p,m,_){let v=ve(p),$=0;for(let[b,x]of Object.entries(m)){let I=ve(v,b);I!==v&&!I.startsWith(v+om)&&T(`refusing to write outside ${v}: ${b}`),_||await xe.stat(I).then(()=>!0).catch(()=>!1)&&T(`${I} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await xe.mkdir(ni(I),{recursive:!0}),await xe.writeFile(I,x,"utf8"),$+=1}return $}function h(p){let m=p.indexOf(","),_=p.startsWith("data:")?m>=0?p.slice(m+1):"":p;if(!_)return null;try{let v=Buffer.from(_,"base64");return v.length>0?new Uint8Array(v):null}catch{return null}}async function f(p,m,_){let v=ve(p),$=async(x,I)=>{let j=ve(v,x);j!==v&&!j.startsWith(v+om)&&T(`refusing to write outside ${v}: ${x}`),_||await xe.stat(j).then(()=>!0).catch(()=>!1)&&T(`${j} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await xe.mkdir(ni(j),{recursive:!0}),await xe.writeFile(j,I)},b=`# ${m.title||"App change request"}
1770
+ `),"utf8"),S(`wrote ${C}${A?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${Jo.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",p=>Number.parseInt(p,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(p=>Bg(p)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, one per rule. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",p=>Number.parseInt(p,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--yes","Skip the confirmation (for scripted runs).").action(p=>Vg(p));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async p=>{let m;try{m=ro("hook",{recordType:p.record,event:p.event,template:p.template,field:p.field,regex:p.regex,source:p.source,id:p.id})}catch($){k($ instanceof Error?$.message:String($))}let w=$e(process.cwd(),m.relativePath);await zo(w,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${w}`),S(`wrote ${w}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async p=>{let m;try{m=ro("conduit",{recordType:p.record,source:p.source,to:p.to,toRecordType:p.toRecord,event:p.event,id:p.id})}catch($){k($ instanceof Error?$.message:String($))}let w=$e(process.cwd(),m.relativePath);await zo(w,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${w}`),S(`wrote ${w}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(p,m)=>{let w=rm(m.reporter),_=await Ko($e(process.cwd(),p)),$=$e(process.cwd(),m.samples),g=await Ho($);g.length===0&&!w&&S(`no samples found under ${$} \u2014 add JSON fixtures to dry-run against.`);let x;try{x=await Ri(_,g.map(L=>L.fixture))}catch(L){k(`bundle failed: ${L instanceof Error?L.message:String(L)}`)}if(w){let L=Oj(x);S(Ai(L,w)),L.cases.some(D=>D.status==="failed")&&process.exit(1);return}let A=0;for(let L of x){let D=L.pass?T.green("PASS"):T.red("FAIL");L.pass||(A+=1);let ne=L.error?` (error: ${L.error})`:L.observed!==L.expected?` (expected ${L.expected}, observed ${L.observed})`:L.rejection?` (rejected: ${L.rejection.code??"rejected"})`:"";S(` ${D} ${L.name}${ne}`)}let C=`${x.length-A}/${x.length} sample(s) passed.`;S(`
1771
+ ${A===0?T.green(C):T.yellow(C)}`),A>0&&process.exit(1)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE bundle (turbobase/bundle.json) to this env (sandbox|prod).").action(async(p,m)=>{if(m.to){let x=await nm(),{baseUrl:A,token:C}=await oe(m.baseUrl),L=new te({baseUrl:A,token:C});try{let D=await Se(`applying bundle to ${m.to}`,()=>L.configApply(x));S(`applied bundle to ${m.to}: +${D.applied.add} ~${D.applied.change} -${D.applied.destroy}`+(D.backfillsQueued.length?` (${D.backfillsQueued.length} backfill(s) queued)`:""))}catch(D){D instanceof _e&&D.status===403&&k("apply forbidden (403) \u2014 the stored PAT is not for an admin."),k(`bundle apply failed: ${D instanceof Error?D.message:String(D)}`)}return}p||k("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:w,token:_}=await oe(m.baseUrl),$=await Ij($e(process.cwd(),p)),g=new te({baseUrl:w,token:_});try{let x=await Se(`deploying ${rk(p)}`,()=>g.deploy($));wt()?S(Lr("Deployed",[`${T.bold(x.id)} ${to(x.status)} ${T.dim(x.outcome)}`])):S(`deployed ${x.id} \u2192 status=${x.status} (${x.outcome}).`)}catch(x){x instanceof _e&&x.status===403&&k("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),k(`deploy failed: ${x instanceof Error?x.message:String(x)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").action(async(p,m,w)=>{let _=$e(process.cwd(),m??".");await me.mkdir(_,{recursive:!0});let $=w.proposal??await y(_),{baseUrl:g,token:x}=await oe(w.baseUrl),A=new te({baseUrl:g,token:x}),C=!1;try{C=(await A.appsList()).some(de=>de.slug===p||de.id===p)}catch(de){Ae(de,"extensions:deploy","deploy"),k(`could not reach ${g}: ${de instanceof Error?de.message:String(de)}`)}if(!C){w.create||k(`no app "${p}" on ${g} \u2014 create it with \`turbobase apps create ${p}\`, or pass --create.`);let de=await Se(`creating app ${p}`,()=>u(g,x,{slug:p},{tolerateExisting:!0}));de.existed||S(`created ${de.slug??p}.`)}let L=de=>me.stat(Rt(_,de)).then(()=>!0).catch(()=>!1),D=p,ne=_,U=w.build!==!1;if(U&&!await L("package.json"))if(await L("index.html"))S("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),U=!1;else if(w.pull===!1)k(`${_} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let de=await Se(`pulling ${p}`,()=>d(g,x,p));D=de.slug??p,await b(_,de.files,!0),S(`pulled generated source (rev ${de.rev}).`)}let fe;if(U){let de=Gg();if(fe={buildId:de,assetBase:Wg(de)},w.install!==!1&&!await L("node_modules")){S("installing dependencies\u2026");try{await E(["install"],_)}catch(Pt){k(`npm install failed: ${Pt instanceof Error?Pt.message:String(Pt)}`)}}S("building\u2026");try{await E(["run","build"],_,{TURBOBASE_ASSET_BASE:fe.assetBase})}catch(Pt){k(`build failed: ${Pt instanceof Error?Pt.message:String(Pt)}`)}await L("dist")||k(`no dist/ after build in ${_} \u2014 check the app's build script.`),ne=Rt(_,"dist")}w.preview&&!fe&&k(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${D}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let se=await J(g,x,D,ne,w.entry,$,fe,w.preview?{label:w.label}:void 0);if(w.preview){let de=se.previewUrl??"(no url returned)",Pt=se.expiresAt?new Date(se.expiresAt).toLocaleDateString():`${Jg} days`;wt()?S(Lr("Preview deployed",[`${T.bold(D)} ${T.green(`v${se.version??"?"}`)} ${T.dim("not live")}`,`${T.bold(de)}`,T.dim(`expires ${Pt}`)])):S(`preview ${D} v${se.version??"?"} \u2192 ${de} (expires ${Pt}; /a/${D} unchanged).`),S(`next: turbobase apps promote ${D} ${se.previewId??"<preview-id>"} # make it live`),S(` turbobase apps preview discard ${se.previewId??"<preview-id>"}`);return}wt()?S(Lr("Deployed",[`${T.bold(D)} ${T.green(`v${se.version??"?"}`)} ${T.dim(se.url??`/a/${D}`)}`])):S(`deployed ${D} \u2192 v${se.version??"?"} (${se.url??`/a/${D}`}).`),await He(se,_)}),c.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m,w)=>{let{baseUrl:_,token:$}=await oe(w.baseUrl),g=await Se(`promoting ${m}`,()=>z(_,$,p,"promote",{previewId:m}));wt()?S(Lr("Promoted",[`${T.bold(p)} ${T.green(`v${g.version??"?"}`)} ${T.dim(g.url??`/a/${p}`)}`])):S(`promoted ${p} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${p}`}.`),await He(g)});let l=c.command("preview").description("Inspect and manage an app's open previews.");l.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:w,token:_}=await oe(m.baseUrl),$=await V(w,_,p);if($.previews.length===0){S(`no open previews for ${p}.`);return}for(let g of $.previews){let x=g.label?` ${g.label}`:"",A=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";S(`v${g.version} ${g.previewId}${x} ${g.url} (expires ${A})`)}}),l.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m,w)=>{let{baseUrl:_,token:$}=await oe(w.baseUrl);await Se(`discarding ${m}`,()=>z(_,$,p,"discard",{previewId:m})),S(`discarded ${m}.`)}),c.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:w,token:_}=await oe(m.baseUrl),$=await Se(`creating ${p}`,()=>u(w,_,{slug:p,name:m.name,description:m.description})),g=$.slug??p;wt()?S(Lr("Created",[`${T.bold(g)} ${T.dim($.url??`/a/${g}`)}`])):S(`created ${g} (${$.url??`/a/${g}`}).`),S(`next: turbobase apps push ${g} . # store the source`),S(` turbobase apps deploy ${g} # build + go live`)});async function u(p,m,w,_={}){let $=`${p.replace(/\/+$/,"")}/v1/apps`,g;try{g=await fetch($,{method:"POST",headers:{Authorization:`Bearer ${m}`,"content-type":"application/json"},body:JSON.stringify({slug:w.slug,name:w.name??w.slug,description:w.description})})}catch(x){k(`create request failed: ${x instanceof Error?x.message:String(x)}`)}if(g.status===401&&k("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&k("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if(_.tolerateExisting)return{slug:w.slug,existed:!0};k(`an app with slug "${w.slug}" already exists.`)}return g.ok||k(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function d(p,m,w){let _=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/pull`,$;try{$=await fetch(_,{headers:{Authorization:`Bearer ${m}`}})}catch(g){k(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return $.status===401&&k("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),$.status===403&&k("pull forbidden (403) \u2014 the PAT is not for an admin."),$.status===404&&k(`no generated source for "${w}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),$.ok||k(`pull failed: HTTP ${$.status} ${(await $.text().catch(()=>"")).slice(0,200)}`),await $.json()}async function b(p,m,w){let _=$e(p),$=0;for(let[g,x]of Object.entries(m)){let A=$e(_,g);A!==_&&!A.startsWith(_+im)&&k(`refusing to write outside ${_}: ${g}`),w||await me.stat(A).then(()=>!0).catch(()=>!1)&&k(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await me.mkdir(Co(A),{recursive:!0}),await me.writeFile(A,x,"utf8"),$+=1}return $}function h(p){let m=p.indexOf(","),w=p.startsWith("data:")?m>=0?p.slice(m+1):"":p;if(!w)return null;try{let _=Buffer.from(w,"base64");return _.length>0?new Uint8Array(_):null}catch{return null}}async function f(p,m,w){let _=$e(p),$=async(x,A)=>{let C=$e(_,x);C!==_&&!C.startsWith(_+im)&&k(`refusing to write outside ${_}: ${x}`),w||await me.stat(C).then(()=>!0).catch(()=>!1)&&k(`${C} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await me.mkdir(Co(C),{recursive:!0}),await me.writeFile(C,A)},g=`# ${m.title||"App change request"}
1717
1772
 
1718
1773
  > Widget proposal \`${m.proposalId}\` \u2014 build this change, then ship it with
1719
1774
  > \`turbobase apps deploy ${m.appSlug}\`. The deploy stamps this proposal complete.
@@ -1723,23 +1778,34 @@ ${m.bodyMarkdown||"_No description provided._"}
1723
1778
  ## Screen context
1724
1779
 
1725
1780
  `+(m.screenshot?"A screenshot of the screen this request was filed from is saved beside this file as `proposal-screenshot.png`.\n":`No screenshot was captured with this request.
1726
- `);if(await $("PROPOSAL.md",b),m.screenshot){let x=h(m.screenshot);x&&await $("proposal-screenshot.png",x)}await $(Er(".turbobase","proposal.json"),`${JSON.stringify({proposalId:m.proposalId},null,2)}
1727
- `)}async function g(p){try{let m=await xe.readFile(Er(p,".turbobase","proposal.json"),"utf8"),_=JSON.parse(m);return typeof _.proposalId=="string"&&_.proposalId?_.proposalId:void 0}catch{return}}async function w(p,m,_,v,$,b){let x=new re({baseUrl:p,token:m});try{return await x.appsPush(_,v,{note:$,proposalId:b})}catch(I){if(I instanceof Te){let j=I.body;if(I.status===401&&T("push unauthorized (401) \u2014 re-run `turbobase auth login`."),I.status===403&&j?.error==="admin_required"&&T("push forbidden (403) \u2014 the PAT is not for an admin."),I.status===403&&Me(I,"extensions:deploy","push app source"),I.status===404&&T(`no app "${_}" on this instance \u2014 create it with \`turbobase apps create ${_}\`.`),I.status===413&&(j?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&T("push rejected: the request body exceeded the instance limit."),T(`push rejected: ${j?.error??"too large"} (limit ${j?.limit??"?"}).`)),I.status===400){let M=j?.path?` in ${j.path}`:"",D=j?.reason?` (${j.reason})`:"";T(`push rejected: ${j?.error??"bad request"}${D}${M}.`)}}T(`push failed: ${I instanceof Error?I.message:String(I)}`)}}function E(p,m,_){return new Promise((v,$)=>{let b=sm("npm",p,{cwd:m,stdio:"inherit",..._?{env:{...process.env,..._}}:{}});b.on("error",$),b.on("exit",x=>x===0?v():$(new Error(`npm ${p.join(" ")} exited ${x??"?"}`)))})}async function R(p,m,_,v){let $=`${p.replace(/\/+$/,"")}${_}`,b;try{b=await fetch($,{method:v.method,headers:{Authorization:`Bearer ${m}`,...v.body?{"content-type":"application/json"}:{}},...v.body?{body:JSON.stringify(v.body)}:{}})}catch(x){T(`request failed: ${x instanceof Error?x.message:String(x)}`)}if(b.status===401&&T("unauthorized (401) \u2014 re-run `turbobase auth login`."),b.status===403&&T("forbidden (403) \u2014 the PAT is not for an admin."),!b.ok){let x=await b.text().catch(()=>""),I=x.slice(0,300);try{let j=JSON.parse(x);I=j.message??j.error??I}catch{}T(`failed: HTTP ${b.status} ${I}`)}return await b.json().catch(()=>({}))}async function C(p,m,_,v,$){return await R(p,m,`/v1/apps/${encodeURIComponent(_)}/preview/${v}`,{method:"POST",body:$})}async function B(p,m,_){return{previews:(await R(p,m,`/v1/apps/${encodeURIComponent(_)}/previews`,{method:"GET"})).previews??[]}}async function W(p,m,_,v,$,b,x,I){let j;try{j=await $e(`zipping ${v}`,()=>bg(v))}catch(Q){T(`could not zip ${v}: ${Q instanceof Error?Q.message:String(Q)}`)}j.fileCount===0&&T(`${v} is empty \u2014 the build produced nothing.`);let M={Authorization:`Bearer ${m}`,"Content-Type":"application/zip"};$&&(M["x-app-entry"]=$),b&&(M["x-proposal-id"]=b),x&&(M["x-app-build-id"]=x.buildId,M["x-app-asset-base"]=x.assetBase),I&&(M["x-app-channel"]="preview",I.label&&(M["x-app-preview-label"]=encodeURIComponent(I.label)));let D=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/deploy`,ce;try{ce=await $e(`deploying ${_} (${j.fileCount} file${j.fileCount===1?"":"s"})`,()=>fetch(D,{method:"POST",headers:M,body:new Uint8Array(j.buffer)}))}catch(Q){T(`deploy request failed: ${Q instanceof Error?Q.message:String(Q)}`)}if(ce.status===401&&T("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),ce.status===403&&T("deploy forbidden (403) \u2014 the PAT is not for an admin."),ce.status===404&&T(`no app "${_}" on ${p} \u2014 create it with \`turbobase apps create ${_}\`.`),!ce.ok){let Q=await ce.text().catch(()=>""),ke=Q.slice(0,300);try{let he=JSON.parse(Q);ke=he.message??he.error??ke}catch{}T(`deploy failed: HTTP ${ce.status} ${ke}`)}return await ce.json().catch(()=>({}))}function He(p){let m=Ag(p);m&&S(m.level==="warn"?k.yellow(m.message):k.dim(m.message))}c.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(p,m,_)=>{let{baseUrl:v,token:$}=await oe(_.baseUrl);if(_.proposal){let j=new re({baseUrl:v,token:$}),M;try{M=await $e(`fetching proposal ${_.proposal}`,()=>j.appPullContext(_.proposal))}catch(he){Me(he,"extensions:deploy","pull proposal"),he instanceof Te&&he.status===404&&T(`no widget proposal "${_.proposal}" on ${v}.`),T(`could not fetch proposal ${_.proposal}: ${he instanceof Error?he.message:String(he)}`)}let D=await $e(`pulling ${M.appSlug}`,()=>d(v,$,M.appSlug)),ce=m??p,Q=ve(process.cwd(),ce??M.appSlug);await xe.mkdir(Q,{recursive:!0});let ke=await y(Q,D.files,!!_.force);await f(Q,M,!!_.force),S(`pulled ${ke} file${ke===1?"":"s"} \u2192 ${Q} (rev ${D.rev}), linked to proposal ${M.proposalId}.`),S(`next: cd ${Rc(process.cwd(),Q)||"."} && turbobase apps deploy ${M.appSlug}`);return}p||T("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let b=await $e(`pulling ${p}`,()=>d(v,$,p)),x=ve(process.cwd(),m??b.slug??p);await xe.mkdir(x,{recursive:!0});let I=await y(x,b.files,!!_.force);S(`pulled ${I} file${I===1?"":"s"} \u2192 ${x} (rev ${b.rev}).`),S(`next: cd ${Rc(process.cwd(),x)||"."} && turbobase apps deploy ${b.slug}`)}),c.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(p,m,_)=>{let v=ve(process.cwd(),m??p),$=await or(_.baseUrl).catch(()=>null),{scaffoldAppFiles:b,starterApp:x}=await Promise.resolve().then(()=>(vy(),wy)),I=_.title??p,j=b({slug:p,title:I,appTsx:x(I),instanceOrigin:$?.baseUrl});await xe.mkdir(v,{recursive:!0});let M=await y(v,j,!!_.force);if(S(`scaffolded ${M} file${M===1?"":"s"} \u2192 ${v}`),_.claude!==!1){let ce=Sl({baseUrl:$?.baseUrl,token:$?.token,appSlug:p}),Q=0;for(let ke of ce){let he=await X$(Er(v,ke.path),ke);(he==="wrote"||he==="merged")&&(Q+=1)}S(`wired Claude Code: ${Q} file${Q===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),$||Ee("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let D=Rc(process.cwd(),v)||".";S(`next: cd ${D} && npm install && npm run dev`),S(` turbobase apps create ${p}`),S(` turbobase apps push ${p} .`),S(` turbobase apps deploy ${p} .`)}),c.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:m,token:_}=await oe(p.baseUrl),v=new re({baseUrl:m,token:_}),$;try{$=await v.appsList()}catch(b){Me(b,"extensions:deploy","list apps"),T(`list apps failed: ${b instanceof Error?b.message:String(b)}`)}if(p.json)return S(JSON.stringify($,null,2));if($.length===0)return S("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");S(bn($.map(b=>[b.slug,b.name,b.deployed?"yes":"no",b.sourceRev===null?"\u2014":`rev ${b.sourceRev}`,b.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),c.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(p,m,_)=>{let v=ve(process.cwd(),m??".");await xe.stat(v).then(he=>he.isDirectory()).catch(()=>!1)||T(`${v} is not a directory.`);let{baseUrl:b,token:x}=await oe(_.baseUrl),I=_.proposal??await g(v),{files:j,skipped:M,secrets:D,unstorable:ce}=await Bg(v),Q=Object.keys(j).length;if(Q===0&&T(`no source files found under ${v} (build output and node_modules are skipped).`),ce.length>0){for(let he of ce)Ee(`${he} contains a NUL byte (U+0000), which cannot be stored.`);T(`push aborted: ${ce.length} ${ce.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let he of M)Ee(k.dim(`skipped binary file ${he}`));for(let he of D)Ee(k.dim(`skipped ${he} (holds credentials \u2014 never pushed)`));let ke=await $e(`pushing ${Q} file${Q===1?"":"s"}`,()=>w(b,x,p,j,_.note,I));S(`pushed ${ke.files} file${ke.files===1?"":"s"} \u2192 ${ke.slug} rev ${ke.rev} (source only, nothing deployed).`),S(`next: turbobase apps deploy ${ke.slug}`)}),o.command("plan").description("Diff the local bundle (turbobase/bundle.json) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let m=await tm(),{baseUrl:_,token:v}=await oe(p.baseUrl),$=new re({baseUrl:_,token:v}),b;try{b=await $e(`planning against ${p.to??_}`,()=>$.configPlan(m))}catch(x){T(`plan failed: ${x instanceof Error?x.message:String(x)}`)}Oj(b,p.to??_)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").action(async p=>{let m=await tm(),{baseUrl:_,token:v}=await oe(p.baseUrl),$=m.tenant??Cj(_),b=iy(p.confirm,$);b.ok||T(`promote refused (fail-closed): ${b.reason}`);let x=new re({baseUrl:_,token:v});try{let I=await $e(`promoting ${p.from} \u2192 ${p.to} (${$})`,()=>x.configApply(m));if(_t()){let j=[`${k.bold(`${p.from} \u2192 ${p.to}`)} ${k.dim($??"")}`,`${Nr.add(String(I.applied.add))} ${Nr.change(String(I.applied.change))} ${Nr.destroy(String(I.applied.destroy))}`];I.backfillsQueued.length&&j.push(k.dim(`${I.backfillsQueued.length} backfill(s) queued`)),S(jr("Promoted",j))}else S(`promoted ${p.from} \u2192 ${p.to} (${$}): +${I.applied.add} ~${I.applied.change} -${I.applied.destroy}`+(I.backfillsQueued.length?` (${I.backfillsQueued.length} backfill(s) queued)`:""))}catch(I){I instanceof Te&&I.status===403&&T("promote forbidden (403) \u2014 the stored PAT is not for an admin."),T(`promote failed: ${I instanceof Error?I.message:String(I)}`)}});let Xe=async(p,m)=>{let{baseUrl:_,token:v}=await oe(m.baseUrl),$=new re({baseUrl:_,token:v}),b=m.limit?Number(m.limit):void 0;if(m.follow){try{await Eg($,p,{follow:!0,limit:b,intervalMs:m.intervalMs?Number(m.intervalMs):void 0,sink:S})}catch(x){T(`logs --follow failed: ${x instanceof Error?x.message:String(x)}`)}return}try{let x=await $.logs(p,b);x.length===0&&S(`no logs for ${p}.`);for(let I of x)S(` [${I.level}] ${I.ts??""} ${I.message}`)}catch(x){T(`logs failed: ${x instanceof Error?x.message:String(x)}`)}};o.command("logs").argument("<id>","Extension id (default) or conduit id (with --follow)").description("Read an extension's logs; with --follow, stream a conduit's run ledger.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--limit <n>","Max log lines").option("--follow","Stream the conduit_event run ledger for the given conduit id.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(Xe),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(p,m)=>{let _=em(m.reporter),v=ve(process.cwd(),p),$=await Ho(v),b=wg($);_?S(Ai(Pj(p,b),_)):S(vg(p,b,{warn:k.yellow,ok:k.green,dim:k.dim})),m.ci&&b.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(p,m)=>{let _=em(m.reporter),v=await pg(ve(process.cwd(),p));if(m.against){m.against!=="sandbox"&&T(`unknown --against target '${m.against}' (only 'sandbox' is supported).`);try{await ug(yl(v))}catch(x){T(x instanceof Error?x.message:String(x))}return}m.fixture||T("replay needs a --fixture <file> (offline) or --against sandbox (online).");let $;try{$=await dg(ve(process.cwd(),m.fixture))}catch(x){T(`could not read fixture ${m.fixture}: ${x instanceof Error?x.message:String(x)}`)}let b=await lg(v,$,m.fixture);if(_){let x=Aj(b);S(Ai(x,_)),x.cases.some(I=>I.status==="failed")&&process.exit(1);return}S(fg(b,!!m.trace)),b.error&&process.exit(1)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async p=>{let{baseUrl:m,token:_}=await oe(p.baseUrl),v=new re({baseUrl:m,token:_});try{await Rg(v,{status:p.status,retry:p.retry,limit:p.limit?Number(p.limit):void 0,sink:S})}catch($){$ instanceof Te&&$.status===403&&T("forbidden (403) \u2014 binding --retry requires an admin PAT."),$ instanceof Te&&$.status===409&&T("binding is not retryable (only divergent/blocked bindings can be retried)."),T(`ext binding failed: ${$ instanceof Error?$.message:String($)}`)}}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(p,m)=>{let _=p.lastIndexOf("@"),v=_>0?p.slice(0,_):p,$=_>0?p.slice(_+1):void 0,b=dl();b||T(`marketplace not configured \u2014 set ${Gn} and ${Ti}.
1728
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=pl(b.registryUrl);x&&T(x);let{baseUrl:I,token:j}=await oe(m.baseUrl),M=new Fo(b),D;try{D=await $e(`fetching ${p}`,()=>M.fetchBundle(v,$))}catch(ue){T(`marketplace fetch failed for ${p}: ${ue instanceof Error?ue.message:String(ue)}`)}let ce=_i(D.manifest),Q=null;if(ce.length>0){if(!m.connection){let ue=ce.map(Pt=>Pt.source_system).join(", ");T(`${D.name}@${D.version} declares a connection input (source: ${ue}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}Q=m.connection}let ke=Ij(D.bundle,D.name,D.kind),he=new re({baseUrl:I,token:j});try{let ue=await $e(`installing ${D.name}@${D.version}`,()=>he.deploy({...ke,provenance:"marketplace",...Q?{connectionId:Q}:{}}));S(`installed ${D.name}@${D.version} \u2192 ${ue.id} (status=${ue.status}, ${ue.outcome})`+(Q?` bound to connection ${Q}.`:"."))}catch(ue){ue instanceof Te&&ue.status===403&&T("install forbidden (403) \u2014 the stored PAT is not for an admin."),T(`install failed: ${ue instanceof Error?ue.message:String(ue)}`)}}),o.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(p,m)=>{let _=dl();_||T(`marketplace not configured \u2014 set ${Gn} and ${Ti}.
1729
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let v=pl(_.registryUrl);v&&T(v);let $=ve(process.cwd(),p),b=await Ho($),x=/\bdefineConduit\s*[<(]/.test(b)?"conduit":"hook",I={};if(m.manifest){let D=ve(process.cwd(),m.manifest),ce;try{ce=await xe.readFile(D,"utf8")}catch{T(`manifest not found at ${m.manifest}.`)}let Q;try{Q=JSON.parse(ce)}catch{T(`manifest is not valid JSON: ${m.manifest}.`)}(typeof Q!="object"||Q===null||Array.isArray(Q))&&T("manifest must be a JSON object."),I=Q}try{Yc(I,b)}catch(D){D instanceof Or&&T(D.message),T(`manifest validation failed: ${D instanceof Error?D.message:String(D)}`)}let j=new Fo(_);try{await $e(`publishing ${m.name}@${m.pkgVersion}`,()=>j.publish({name:m.name,version:m.pkgVersion,kind:x,bundle:b,manifest:I}))}catch(D){D instanceof Te&&D.status===403&&T("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),D instanceof Te&&D.status===409&&T(`version already published \u2014 ${m.name}@${m.pkgVersion} exists. Bump the version.`),T(`publish failed: ${D instanceof Error?D.message:String(D)}`)}let M=_i(I);S(`published ${m.name}@${m.pkgVersion} (kind=${x}) to the marketplace.`),M.length>0&&S(` declares ${M.length} connection input(s): ${M.map(D=>D.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async p=>{let m=await or(p.baseUrl).catch(()=>null),_=Sl({baseUrl:m?.baseUrl,token:m?.token}),v=0,$=0,b=0;for(let x of _){let I=ve(process.cwd(),x.path),j=await X$(I,x);j==="wrote"?(v+=1,S(` wrote ${x.path}`)):j==="merged"?(b+=1,S(` merged ${x.path} (added the .mcp.json rule)`)):($+=1,S(` skipped ${x.path} (exists)`))}S(`
1730
- project init: ${v} written, ${b} merged, ${$} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${kl} (non-destructive).`).action(async()=>{let p=Ig(),m=0,_=0;for(let v of p){let $=ve(process.cwd(),v.path);await Ao($,v.content,v.executable)==="wrote"?(m+=1,S(` wrote ${v.path}`)):(_+=1,S(` skipped ${v.path} (exists)`))}S(`
1731
- project ci: ${m} written, ${_} skipped.`),m>0&&(S(`
1732
- Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),S("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),S("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async p=>{let{baseUrl:m,token:_}=await oe(p.baseUrl),v=new re({baseUrl:m,token:_}),$;try{$=await v.catalogRecords()}catch(M){M instanceof Te&&(M.status===401||M.status===403)&&T("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),T(`catalog fetch failed: ${M instanceof Error?M.message:String(M)}`)}if($.length===0){S("no records in the instance catalog \u2014 nothing to generate.");return}let b=ve(process.cwd(),p.out),x=mg($,{event:p.event}),I=0,j=0;for(let{recordType:M,fixture:D}of x){let ce=Er(b,`${M}.json`),Q=`${JSON.stringify(D,null,2)}
1733
- `;p.force?(await xe.mkdir(ni(ce),{recursive:!0}),await xe.writeFile(ce,Q,{mode:420}),I+=1,S(` wrote ${p.out}/${M}.json`)):await Ao(ce,Q)==="wrote"?(I+=1,S(` wrote ${p.out}/${M}.json`)):(j+=1,S(` skipped ${p.out}/${M}.json (exists \u2014 use --force to overwrite)`))}S(`
1734
- samples init: ${I} written, ${j} skipped.`)});let St=e.command("guardrails").description("Control PG\u2192source write-back with DENY rules (staged write rollout)."),Io=p=>[p.name,p.enabled?k.green("on"):k.dim("off"),p.source,p.record,p.when||k.dim("(always)"),p.note??""];St.command("list").description("List every write guardrail on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:m,token:_}=await oe(p.baseUrl),v=new re({baseUrl:m,token:_}),$;try{$=await v.guardrailsList()}catch(b){Me(b,"extensions:deploy","list guardrails"),T(`list guardrails failed: ${b instanceof Error?b.message:String(b)}`)}if(p.json)return S(JSON.stringify($,null,2));if($.length===0)return S(`no write guardrails \u2014 every record the admin entitlement allows is writable.
1735
- `+k.dim("create one with `turbobase guardrails create <name> --source <s> --when '\u2026'`"));S(bn($.map(Io),{head:["NAME","STATE","SOURCE","RECORD","WHEN","NOTE"]}))}),St.command("create <name>").description("Create a DENY rule. Blocks PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--when <expr>","Condition, e.g. 'recordType not_in customer,invoice' or 'record.amount gt 10000'. Omit to deny unconditionally.").option("--message <text>","What a blocked writer is told.").option("--note <text>","Why this rule exists \u2014 for whoever reads `list` later.").option("--disabled","Create the rule parked, so it takes effect only when enabled.").option("--confirm-freeze-all","Required for an unconditional '*'/'*' rule.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:_,token:v}=await oe(m.baseUrl),$=new re({baseUrl:_,token:v}),b;try{b=await $.guardrailCreate({name:p,source:m.source,record:m.record,...m.when?{when:m.when}:{},...m.message?{message:m.message}:{},...m.note?{note:m.note}:{},...m.disabled?{enabled:!1}:{},...m.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(x){Me(x,"extensions:deploy","create a guardrail"),T(`create guardrail failed: ${x instanceof Error?x.message:String(x)}`)}S(`${k.green("\u2713")} guardrail ${k.bold(b.name)} created${b.enabled?"":k.dim(" (parked \u2014 enable it to take effect)")}`),S(k.dim(` denies ${b.source}/${b.record}${b.when?` where ${b.when}`:" (always)"}`)),S(k.dim(` verify with: turbobase guardrails test --source ${b.source==="*"?"<source>":b.source} --record <record>`))}),St.command("edit <name>").description("Change a rule \u2014 most often widening its exception set as records are proven.").option("--when <expr>","New condition. Pass '' to make it unconditional.").option("--message <text>","What a blocked writer is told.").option("--note <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{m.when===void 0&&m.message===void 0&&m.note===void 0&&T("edit: nothing to change \u2014 pass --when, --message or --note.");let{baseUrl:_,token:v}=await oe(m.baseUrl),$=new re({baseUrl:_,token:v}),b;try{b=await $.guardrailUpdate(p,{...m.when!==void 0?{when:m.when}:{},...m.message!==void 0?{message:m.message}:{},...m.note!==void 0?{note:m.note}:{}})}catch(x){Me(x,"extensions:deploy","edit a guardrail"),T(`edit guardrail failed: ${x instanceof Error?x.message:String(x)}`)}S(`${k.green("\u2713")} guardrail ${k.bold(b.name)} updated`),S(k.dim(` denies ${b.source}/${b.record}${b.when?` where ${b.when}`:" (always)"}`))});for(let[p,m,_]of[["enable",!0,"enabled"],["disable",!1,"disabled"]])St.command(`${p} <name>`).description(m?"Arm a parked rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(v,$)=>{let{baseUrl:b,token:x}=await oe($.baseUrl),I=new re({baseUrl:b,token:x});try{await I.guardrailUpdate(v,{enabled:m})}catch(j){Me(j,"extensions:deploy",`${p} a guardrail`),T(`${p} guardrail failed: ${j instanceof Error?j.message:String(j)}`)}S(`${k.green("\u2713")} guardrail ${k.bold(v)} ${_}`),m||S(k.dim(" writes it was blocking are now permitted (subject to the other rules)."))});St.command("delete <name>").description("Remove a rule. This OPENS a write path \u2014 prefer `disable` if unsure.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:_,token:v}=await oe(m.baseUrl),$=new re({baseUrl:_,token:v});try{await $.guardrailDelete(p)}catch(b){Me(b,"extensions:deploy","delete a guardrail"),T(`delete guardrail failed: ${b instanceof Error?b.message:String(b)}`)}S(`${k.green("\u2713")} guardrail ${k.bold(p)} deleted`)}),St.command("test").description("Would a write be blocked? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--origin <origin>","Write origin to simulate ('user', 'agent').").option("--fields <json>","A candidate row as JSON, so `record.<column>` conditions can be decided.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async p=>{let m;if(p.fields)try{m=JSON.parse(p.fields)}catch(x){T(`--fields must be valid JSON: ${x instanceof Error?x.message:String(x)}`)}let{baseUrl:_,token:v}=await oe(p.baseUrl),$=new re({baseUrl:_,token:v}),b;try{b=await $.guardrailTest({source:p.source,record:p.record,...p.origin?{origin:p.origin}:{},...m?{fields:m}:{}})}catch(x){Me(x,"extensions:deploy","test guardrails"),T(`guardrails test failed: ${x instanceof Error?x.message:String(x)}`)}if(p.json)return S(JSON.stringify(b,null,2));b.allowed?S(`${k.green("\u2713")} ${p.source}/${p.record} \u2014 no guardrail blocks this write`):(S(`${k.red("\u2717")} ${p.source}/${p.record} \u2014 blocked by ${k.bold(b.blockedBy??"?")}`),b.message&&S(k.dim(` ${b.message}`))),b.undecided.length>0&&(S(k.yellow(` ${b.undecided.length} rule(s) need a row to decide: ${b.undecided.join(", ")}`)),S(k.dim(` re-run with --fields '{"\u2026":"\u2026"}' to evaluate them.`))),b.allowed||(process.exitCode=1)});let Bt=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),en=(p,m={})=>{let _=`${k.bold(p.table)} ${k.dim(p.displayName)}`;S(p.exists===!1?`${_} ${k.dim("(new)")}`:_);for(let v of p.fields){let $=[v.required?"required":null].filter(Boolean).join(", "),b=m.showClaimants&&v.claimedBy?.length?` ${k.dim(`\u2190 ${v.claimedBy.join(", ")}`)}`:"";S(` ${v.column.padEnd(28)} ${v.type}${$?` (${$})`:""}${b}`)}m.showClaimants&&p.claimants.length>1&&S(k.dim(` claimed by ${p.claimants.join(", ")}`))};function Mn(p){if(p instanceof Te&&p.status===409){let m=p.body;m?.error==="table_conflict"&&m.message&&(Ee(m.message),process.exit(1))}T(`tables: ${p instanceof Error?p.message:String(p)}`)}let Oo=async p=>{let m=Er(ve(process.cwd(),p),"public","turbobase.json"),_=await xe.readFile(m,"utf8").catch(()=>null);if(_===null)return null;let v;try{v=JSON.parse(_)}catch(b){T(`${m} is not valid JSON: ${b instanceof Error?b.message:String(b)}`)}let $=v.tables;return $===void 0?{tables:[],manifestPath:m}:(Array.isArray($)||T(`${m}: "tables" must be an array.`),{tables:$,manifestPath:m})};Bt.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:m,token:_}=await oe(p.baseUrl),v=new re({baseUrl:m,token:_}),$;try{$=await v.tablesList()}catch(b){Me(b,"extensions:deploy","list tables"),T(`list tables failed: ${b instanceof Error?b.message:String(b)}`)}if(p.json)return S(JSON.stringify($,null,2));if($.length===0)return S("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");S(bn($.map(b=>[b.table,b.displayName,String(b.fields.length),b.status,b.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Bt.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(p,m)=>{let _=await Oo(p??".");if(_||T(`no public/turbobase.json under ${ve(process.cwd(),p??".")}.`),_.tables.length===0)return S(`${_.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:v,token:$}=await oe(m.baseUrl),b=new re({baseUrl:v,token:$}),x;try{x=await $e("planning tables",()=>b.tablesPlan({claimedBy:m.as,tables:_.tables}))}catch(I){Me(I,"extensions:deploy","plan tables"),Mn(I)}S(`claiming as ${k.bold(x.claimedBy)}`);for(let I of x.tables)en(I,{showClaimants:!0});S(""),S(k.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Bt.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(p,m)=>{let _=await Oo(p??".");if(_||T(`no public/turbobase.json under ${ve(process.cwd(),p??".")}.`),_.tables.length===0)return S(`${_.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:v,token:$}=await oe(m.baseUrl),b=new re({baseUrl:v,token:$}),x;try{x=await $e("applying tables",()=>b.tablesApply({claimedBy:m.as,tables:_.tables}))}catch(I){Me(I,"extensions:deploy","apply tables"),Mn(I)}for(let I of x.tables)en(I,{showClaimants:!0});S(`applied ${x.tables.length} table${x.tables.length===1?"":"s"} as ${x.claimedBy}.`)}),Bt.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(p,m)=>[...m??[],p],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let _=m.field.map(I=>{let[j,M,D]=I.split(":");return(!j||!M)&&T(`--field "${I}" must be name:type[:required] (e.g. title:text:required).`),D!==void 0&&D!=="required"&&T(`--field "${I}": the third part may only be "required".`),{name:j,type:M,...D==="required"?{required:!0}:{}}}),{baseUrl:v,token:$}=await oe(m.baseUrl),b=new re({baseUrl:v,token:$}),x;try{x=await $e(`creating cr_${p}`,()=>b.tablesApply({tables:[{slug:p,displayName:m.name??p,fields:_,...m.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(I){Me(I,"extensions:deploy","create a table"),Mn(I)}for(let I of x.tables)en(I);S(""),S(k.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Bt.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{m.confirm!==p&&T(`drop refused: --confirm "${m.confirm}" does not match "${p}".`);let{baseUrl:_,token:v}=await oe(m.baseUrl),$=new re({baseUrl:_,token:v}),b;try{b=await $e(`dropping cr_${p}`,()=>$.tablesDrop(p,m.confirm))}catch(x){Me(x,"extensions:deploy","drop a table"),T(`drop failed: ${x instanceof Error?x.message:String(x)}`)}if(!b.removed)return S(`no table named "${p}" on this instance \u2014 nothing dropped.`);S(`dropped ${b.table} and every row in it.`)});let Co=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Co.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async p=>{process.env.TURBOBASE_SANDBOX="1";let m=rm(),_;try{_=await ty(m,{fromTenant:p.from,ttl:p.ttl,sample:p.sample,baseUrl:p.baseUrl})}catch(v){v instanceof Yo&&T(v.message),T(`sandbox create failed: ${v instanceof Error?v.message:String(v)}`)}S(`sandbox ${_.name} ready.`),S(` source: ${_.fromTenant} (sampled ${Math.round(_.sampleFraction*100)}%, redacted)`),S(` url: ${_.url}`),S(` expires: ${_.expiresAt}`)}),Co.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async p=>{let m=rm();await Ml(m).catch(()=>[]);let _;try{_=await ry(m,p)}catch(v){T(`sandbox destroy failed: ${v instanceof Error?v.message:String(v)}`)}_||T(`no sandbox named '${p}'.`),S(`destroyed sandbox ${_.name} (dropped ${_.database}).`)}),Co.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let p=rm(),m=await Ml(p).catch(()=>[]),_=await zi(),{active:v}=Ll(_);if(v.length===0)S("no active sandboxes.");else{for(let $ of v)S(` ${$.name} from=${$.fromTenant} expires=${$.expiresAt} ${$.url}`);S(`
1736
- ${v.length} active sandbox(es).`)}m.length>0&&S(`(reaped ${m.length} expired sandbox(es).)`)}),o.command("export").description("Snapshot the live instance into turbobase/bundle.json.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Ni).action(async p=>{let{baseUrl:m,token:_}=await oe(p.baseUrl),v=new re({baseUrl:m,token:_}),$;try{$=await $e("exporting instance config",()=>v.configExport())}catch(I){I instanceof Te&&(I.status===401||I.status===403)&&T("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),T(`ext export failed: ${I instanceof Error?I.message:String(I)}`)}let b=typeof $.serialized=="string"?$.serialized:`${JSON.stringify($.manifest??$,null,2)}
1737
- `,x=ve(process.cwd(),p.out,Qo);await xe.mkdir(ni(x),{recursive:!0}),await xe.writeFile(x,b,"utf8"),S(`wrote ${p.out}/${Qo} (${b.split(`
1738
- `).length} lines).`)});let am=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),ek=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],cm=()=>process.env.TURBOBASE_HOME?.trim()||Er(xj(),".turbobase"),tk=()=>"1.1.12",si=async()=>Promise.all(ek.map(async p=>{try{return await import(p.name),{...p,present:!0}}catch{return{...p,present:!1}}}));am.command("status").description("Report which optional native packages are installed.").action(async()=>{let p=await si();for(let m of p)S(`${m.present?lt.success("installed"):lt.warn("missing")} ${k.bold(m.name)} \u2014 ${m.needs}`);p.some(m=>!m.present)&&S(`
1739
- run \`${Go} ext extras install\` to fetch them into ${cm()}.`)}),am.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let p=await si();if(p.every(j=>j.present)){S(lt.success("extras already installed \u2014 nothing to do."));return}let m=cm();await xe.mkdir(m,{recursive:!0});let _=p.filter(j=>!j.present).map(j=>j.name),v=Il(process.platform,process.arch),$=async(j,M)=>{let{code:D,stderr:ce}=await oi("npm",["install","--prefix",m,"--no-audit","--no-fund",...j]);D!==0&&T(`extras install failed while installing ${M} (npm exited ${D}).
1740
- ${ce.trim()}
1741
- These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},b=_.filter(j=>j!=="isolated-vm");if(b.length>0){let j=b.map(M=>`${M}@${Pl[M]??"latest"}`);S(`installing ${j.join(", ")} \u2192 ${m}/node_modules \u2026`),await $(j,b.join(", "))}if(_.includes("isolated-vm")){let j=`isolated-vm@${Pl["isolated-vm"]}`;if(S(`installing ${j} \u2192 ${m}/node_modules \u2026`),await $(["--ignore-scripts",j],"isolated-vm"),Gg.includes(v)){let D=`${Al}@${tk()}`;S(`fetching ${D} (no upstream binary for ${v}) \u2026`);let{code:ce}=await oi("npm",["install","--prefix",m,"--no-audit","--no-fund","--ignore-scripts",D]);ce!==0&&S(lt.warn(`could not fetch ${D} \u2014 falling back to a source build.`))}let M=await Wg({home:m});M.length>0&&S(` ${lt.success("prebuilt")} ${M.join(", ")} \u2192 isolated-vm/prebuilds/${v}`)}let x=await si(),I=x.filter(j=>!j.present).map(j=>j.name);if(I.includes("isolated-vm")){S(lt.warn(`no prebuilt isolated-vm for ${v} / Node ${process.versions.node} (${Ol()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:j}=await oi("npm",["rebuild","--prefix",m,"isolated-vm"]);j===0&&(x=await si(),I=x.filter(M=>!M.present).map(M=>M.name))}I.length>0&&T(`npm succeeded but ${I.join(", ")} still will not load \u2014 no prebuilt binary for ${v} / Node ${process.versions.node} (${Ol()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),S(lt.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let ii=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return ii.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async p=>{let m=p.target==="approved"?"approved":p.target==="auto"?"auto":null;m||T(`--target must be 'auto' or 'approved' (got '${p.target}').`);let _=await zj(ve(process.cwd(),p.project??".")),v=Object.keys(_).length;!p.solution&&v===0&&T("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let b=(p.ref?await nm(["rev-parse",p.ref])??p.ref:null)??process.env.GITHUB_SHA??await nm(["rev-parse","HEAD"]),x=p.gitRepo??process.env.GITHUB_REPOSITORY??await nm(["remote","get-url","origin"]),I=p.gitRef??process.env.GITHUB_REF??null,j=p.prUrl??process.env.PR_URL??null,{baseUrl:M,token:D}=await oe(p.baseUrl),ce=new re({baseUrl:M,token:D}),Q;try{Q=await ce.releaseDeploy({solutionId:p.solution??null,target:m,approvedBy:p.approvedBy??null,files:v>0?_:null,gitRepo:x,gitRef:I,gitSha:b,prUrl:j})}catch(ke){Me(ke,"releases:write","release deploy"),ke instanceof Te&&ke.status===404&&T("solution_not_found \u2014 no solution with that id."),T(`release deploy failed: ${ke instanceof Error?ke.message:String(ke)}`)}S(`release ${Q.releaseId} enqueued \u2192 taskId=${Q.taskId} (target=${m}`+(v>0?`, uploaded ${v} bundle file(s)`:", live-fetch")+")."),p.follow&&await El(()=>ce.releaseStatus(Q.releaseId),`release ${Q.releaseId}`,p.intervalMs)}),ii.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(p,m)=>{let{baseUrl:_,token:v}=await oe(m.baseUrl),$=new re({baseUrl:_,token:v});if(m.follow){await El(()=>$.releaseStatus(p),`release ${p}`,m.intervalMs);return}let b;try{b=await $.releaseStatus(p)}catch(x){Me(x,"releases:write","release status"),x instanceof Te&&x.status===404&&T(`release ${p} not found.`),T(`release status failed: ${x instanceof Error?x.message:String(x)}`)}S(`release ${p}: status=${b.releaseStatus??"?"} stage=${b.stage} ${b.percent}%`+(b.runStatus?` (${b.runStatus})`:"")),b.outputTail&&S(b.outputTail.replace(/\n+$/,""))}),ii.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:_,token:v}=await oe(m.baseUrl),$=new re({baseUrl:_,token:v}),b;try{b=await $.releaseRollback(p)}catch(x){Me(x,"releases:write","release rollback"),x instanceof Te&&x.status===404&&T(`release ${p} not found.`),x instanceof Te&&x.status===409&&T(`release ${p} cannot be rolled back (not live, or a newer release advanced past it).`),T(`release rollback failed: ${x instanceof Error?x.message:String(x)}`)}S(`release ${b.releaseId} rolled back \u2192 status=${b.release?.status??"rolled_back"}.`)}),ii.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let{baseUrl:m,token:_}=await oe(p.baseUrl),v=new re({baseUrl:m,token:_}),$;try{$=await v.releaseList()}catch(b){Me(b,"releases:write","release list"),T(`release list failed: ${b instanceof Error?b.message:String(b)}`)}if($.length===0){S("no releases.");return}if(_t())S(bn($.map(b=>[b.id,Xn(b.status),b.target,b.backend,b.solutionTitles?.length?b.solutionTitles.map(x=>`"${x}"`).join(", "):k.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let b of $){let x=b.solutionTitles?.length?` "${b.solutionTitles.join('", "')}"`:"";S(` ${b.id} ${b.status.padEnd(11)} target=${b.target} backend=${b.backend}${x}`)}S(`
1742
- ${$.length} release(s).`)}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let{runAuthoringMcpServer:m}=await Promise.resolve().then(()=>(Y$(),J$));await m({baseUrl:p.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
1743
- `)),t&&void 0,e}function Ij(t,e,r){let n=o=>{let s=new RegExp(`${o}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return s?s[2]:void 0};return{id:n("id")??`marketplace:${e}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:t,extensionKind:r||"hook"}}async function tm(){let t=ve(process.cwd(),Ni,Qo),e;try{e=await xe.readFile(t,"utf8")}catch{T(`no bundle found at ${Ni}/${Qo} \u2014 run \`turbobase ext export\` first.`)}try{return sy(e)}catch(r){T(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}function Oj(t,e){S(`plan against ${e}:`);for(let r of t.add)S(` ${Nr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)S(` ${Nr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)S(` ${Nr.destroy(`${r.kind} ${r.id}`)}`);S(`
1744
- ${t.add.length} to add, ${t.change.length} to change, ${t.destroy.length} to destroy.`+(t.add.length+t.change.length+t.destroy.length===0?" (no changes \u2014 up to date.)":""))}function Cj(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function oi(t,e,r){return new Promise(n=>{let o=sm(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),s="";o.stderr?.on("data",i=>{let a=i.toString();s+=a,process.stderr.write(a)}),o.on("error",i=>n({code:-1,stderr:i.message})),o.on("exit",i=>n({code:i??-1,stderr:s}))})}function rm(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let o=n?t.replace(/\/[^/]*$/,`/${n}`):t,s=await oi("psql",[o,"-v","ON_ERROR_STOP=1","-c",r]);if(s.code!==0)throw new Error(`psql failed (exit ${s.code}): ${s.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),o=await oi("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},dataCopyUnavailable:()=>"seeding a sandbox from an instance is not implemented yet: it needs a per-column PII classification for the source tables, and a sandbox will never copy a column it cannot prove is safe. Nothing was created. Use `turbobase ext test <file>` or `turbobase ext replay <file> --fixture <f>` for the offline paths.",readSourceTables:async r=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(r,n,o)=>{let s=Object.keys(o[0]??{});if(s.length===0)return;let i=o.map(a=>`(${s.map(c=>a[c]===null||a[c]===void 0?"NULL":`'${String(a[c]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${n} (${s.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function zj(t){let e=ve(t,"src"),r={},n=async o=>{let s;try{s=await xe.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=Er(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=Rc(e,a).split(om).join("/");r[c]=await xe.readFile(a,"utf8")}}};return await n(e),r}function nm(t){return new Promise(e=>{let r=sm("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.on("error",()=>e(null)),r.on("exit",o=>e(o===0&&n.trim()?n.trim():null))})}var Nj=!1;Nj&&im().parseAsync(process.argv).catch(t=>T(t instanceof Error?t.message:String(t)));im().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
1781
+ `);if(await $("PROPOSAL.md",g),m.screenshot){let x=h(m.screenshot);x&&await $("proposal-screenshot.png",x)}await $(Rt(".turbobase","proposal.json"),`${JSON.stringify({proposalId:m.proposalId},null,2)}
1782
+ `)}async function y(p){try{let m=await me.readFile(Rt(p,".turbobase","proposal.json"),"utf8"),w=JSON.parse(m);return typeof w.proposalId=="string"&&w.proposalId?w.proposalId:void 0}catch{return}}async function v(p,m,w,_,$,g){let x=new te({baseUrl:p,token:m});try{return await x.appsPush(w,_,{note:$,proposalId:g})}catch(A){if(A instanceof _e){let C=A.body;if(A.status===401&&k("push unauthorized (401) \u2014 re-run `turbobase auth login`."),A.status===403&&C?.error==="admin_required"&&k("push forbidden (403) \u2014 the PAT is not for an admin."),A.status===403&&Ae(A,"extensions:deploy","push app source"),A.status===404&&k(`no app "${w}" on this instance \u2014 create it with \`turbobase apps create ${w}\`.`),A.status===413&&(C?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&k("push rejected: the request body exceeded the instance limit."),k(`push rejected: ${C?.error??"too large"} (limit ${C?.limit??"?"}).`)),A.status===400){let L=C?.path?` in ${C.path}`:"",D=C?.reason?` (${C.reason})`:"";k(`push rejected: ${C?.error??"bad request"}${D}${L}.`)}}k(`push failed: ${A instanceof Error?A.message:String(A)}`)}}function E(p,m,w){return new Promise((_,$)=>{let g=am("npm",p,{cwd:m,stdio:"inherit",...w?{env:{...process.env,...w}}:{}});g.on("error",$),g.on("exit",x=>x===0?_():$(new Error(`npm ${p.join(" ")} exited ${x??"?"}`)))})}async function R(p,m,w,_){let $=`${p.replace(/\/+$/,"")}${w}`,g;try{g=await fetch($,{method:_.method,headers:{Authorization:`Bearer ${m}`,..._.body?{"content-type":"application/json"}:{}},..._.body?{body:JSON.stringify(_.body)}:{}})}catch(x){k(`request failed: ${x instanceof Error?x.message:String(x)}`)}if(g.status===401&&k("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&k("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let x=await g.text().catch(()=>""),A=x.slice(0,300);try{let C=JSON.parse(x);A=C.message??C.error??A}catch{}k(`failed: HTTP ${g.status} ${A}`)}return await g.json().catch(()=>({}))}async function z(p,m,w,_,$){return await R(p,m,`/v1/apps/${encodeURIComponent(w)}/preview/${_}`,{method:"POST",body:$})}async function V(p,m,w){return{previews:(await R(p,m,`/v1/apps/${encodeURIComponent(w)}/previews`,{method:"GET"})).previews??[]}}async function J(p,m,w,_,$,g,x,A){let C;try{C=await Se(`zipping ${_}`,()=>vg(_))}catch(U){k(`could not zip ${_}: ${U instanceof Error?U.message:String(U)}`)}C.fileCount===0&&k(`${_} is empty \u2014 the build produced nothing.`);let L={Authorization:`Bearer ${m}`,"Content-Type":"application/zip"};$&&(L["x-app-entry"]=$),g&&(L["x-proposal-id"]=g),x&&(L["x-app-build-id"]=x.buildId,L["x-app-asset-base"]=x.assetBase),A&&(L["x-app-channel"]="preview",A.label&&(L["x-app-preview-label"]=encodeURIComponent(A.label)));let D=`${p.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/deploy`,ne;try{ne=await Se(`deploying ${w} (${C.fileCount} file${C.fileCount===1?"":"s"})`,()=>fetch(D,{method:"POST",headers:L,body:new Uint8Array(C.buffer)}))}catch(U){k(`deploy request failed: ${U instanceof Error?U.message:String(U)}`)}if(ne.status===401&&k("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),ne.status===403&&k("deploy forbidden (403) \u2014 the PAT is not for an admin."),ne.status===404&&k(`no app "${w}" on ${p} \u2014 create it with \`turbobase apps create ${w}\`.`),!ne.ok){let U=await ne.text().catch(()=>""),fe=U.slice(0,300);try{let se=JSON.parse(U);fe=se.message??se.error??fe}catch{}k(`deploy failed: HTTP ${ne.status} ${fe}`)}return await ne.json().catch(()=>({}))}async function He(p,m){let w=Cg(p,{localDocsModifiedAt:await Xe(m)});w&&S(w.level==="warn"?T.yellow(w.message):T.dim(w.message))}async function Xe(p){if(!p)return null;let m=null;for(let w of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let _=await me.stat(Rt(p,w));(m===null||_.mtimeMs>m)&&(m=_.mtimeMs)}catch{}return m===null?null:new Date(m)}c.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(p,m,w)=>{let{baseUrl:_,token:$}=await oe(w.baseUrl);if(w.proposal){let C=new te({baseUrl:_,token:$}),L;try{L=await Se(`fetching proposal ${w.proposal}`,()=>C.appPullContext(w.proposal))}catch(se){Ae(se,"extensions:deploy","pull proposal"),se instanceof _e&&se.status===404&&k(`no widget proposal "${w.proposal}" on ${_}.`),k(`could not fetch proposal ${w.proposal}: ${se instanceof Error?se.message:String(se)}`)}let D=await Se(`pulling ${L.appSlug}`,()=>d(_,$,L.appSlug)),ne=m??p,U=$e(process.cwd(),ne??L.appSlug);await me.mkdir(U,{recursive:!0});let fe=await b(U,D.files,!!w.force);await f(U,L,!!w.force),S(`pulled ${fe} file${fe===1?"":"s"} \u2192 ${U} (rev ${D.rev}), linked to proposal ${L.proposalId}.`),S(`next: cd ${Rc(process.cwd(),U)||"."} && turbobase apps deploy ${L.appSlug}`);return}p||k("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await Se(`pulling ${p}`,()=>d(_,$,p)),x=$e(process.cwd(),m??g.slug??p);await me.mkdir(x,{recursive:!0});let A=await b(x,g.files,!!w.force);S(`pulled ${A} file${A===1?"":"s"} \u2192 ${x} (rev ${g.rev}).`),S(`next: cd ${Rc(process.cwd(),x)||"."} && turbobase apps deploy ${g.slug}`)}),c.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(p,m,w)=>{let _=$e(process.cwd(),m??p),$=await or(w.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:x}=await Promise.resolve().then(()=>(ky(),$y)),A=w.title??p,C=g({slug:p,title:A,appTsx:x(A),instanceOrigin:$?.baseUrl});await me.mkdir(_,{recursive:!0});let L=await b(_,C,!!w.force);if(S(`scaffolded ${L} file${L===1?"":"s"} \u2192 ${_}`),w.claude!==!1){let ne=El({baseUrl:$?.baseUrl,token:$?.token,appSlug:p}),U=0;for(let fe of ne){let se=await tk(Rt(_,fe.path),fe);(se==="wrote"||se==="merged")&&(U+=1)}S(`wired Claude Code: ${U} file${U===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),$||Ee("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let D=Rc(process.cwd(),_)||".";S(`next: cd ${D} && npm install && npm run dev`),S(` turbobase apps create ${p}`),S(` turbobase apps push ${p} .`),S(` turbobase apps deploy ${p} .`)}),c.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:m,token:w}=await oe(p.baseUrl),_=new te({baseUrl:m,token:w}),$;try{$=await _.appsList()}catch(g){Ae(g,"extensions:deploy","list apps"),k(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return S(JSON.stringify($,null,2));if($.length===0)return S("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");S(wn($.map(g=>[g.slug,g.name,g.deployed?"yes":"no",g.sourceRev===null?"\u2014":`rev ${g.sourceRev}`,g.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),c.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(p,m,w)=>{let _=$e(process.cwd(),m??".");await me.stat(_).then(se=>se.isDirectory()).catch(()=>!1)||k(`${_} is not a directory.`);let{baseUrl:g,token:x}=await oe(w.baseUrl),A=w.proposal??await y(_),{files:C,skipped:L,secrets:D,unstorable:ne}=await Kg(_),U=Object.keys(C).length;if(U===0&&k(`no source files found under ${_} (build output and node_modules are skipped).`),ne.length>0){for(let se of ne)Ee(`${se} contains a NUL byte (U+0000), which cannot be stored.`);k(`push aborted: ${ne.length} ${ne.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let se of L)Ee(T.dim(`skipped binary file ${se}`));for(let se of D)Ee(T.dim(`skipped ${se} (holds credentials \u2014 never pushed)`));let fe=await Se(`pushing ${U} file${U===1?"":"s"}`,()=>v(g,x,p,C,w.note,A));S(`pushed ${fe.files} file${fe.files===1?"":"s"} \u2192 ${fe.slug} rev ${fe.rev} (source only, nothing deployed).`),S(`next: turbobase apps deploy ${fe.slug}`)}),o.command("plan").description("Diff the local bundle (turbobase/bundle.json) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let m=await nm(),{baseUrl:w,token:_}=await oe(p.baseUrl),$=new te({baseUrl:w,token:_}),g;try{g=await Se(`planning against ${p.to??w}`,()=>$.configPlan(m))}catch(x){k(`plan failed: ${x instanceof Error?x.message:String(x)}`)}jj(g,p.to??w)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").action(async p=>{let m=await nm(),{baseUrl:w,token:_}=await oe(p.baseUrl),$=m.tenant??Lj(w),g=ly(p.confirm,$);g.ok||k(`promote refused (fail-closed): ${g.reason}`);let x=new te({baseUrl:w,token:_});try{let A=await Se(`promoting ${p.from} \u2192 ${p.to} (${$})`,()=>x.configApply(m));if(wt()){let C=[`${T.bold(`${p.from} \u2192 ${p.to}`)} ${T.dim($??"")}`,`${jr.add(String(A.applied.add))} ${jr.change(String(A.applied.change))} ${jr.destroy(String(A.applied.destroy))}`];A.backfillsQueued.length&&C.push(T.dim(`${A.backfillsQueued.length} backfill(s) queued`)),S(Lr("Promoted",C))}else S(`promoted ${p.from} \u2192 ${p.to} (${$}): +${A.applied.add} ~${A.applied.change} -${A.applied.destroy}`+(A.backfillsQueued.length?` (${A.backfillsQueued.length} backfill(s) queued)`:""))}catch(A){A instanceof _e&&A.status===403&&k("promote forbidden (403) \u2014 the stored PAT is not for an admin."),k(`promote failed: ${A instanceof Error?A.message:String(A)}`)}});let Rr=async(p,m)=>{let{baseUrl:w,token:_}=await oe(m.baseUrl),$=new te({baseUrl:w,token:_}),g=m.limit?Number(m.limit):void 0;if(m.follow){try{await Ag($,p,{follow:!0,limit:g,intervalMs:m.intervalMs?Number(m.intervalMs):void 0,sink:S})}catch(x){k(`logs --follow failed: ${x instanceof Error?x.message:String(x)}`)}return}try{let x=await $.logs(p,g);x.length===0&&S(`no logs for ${p}.`);for(let A of x)S(` [${A.level}] ${A.ts??""} ${A.message}`)}catch(x){k(`logs failed: ${x instanceof Error?x.message:String(x)}`)}};o.command("logs").argument("<id>","Extension id (default) or conduit id (with --follow)").description("Read an extension's logs; with --follow, stream a conduit's run ledger.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--limit <n>","Max log lines").option("--follow","Stream the conduit_event run ledger for the given conduit id.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(Rr),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(p,m)=>{let w=rm(m.reporter),_=$e(process.cwd(),p),$=await Ko(_),g=$g($);w?S(Ai(Cj(p,g),w)):S(kg(p,g,{warn:T.yellow,ok:T.green,dim:T.dim})),m.ci&&g.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(p,m)=>{let w=rm(m.reporter),_=await mg($e(process.cwd(),p));if(m.against){m.against!=="sandbox"&&k(`unknown --against target '${m.against}' (only 'sandbox' is supported).`);try{await fg(wl(_))}catch(x){k(x instanceof Error?x.message:String(x))}return}m.fixture||k("replay needs a --fixture <file> (offline) or --against sandbox (online).");let $;try{$=await hg($e(process.cwd(),m.fixture))}catch(x){k(`could not read fixture ${m.fixture}: ${x instanceof Error?x.message:String(x)}`)}let g=await pg(_,$,m.fixture);if(w){let x=zj(g);S(Ai(x,w)),x.cases.some(A=>A.status==="failed")&&process.exit(1);return}S(gg(g,!!m.trace)),g.error&&process.exit(1)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async p=>{let{baseUrl:m,token:w}=await oe(p.baseUrl),_=new te({baseUrl:m,token:w});try{await Ig(_,{status:p.status,retry:p.retry,limit:p.limit?Number(p.limit):void 0,sink:S})}catch($){$ instanceof _e&&$.status===403&&k("forbidden (403) \u2014 binding --retry requires an admin PAT."),$ instanceof _e&&$.status===409&&k("binding is not retryable (only divergent/blocked bindings can be retried)."),k(`ext binding failed: ${$ instanceof Error?$.message:String($)}`)}}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(p,m)=>{let w=p.lastIndexOf("@"),_=w>0?p.slice(0,w):p,$=w>0?p.slice(w+1):void 0,g=fl();g||k(`marketplace not configured \u2014 set ${Yn} and ${Ti}.
1783
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=hl(g.registryUrl);x&&k(x);let{baseUrl:A,token:C}=await oe(m.baseUrl),L=new Bo(g),D;try{D=await Se(`fetching ${p}`,()=>L.fetchBundle(_,$))}catch(de){k(`marketplace fetch failed for ${p}: ${de instanceof Error?de.message:String(de)}`)}let ne=wi(D.manifest),U=null;if(ne.length>0){if(!m.connection){let de=ne.map(Pt=>Pt.source_system).join(", ");k(`${D.name}@${D.version} declares a connection input (source: ${de}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}U=m.connection}let fe=Nj(D.bundle,D.name,D.kind),se=new te({baseUrl:A,token:C});try{let de=await Se(`installing ${D.name}@${D.version}`,()=>se.deploy({...fe,provenance:"marketplace",...U?{connectionId:U}:{}}));S(`installed ${D.name}@${D.version} \u2192 ${de.id} (status=${de.status}, ${de.outcome})`+(U?` bound to connection ${U}.`:"."))}catch(de){de instanceof _e&&de.status===403&&k("install forbidden (403) \u2014 the stored PAT is not for an admin."),k(`install failed: ${de instanceof Error?de.message:String(de)}`)}}),o.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(p,m)=>{let w=fl();w||k(`marketplace not configured \u2014 set ${Yn} and ${Ti}.
1784
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let _=hl(w.registryUrl);_&&k(_);let $=$e(process.cwd(),p),g=await Ko($),x=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",A={};if(m.manifest){let D=$e(process.cwd(),m.manifest),ne;try{ne=await me.readFile(D,"utf8")}catch{k(`manifest not found at ${m.manifest}.`)}let U;try{U=JSON.parse(ne)}catch{k(`manifest is not valid JSON: ${m.manifest}.`)}(typeof U!="object"||U===null||Array.isArray(U))&&k("manifest must be a JSON object."),A=U}try{Xc(A,g)}catch(D){D instanceof Cr&&k(D.message),k(`manifest validation failed: ${D instanceof Error?D.message:String(D)}`)}let C=new Bo(w);try{await Se(`publishing ${m.name}@${m.pkgVersion}`,()=>C.publish({name:m.name,version:m.pkgVersion,kind:x,bundle:g,manifest:A}))}catch(D){D instanceof _e&&D.status===403&&k("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),D instanceof _e&&D.status===409&&k(`version already published \u2014 ${m.name}@${m.pkgVersion} exists. Bump the version.`),k(`publish failed: ${D instanceof Error?D.message:String(D)}`)}let L=wi(A);S(`published ${m.name}@${m.pkgVersion} (kind=${x}) to the marketplace.`),L.length>0&&S(` declares ${L.length} connection input(s): ${L.map(D=>D.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async p=>{let m=await or(p.baseUrl).catch(()=>null),w=El({baseUrl:m?.baseUrl,token:m?.token}),_=0,$=0,g=0;for(let x of w){let A=$e(process.cwd(),x.path),C=await tk(A,x);C==="wrote"?(_+=1,S(` wrote ${x.path}`)):C==="merged"?(g+=1,S(` merged ${x.path} (added the .mcp.json rule)`)):($+=1,S(` skipped ${x.path} (exists)`))}S(`
1785
+ project init: ${_} written, ${g} merged, ${$} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Tl} (non-destructive).`).action(async()=>{let p=zg(),m=0,w=0;for(let _ of p){let $=$e(process.cwd(),_.path);await zo($,_.content,_.executable)==="wrote"?(m+=1,S(` wrote ${_.path}`)):(w+=1,S(` skipped ${_.path} (exists)`))}S(`
1786
+ project ci: ${m} written, ${w} skipped.`),m>0&&(S(`
1787
+ Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),S("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),S("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async p=>{let{baseUrl:m,token:w}=await oe(p.baseUrl),_=new te({baseUrl:m,token:w}),$;try{$=await _.catalogRecords()}catch(L){L instanceof _e&&(L.status===401||L.status===403)&&k("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),k(`catalog fetch failed: ${L instanceof Error?L.message:String(L)}`)}if($.length===0){S("no records in the instance catalog \u2014 nothing to generate.");return}let g=$e(process.cwd(),p.out),x=bg($,{event:p.event}),A=0,C=0;for(let{recordType:L,fixture:D}of x){let ne=Rt(g,`${L}.json`),U=`${JSON.stringify(D,null,2)}
1788
+ `;p.force?(await me.mkdir(Co(ne),{recursive:!0}),await me.writeFile(ne,U,{mode:420}),A+=1,S(` wrote ${p.out}/${L}.json`)):await zo(ne,U)==="wrote"?(A+=1,S(` wrote ${p.out}/${L}.json`)):(C+=1,S(` skipped ${p.out}/${L}.json (exists \u2014 use --force to overwrite)`))}S(`
1789
+ samples init: ${A} written, ${C} skipped.`)});let er=e.command("guardrails").description("Control PG\u2192source write-back with DENY rules (staged write rollout)."),tn=p=>[p.name,p.enabled?T.green("on"):T.dim("off"),p.source,p.record,p.when||T.dim("(always)"),p.note??""];er.command("list").description("List every write guardrail on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:m,token:w}=await oe(p.baseUrl),_=new te({baseUrl:m,token:w}),$;try{$=await _.guardrailsList()}catch(g){Ae(g,"extensions:deploy","list guardrails"),k(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return S(JSON.stringify($,null,2));if($.length===0)return S(`no write guardrails \u2014 every record the admin entitlement allows is writable.
1790
+ `+T.dim("create one with `turbobase guardrails create <name> --source <s> --when '\u2026'`"));S(wn($.map(tn),{head:["NAME","STATE","SOURCE","RECORD","WHEN","NOTE"]}))}),er.command("create <name>").description("Create a DENY rule. Blocks PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--when <expr>","Condition, e.g. 'recordType not_in customer,invoice' or 'record.amount gt 10000'. Omit to deny unconditionally.").option("--message <text>","What a blocked writer is told.").option("--note <text>","Why this rule exists \u2014 for whoever reads `list` later.").option("--disabled","Create the rule parked, so it takes effect only when enabled.").option("--confirm-freeze-all","Required for an unconditional '*'/'*' rule.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:w,token:_}=await oe(m.baseUrl),$=new te({baseUrl:w,token:_}),g;try{g=await $.guardrailCreate({name:p,source:m.source,record:m.record,...m.when?{when:m.when}:{},...m.message?{message:m.message}:{},...m.note?{note:m.note}:{},...m.disabled?{enabled:!1}:{},...m.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(x){Ae(x,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${x instanceof Error?x.message:String(x)}`)}S(`${T.green("\u2713")} guardrail ${T.bold(g.name)} created${g.enabled?"":T.dim(" (parked \u2014 enable it to take effect)")}`),S(T.dim(` denies ${g.source}/${g.record}${g.when?` where ${g.when}`:" (always)"}`)),S(T.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),er.command("edit <name>").description("Change a rule \u2014 most often widening its exception set as records are proven.").option("--when <expr>","New condition. Pass '' to make it unconditional.").option("--message <text>","What a blocked writer is told.").option("--note <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{m.when===void 0&&m.message===void 0&&m.note===void 0&&k("edit: nothing to change \u2014 pass --when, --message or --note.");let{baseUrl:w,token:_}=await oe(m.baseUrl),$=new te({baseUrl:w,token:_}),g;try{g=await $.guardrailUpdate(p,{...m.when!==void 0?{when:m.when}:{},...m.message!==void 0?{message:m.message}:{},...m.note!==void 0?{note:m.note}:{}})}catch(x){Ae(x,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${x instanceof Error?x.message:String(x)}`)}S(`${T.green("\u2713")} guardrail ${T.bold(g.name)} updated`),S(T.dim(` denies ${g.source}/${g.record}${g.when?` where ${g.when}`:" (always)"}`))});for(let[p,m,w]of[["enable",!0,"enabled"],["disable",!1,"disabled"]])er.command(`${p} <name>`).description(m?"Arm a parked rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(_,$)=>{let{baseUrl:g,token:x}=await oe($.baseUrl),A=new te({baseUrl:g,token:x});try{await A.guardrailUpdate(_,{enabled:m})}catch(C){Ae(C,"extensions:deploy",`${p} a guardrail`),k(`${p} guardrail failed: ${C instanceof Error?C.message:String(C)}`)}S(`${T.green("\u2713")} guardrail ${T.bold(_)} ${w}`),m||S(T.dim(" writes it was blocking are now permitted (subject to the other rules)."))});er.command("delete <name>").description("Remove a rule. This OPENS a write path \u2014 prefer `disable` if unsure.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:w,token:_}=await oe(m.baseUrl),$=new te({baseUrl:w,token:_});try{await $.guardrailDelete(p)}catch(g){Ae(g,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}S(`${T.green("\u2713")} guardrail ${T.bold(p)} deleted`)}),er.command("test").description("Would a write be blocked? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--origin <origin>","Write origin to simulate ('user', 'agent').").option("--fields <json>","A candidate row as JSON, so `record.<column>` conditions can be decided.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async p=>{let m;if(p.fields)try{m=JSON.parse(p.fields)}catch(x){k(`--fields must be valid JSON: ${x instanceof Error?x.message:String(x)}`)}let{baseUrl:w,token:_}=await oe(p.baseUrl),$=new te({baseUrl:w,token:_}),g;try{g=await $.guardrailTest({source:p.source,record:p.record,...p.origin?{origin:p.origin}:{},...m?{fields:m}:{}})}catch(x){Ae(x,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${x instanceof Error?x.message:String(x)}`)}if(p.json)return S(JSON.stringify(g,null,2));g.allowed?S(`${T.green("\u2713")} ${p.source}/${p.record} \u2014 no guardrail blocks this write`):(S(`${T.red("\u2717")} ${p.source}/${p.record} \u2014 blocked by ${T.bold(g.blockedBy??"?")}`),g.message&&S(T.dim(` ${g.message}`))),g.undecided.length>0&&(S(T.yellow(` ${g.undecided.length} rule(s) need a row to decide: ${g.undecided.join(", ")}`)),S(T.dim(` re-run with --fields '{"\u2026":"\u2026"}' to evaluate them.`))),g.allowed||(process.exitCode=1)});let fr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Dn=(p,m={})=>{let w=`${T.bold(p.table)} ${T.dim(p.displayName)}`;S(p.exists===!1?`${w} ${T.dim("(new)")}`:w);for(let _ of p.fields){let $=[_.required?"required":null].filter(Boolean).join(", "),g=m.showClaimants&&_.claimedBy?.length?` ${T.dim(`\u2190 ${_.claimedBy.join(", ")}`)}`:"";S(` ${_.column.padEnd(28)} ${_.type}${$?` (${$})`:""}${g}`)}m.showClaimants&&p.claimants.length>1&&S(T.dim(` claimed by ${p.claimants.join(", ")}`))};function Un(p){if(p instanceof _e&&p.status===409){let m=p.body;m?.error==="table_conflict"&&m.message&&(Ee(m.message),process.exit(1))}k(`tables: ${p instanceof Error?p.message:String(p)}`)}let si=async p=>{let m=Rt($e(process.cwd(),p),"public","turbobase.json"),w=await me.readFile(m,"utf8").catch(()=>null);if(w===null)return null;let _;try{_=JSON.parse(w)}catch(g){k(`${m} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let $=_.tables;return $===void 0?{tables:[],manifestPath:m}:(Array.isArray($)||k(`${m}: "tables" must be an array.`),{tables:$,manifestPath:m})};fr.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async p=>{let{baseUrl:m,token:w}=await oe(p.baseUrl),_=new te({baseUrl:m,token:w}),$;try{$=await _.tablesList()}catch(g){Ae(g,"extensions:deploy","list tables"),k(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(p.json)return S(JSON.stringify($,null,2));if($.length===0)return S("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");S(wn($.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),fr.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(p,m)=>{let w=await si(p??".");if(w||k(`no public/turbobase.json under ${$e(process.cwd(),p??".")}.`),w.tables.length===0)return S(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:_,token:$}=await oe(m.baseUrl),g=new te({baseUrl:_,token:$}),x;try{x=await Se("planning tables",()=>g.tablesPlan({claimedBy:m.as,tables:w.tables}))}catch(A){Ae(A,"extensions:deploy","plan tables"),Un(A)}S(`claiming as ${T.bold(x.claimedBy)}`);for(let A of x.tables)Dn(A,{showClaimants:!0});S(""),S(T.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),fr.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(p,m)=>{let w=await si(p??".");if(w||k(`no public/turbobase.json under ${$e(process.cwd(),p??".")}.`),w.tables.length===0)return S(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:_,token:$}=await oe(m.baseUrl),g=new te({baseUrl:_,token:$}),x;try{x=await Se("applying tables",()=>g.tablesApply({claimedBy:m.as,tables:w.tables}))}catch(A){Ae(A,"extensions:deploy","apply tables"),Un(A)}for(let A of x.tables)Dn(A,{showClaimants:!0});S(`applied ${x.tables.length} table${x.tables.length===1?"":"s"} as ${x.claimedBy}.`)}),fr.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(p,m)=>[...m??[],p],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let w=m.field.map(A=>{let[C,L,D]=A.split(":");return(!C||!L)&&k(`--field "${A}" must be name:type[:required] (e.g. title:text:required).`),D!==void 0&&D!=="required"&&k(`--field "${A}": the third part may only be "required".`),{name:C,type:L,...D==="required"?{required:!0}:{}}}),{baseUrl:_,token:$}=await oe(m.baseUrl),g=new te({baseUrl:_,token:$}),x;try{x=await Se(`creating cr_${p}`,()=>g.tablesApply({tables:[{slug:p,displayName:m.name??p,fields:w,...m.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(A){Ae(A,"extensions:deploy","create a table"),Un(A)}for(let A of x.tables)Dn(A);S(""),S(T.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),fr.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{m.confirm!==p&&k(`drop refused: --confirm "${m.confirm}" does not match "${p}".`);let{baseUrl:w,token:_}=await oe(m.baseUrl),$=new te({baseUrl:w,token:_}),g;try{g=await Se(`dropping cr_${p}`,()=>$.tablesDrop(p,m.confirm))}catch(x){Ae(x,"extensions:deploy","drop a table"),k(`drop failed: ${x instanceof Error?x.message:String(x)}`)}if(!g.removed)return S(`no table named "${p}" on this instance \u2014 nothing dropped.`);S(`dropped ${g.table} and every row in it.`)});let Pc=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Pc.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async p=>{process.env.TURBOBASE_SANDBOX="1";let m=om(),w;try{w=await oy(m,{fromTenant:p.from,ttl:p.ttl,sample:p.sample,baseUrl:p.baseUrl})}catch(_){_ instanceof Xo&&k(_.message),k(`sandbox create failed: ${_ instanceof Error?_.message:String(_)}`)}S(`sandbox ${w.name} ready.`),S(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),S(` url: ${w.url}`),S(` expires: ${w.expiresAt}`)}),Pc.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async p=>{let m=om();await Ul(m).catch(()=>[]);let w;try{w=await sy(m,p)}catch(_){k(`sandbox destroy failed: ${_ instanceof Error?_.message:String(_)}`)}w||k(`no sandbox named '${p}'.`),S(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Pc.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let p=om(),m=await Ul(p).catch(()=>[]),w=await zi(),{active:_}=Dl(w);if(_.length===0)S("no active sandboxes.");else{for(let $ of _)S(` ${$.name} from=${$.fromTenant} expires=${$.expiresAt} ${$.url}`);S(`
1791
+ ${_.length} active sandbox(es).`)}m.length>0&&S(`(reaped ${m.length} expired sandbox(es).)`)}),o.command("export").description("Snapshot the live instance into turbobase/bundle.json.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Ni).action(async p=>{let{baseUrl:m,token:w}=await oe(p.baseUrl),_=new te({baseUrl:m,token:w}),$;try{$=await Se("exporting instance config",()=>_.configExport())}catch(A){A instanceof _e&&(A.status===401||A.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${A instanceof Error?A.message:String(A)}`)}let g=typeof $.serialized=="string"?$.serialized:`${JSON.stringify($.manifest??$,null,2)}
1792
+ `,x=$e(process.cwd(),p.out,es);await me.mkdir(Co(x),{recursive:!0}),await me.writeFile(x,g,"utf8"),S(`wrote ${p.out}/${es} (${g.split(`
1793
+ `).length} lines).`)});let lm=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),nk=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],um=()=>process.env.TURBOBASE_HOME?.trim()||Rt(Tj(),".turbobase"),ok=()=>"1.1.14",ii=async()=>Promise.all(nk.map(async p=>{try{return await import(p.name),{...p,present:!0}}catch{return{...p,present:!1}}}));lm.command("status").description("Report which optional native packages are installed.").action(async()=>{let p=await ii();for(let m of p)S(`${m.present?lt.success("installed"):lt.warn("missing")} ${T.bold(m.name)} \u2014 ${m.needs}`);p.some(m=>!m.present)&&S(`
1794
+ run \`${Wo} ext extras install\` to fetch them into ${um()}.`)}),lm.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let p=await ii();if(p.every(C=>C.present)){S(lt.success("extras already installed \u2014 nothing to do."));return}let m=um();await me.mkdir(m,{recursive:!0});let w=p.filter(C=>!C.present).map(C=>C.name),_=Cl(process.platform,process.arch),$=async(C,L)=>{let{code:D,stderr:ne}=await oi("npm",["install","--prefix",m,"--no-audit","--no-fund",...C]);D!==0&&k(`extras install failed while installing ${L} (npm exited ${D}).
1795
+ ${ne.trim()}
1796
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=w.filter(C=>C!=="isolated-vm");if(g.length>0){let C=g.map(L=>`${L}@${Il[L]??"latest"}`);S(`installing ${C.join(", ")} \u2192 ${m}/node_modules \u2026`),await $(C,g.join(", "))}if(w.includes("isolated-vm")){let C=`isolated-vm@${Il["isolated-vm"]}`;if(S(`installing ${C} \u2192 ${m}/node_modules \u2026`),await $(["--ignore-scripts",C],"isolated-vm"),Yg.includes(_)){let D=`${Ol}@${ok()}`;S(`fetching ${D} (no upstream binary for ${_}) \u2026`);let{code:ne}=await oi("npm",["install","--prefix",m,"--no-audit","--no-fund","--ignore-scripts",D]);ne!==0&&S(lt.warn(`could not fetch ${D} \u2014 falling back to a source build.`))}let L=await Xg({home:m});L.length>0&&S(` ${lt.success("prebuilt")} ${L.join(", ")} \u2192 isolated-vm/prebuilds/${_}`)}let x=await ii(),A=x.filter(C=>!C.present).map(C=>C.name);if(A.includes("isolated-vm")){S(lt.warn(`no prebuilt isolated-vm for ${_} / Node ${process.versions.node} (${zl()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:C}=await oi("npm",["rebuild","--prefix",m,"isolated-vm"]);C===0&&(x=await ii(),A=x.filter(L=>!L.present).map(L=>L.name))}A.length>0&&k(`npm succeeded but ${A.join(", ")} still will not load \u2014 no prebuilt binary for ${_} / Node ${process.versions.node} (${zl()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),S(lt.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Zn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Zn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async p=>{let m=p.target==="approved"?"approved":p.target==="auto"?"auto":null;m||k(`--target must be 'auto' or 'approved' (got '${p.target}').`);let w=await Mj($e(process.cwd(),p.project??".")),_=Object.keys(w).length;!p.solution&&_===0&&k("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(p.ref?await sm(["rev-parse",p.ref])??p.ref:null)??process.env.GITHUB_SHA??await sm(["rev-parse","HEAD"]),x=p.gitRepo??process.env.GITHUB_REPOSITORY??await sm(["remote","get-url","origin"]),A=p.gitRef??process.env.GITHUB_REF??null,C=p.prUrl??process.env.PR_URL??null,{baseUrl:L,token:D}=await oe(p.baseUrl),ne=new te({baseUrl:L,token:D}),U;try{U=await ne.releaseDeploy({solutionId:p.solution??null,target:m,approvedBy:p.approvedBy??null,files:_>0?w:null,gitRepo:x,gitRef:A,gitSha:g,prUrl:C})}catch(fe){Ae(fe,"releases:write","release deploy"),fe instanceof _e&&fe.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${fe instanceof Error?fe.message:String(fe)}`)}S(`release ${U.releaseId} enqueued \u2192 taskId=${U.taskId} (target=${m}`+(_>0?`, uploaded ${_} bundle file(s)`:", live-fetch")+")."),p.follow&&await Pl(()=>ne.releaseStatus(U.releaseId),`release ${U.releaseId}`,p.intervalMs)}),Zn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:w,token:_}=await oe(m.baseUrl),$=new te({baseUrl:w,token:_}),g;try{g=await $.releaseFiles(p)}catch(C){C instanceof _e&&C.status===404&&k(`release ${p} not found.`),C instanceof _e&&C.status===409&&k(`no built project was retained for release ${p}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),Ae(C,"releases:write","pull a release"),k(`release pull failed: ${C instanceof Error?C.message:String(C)}`)}let x=$e(process.cwd(),m.dir),A=0;for(let[C,L]of[["owned",g.owned],["context",g.context]])for(let[D,ne]of Object.entries(L)){let U=Rt(x,C,D);await me.mkdir(Co(U),{recursive:!0}),await me.writeFile(U,ne,"utf8"),A++}await me.writeFile(Rt(x,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),S(`pulled release ${g.releaseId} (${g.status}) \u2192 ${x}
1797
+ ${Object.keys(g.owned).length} owned file(s), ${Object.keys(g.context).length} context file(s), ${A} total
1798
+ `+(g.logTail?`
1799
+ the failure these bytes produced:
1800
+ ${g.logTail.trim()}
1801
+ `:"")+`
1802
+ edit the files under owned/, then:
1803
+ turbobase release push ${g.releaseId} --dir ${m.dir}`)}),Zn.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(p,m)=>{let{baseUrl:w,token:_}=await oe(m.baseUrl),$=new te({baseUrl:w,token:_}),g=$e(process.cwd(),m.dir),x;try{x=await $.releaseFiles(p)}catch(U){U instanceof _e&&U.status===404&&k(`release ${p} not found.`),Ae(U,"releases:write","push a release"),k(`release push failed: ${U instanceof Error?U.message:String(U)}`)}let A=async(U,fe)=>{try{return await me.readFile(Rt(g,U,fe),"utf8")}catch{return null}},C=[];for(let[U,fe]of Object.entries(x.context)){let se=await A("context",U);se!==null&&se!==fe&&C.push(U)}C.length>0&&k(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
1804
+ `+C.map(U=>` context/${U}`).join(`
1805
+ `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let L={...x.context},D=0;for(let[U,fe]of Object.entries(x.owned)){let se=await A("owned",U);L[U]=se??fe,se!==null&&se!==fe&&D++}D===0&&S("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let ne=m.target==="approved"?"approved":"auto";try{let U=await $.releasePush(p,{files:L,target:ne,...m.approvedBy?{approvedBy:m.approvedBy}:{}});S(`pushed ${Object.keys(L).length} file(s) (${D} edited) \u2192 release ${U.releaseId} (task ${U.taskId}).
1806
+ follow it with:
1807
+ turbobase release status ${U.releaseId} --follow`)}catch(U){U instanceof _e&&U.status===403&&k("an approved target needs --approved-by (the deploy gate fails closed)."),U instanceof _e&&U.status===409&&k("that solution already has an active release \u2014 roll it back or wait for it."),Ae(U,"releases:write","push a release"),k(`release push failed: ${U instanceof Error?U.message:String(U)}`)}}),Zn.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(p,m)=>{let{baseUrl:w,token:_}=await oe(m.baseUrl),$=new te({baseUrl:w,token:_});if(m.follow){await Pl(()=>$.releaseStatus(p),`release ${p}`,m.intervalMs);return}let g;try{g=await $.releaseStatus(p)}catch(x){Ae(x,"releases:write","release status"),x instanceof _e&&x.status===404&&k(`release ${p} not found.`),k(`release status failed: ${x instanceof Error?x.message:String(x)}`)}S(`release ${p}: status=${g.releaseStatus??"?"} stage=${g.stage} ${g.percent}%`+(g.runStatus?` (${g.runStatus})`:"")),g.outputTail&&S(g.outputTail.replace(/\n+$/,""))}),Zn.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(p,m)=>{let{baseUrl:w,token:_}=await oe(m.baseUrl),$=new te({baseUrl:w,token:_}),g;try{g=await $.releaseRollback(p)}catch(x){Ae(x,"releases:write","release rollback"),x instanceof _e&&x.status===404&&k(`release ${p} not found.`),x instanceof _e&&x.status===409&&k(`release ${p} cannot be rolled back (not live, or a newer release advanced past it).`),k(`release rollback failed: ${x instanceof Error?x.message:String(x)}`)}S(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),Zn.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let{baseUrl:m,token:w}=await oe(p.baseUrl),_=new te({baseUrl:m,token:w}),$;try{$=await _.releaseList()}catch(g){Ae(g,"releases:write","release list"),k(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if($.length===0){S("no releases.");return}if(wt())S(wn($.map(g=>[g.id,to(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map(x=>`"${x}"`).join(", "):T.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of $){let x=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";S(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${x}`)}S(`
1808
+ ${$.length} release(s).`)}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async p=>{let{runAuthoringMcpServer:m}=await Promise.resolve().then(()=>(ek(),Q$));await m({baseUrl:p.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
1809
+ `)),t&&void 0,e}function Nj(t,e,r){let n=o=>{let s=new RegExp(`${o}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return s?s[2]:void 0};return{id:n("id")??`marketplace:${e}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:t,extensionKind:r||"hook"}}async function nm(){let t=$e(process.cwd(),Ni,es),e;try{e=await me.readFile(t,"utf8")}catch{k(`no bundle found at ${Ni}/${es} \u2014 run \`turbobase ext export\` first.`)}try{return cy(e)}catch(r){k(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}function jj(t,e){S(`plan against ${e}:`);for(let r of t.add)S(` ${jr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)S(` ${jr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)S(` ${jr.destroy(`${r.kind} ${r.id}`)}`);S(`
1810
+ ${t.add.length} to add, ${t.change.length} to change, ${t.destroy.length} to destroy.`+(t.add.length+t.change.length+t.destroy.length===0?" (no changes \u2014 up to date.)":""))}function Lj(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function oi(t,e,r){return new Promise(n=>{let o=am(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),s="";o.stderr?.on("data",i=>{let a=i.toString();s+=a,process.stderr.write(a)}),o.on("error",i=>n({code:-1,stderr:i.message})),o.on("exit",i=>n({code:i??-1,stderr:s}))})}function om(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let o=n?t.replace(/\/[^/]*$/,`/${n}`):t,s=await oi("psql",[o,"-v","ON_ERROR_STOP=1","-c",r]);if(s.code!==0)throw new Error(`psql failed (exit ${s.code}): ${s.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),o=await oi("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},dataCopyUnavailable:()=>"seeding a sandbox from an instance is not implemented yet: it needs a per-column PII classification for the source tables, and a sandbox will never copy a column it cannot prove is safe. Nothing was created. Use `turbobase ext test <file>` or `turbobase ext replay <file> --fixture <f>` for the offline paths.",readSourceTables:async r=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(r,n,o)=>{let s=Object.keys(o[0]??{});if(s.length===0)return;let i=o.map(a=>`(${s.map(c=>a[c]===null||a[c]===void 0?"NULL":`'${String(a[c]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${n} (${s.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function Mj(t){let e=$e(t,"src"),r={},n=async o=>{let s;try{s=await me.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=Rt(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=Rc(e,a).split(im).join("/");r[c]=await me.readFile(a,"utf8")}}};return await n(e),r}function sm(t){return new Promise(e=>{let r=am("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.on("error",()=>e(null)),r.on("exit",o=>e(o===0&&n.trim()?n.trim():null))})}var Dj=!1;Dj&&cm().parseAsync(process.argv).catch(t=>k(t instanceof Error?t.message:String(t)));cm().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
1745
1811
  `),process.exit(1)});