@turbobase/cli 1.5.0 → 1.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/turbobase-standalone.mjs +443 -158
- package/dist/turbobase.js +462 -177
- package/package.json +1 -1
|
@@ -1,47 +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
|
|
4
|
+
var IS=Object.create;var al=Object.defineProperty;var OS=Object.getOwnPropertyDescriptor;var CS=Object.getOwnPropertyNames;var NS=Object.getPrototypeOf,zS=Object.prototype.hasOwnProperty;var Go=(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)al(t,r,{get:e[r],enumerable:!0})},jS=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of CS(e))!zS.call(t,o)&&o!==r&&al(t,o,{get:()=>e[o],enumerable:!(n=OS(e,o))||n.enumerable});return t};var cl=(t,e,r)=>(r=t!=null?IS(NS(t)):{},jS(e||!t||!t.__esModule?al(r,"default",{value:t,enumerable:!0}):r,t));var Yo=Z(ul=>{var Si=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}},ll=class extends Si{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ul.CommanderError=Si;ul.InvalidArgumentError=ll});var Ti=Z(pl=>{var{InvalidArgumentError:LS}=Yo(),dl=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 LS(`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 DS(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}pl.Argument=dl;pl.humanReadableArgName=DS});var fl=Z(Wm=>{var{humanReadableArgName:US}=Ti(),hl=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=>US(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(h,b){if(b){let $=`${h.padEnd(n+i)}${b}`;return r.wrap($,o-s,n+i)}return h}function c(h){return h.join(`
|
|
5
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 p=r.visibleArguments(e).map(h=>a(r.argumentTerm(h),r.argumentDescription(h)));p.length>0&&(l=l.concat(["Arguments:",c(p),""]));let w=r.visibleOptions(e).map(h=>a(r.optionTerm(h),r.optionDescription(h)));if(w.length>0&&(l=l.concat(["Options:",c(w),""])),this.showGlobalOptions){let h=r.visibleGlobalOptions(e).map(b=>a(r.optionTerm(b),r.optionDescription(b)));h.length>0&&(l=l.concat(["Global Options:",c(h),""]))}let m=r.visibleCommands(e).map(h=>a(r.subcommandTerm(h),r.subcommandDescription(h)));return m.length>0&&(l=l.concat(["Commands:",c(m),""])),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
8
|
`),u=" ".repeat(n),w="\\s\u200B",m=new RegExp(`
|
|
9
|
-
|.{1,${a-1}}([${w}]|$)|[^${w}]+?([${w}]|$)`,"g"),h=l.match(m)||[];return c+h.map((b
|
|
10
|
-
`?"":(
|
|
11
|
-
`)}};
|
|
9
|
+
|.{1,${a-1}}([${w}]|$)|[^${w}]+?([${w}]|$)`,"g"),h=l.match(m)||[];return c+h.map((b,$)=>b===`
|
|
10
|
+
`?"":($>0?u:"")+b.trimEnd()).join(`
|
|
11
|
+
`)}};Wm.Help=hl});var yl=Z(Ei=>{var{InvalidArgumentError:MS}=Yo(),ml=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=Gm(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 MS(`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 qS(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},gl=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 qS(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Gm(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}}Ei.Option=ml;Ei.splitOptionFlags=Gm;Ei.DualOptions=gl});var Ym=Z(Jm=>{function ZS(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 BS(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=ZS(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]}?)`:""}
|
|
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
|
|
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
|
|
13
|
+
(Did you mean ${n[0]}?)`:""}Jm.suggestSimilar=BS});var ng=Z(rg=>{var FS=Go("events").EventEmitter,bl=Go("child_process"),wr=Go("path"),wl=Go("fs"),Ue=Go("process"),{Argument:HS,humanReadableArgName:VS}=Ti(),{CommanderError:vl}=Yo(),{Help:KS}=fl(),{Option:Xm,splitOptionFlags:WS,DualOptions:GS}=yl(),{suggestSimilar:Qm}=Ym(),_l=class t extends FS{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=>Ue.stdout.write(r),writeErr:r=>Ue.stderr.write(r),getOutHelpWidth:()=>Ue.stdout.isTTY?Ue.stdout.columns:void 0,getErrHelpWidth:()=>Ue.stderr.isTTY?Ue.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 KS,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 HS(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 vl(e,r,n)),Ue.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 Xm(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 Xm)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=Ue.argv,Ue.versions&&Ue.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":Ue.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,p){let w=wr.resolve(u,p);if(wl.existsSync(w))return w;if(o.includes(wr.extname(p)))return;let m=o.find(h=>wl.existsSync(`${w}${h}`));if(m)return`${w}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=wl.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=wr.resolve(wr.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let p=wr.basename(this._scriptPath,wr.extname(this._scriptPath));p!==this._name&&(u=s(a,`${p}-${e._name}`))}i=u||i}n=o.includes(wr.extname(i));let c;Ue.platform!=="win32"?n?(r.unshift(i),r=tg(Ue.execArgv).concat(r),c=bl.spawn(Ue.argv[0],r,{stdio:"inherit"})):c=bl.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=tg(Ue.execArgv).concat(r),c=bl.spawn(Ue.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{Ue.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});let l=this._exitCallback;l?c.on("close",()=>{l(new vl(Ue.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",Ue.exit.bind(Ue)),c.on("error",u=>{if(u.code==="ENOENT"){let p=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",w=`'${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
|
-
- ${p}`;throw new Error(w)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Ue.exit(1);else{let p=new
|
|
18
|
+
- ${p}`;throw new Error(w)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Ue.exit(1);else{let p=new vl(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,l(p)}}),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 eg(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),eg(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
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 Ue.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()}`,Ue.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new GS(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(p=>p.negate&&a===p.attributeName()),u=this.options.find(p=>!p.negate&&a===p.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=Qm(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=Qm(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=>
|
|
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=>VS(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=wr.basename(e,wr.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=WS(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let r=Ue.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 Xm(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function eg(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})}tg.Command=vl});var ig=Z((Jt,sg)=>{var{Argument:WS}=Si(),{Command:ng}=rg(),{CommanderError:JS,InvalidArgumentError:og}=Qo(),{Help:YS}=hl(),{Option:QS}=gl();Jt=sg.exports=new ng;Jt.program=Jt;Jt.Command=ng;Jt.Option=QS;Jt.Argument=WS;Jt.Help=YS;Jt.CommanderError=JS;Jt.InvalidArgumentError=og;Jt.InvalidOptionArgumentError=og});function Xo(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var Ei=N(()=>{});var ge,_l,F,lr,es=N(()=>{(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})(ge||(ge={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(_l||(_l={}));F=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),lr=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 L,XS,_t,Ri=N(()=>{es();L=ge.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"]),XS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),_t=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,ge.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()}};_t.create=t=>new _t(t)});var eT,_r,xl=N(()=>{Ri();es();eT=(t,e)=>{let r;switch(t.code){case L.invalid_type:t.received===F.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case L.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ge.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:r=`Unrecognized key(s) in object: ${ge.joinValues(t.keys,", ")}`;break;case L.invalid_union:r="Invalid input";break;case L.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ge.joinValues(t.options)}`;break;case L.invalid_enum_value:r=`Invalid enum value. Expected ${ge.joinValues(t.options)}, received '${t.received}'`;break;case L.invalid_arguments:r="Invalid function arguments";break;case L.invalid_return_type:r="Invalid function return type";break;case L.invalid_date:r="Invalid date";break;case L.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}"`:ge.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case L.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 L.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 L.custom:r="Invalid input";break;case L.invalid_intersection_types:r="Intersection results could not be merged";break;case L.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case L.not_finite:r="Number must be finite";break;default:r=e.defaultError,ge.assertNever(t)}return{message:r}},_r=eT});function tT(t){lg=t}function Qn(){return lg}var lg,Pi=N(()=>{xl();lg=_r});function B(t,e){let r=Qn(),n=ts({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===_r?void 0:_r].filter(o=>!!o)});t.common.issues.push(n)}var ts,rT,nt,ee,pn,lt,Ai,Ii,jr,Xn,kl=N(()=>{Pi();xl();ts=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}},rT=[];nt=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 ee;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 ee;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}}},ee=Object.freeze({status:"aborted"}),pn=t=>({status:"dirty",value:t}),lt=t=>({status:"valid",value:t}),Ai=t=>t.status==="aborted",Ii=t=>t.status==="dirty",jr=t=>t.status==="valid",Xn=t=>typeof Promise<"u"&&t instanceof Promise});var ug=N(()=>{});var K,dg=N(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(K||(K={}))});function le(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 mg(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 wT(t){return new RegExp(`^${mg(t)}$`)}function gg(t){let e=`${fg}T${mg(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 vT(t,e){return!!((e==="v4"||!e)&&pT.test(t)||(e==="v6"||!e)&&fT.test(t))}function _T(t,e){if(!cT.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 xT(t,e){return!!((e==="v4"||!e)&&hT.test(t)||(e==="v6"||!e)&&mT.test(t))}function kT(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 eo(t){if(t instanceof kt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=xt.create(eo(n))}return new kt({...t._def,shape:()=>e})}else return t instanceof $r?new $r({...t._def,type:eo(t.element)}):t instanceof xt?xt.create(eo(t.unwrap())):t instanceof dr?dr.create(eo(t.unwrap())):t instanceof ur?ur.create(t.items.map(e=>eo(e))):t}function Sl(t,e){let r=lr(t),n=lr(e);if(t===e)return{valid:!0,data:t};if(r===F.object&&n===F.object){let o=ge.objectKeys(e),s=ge.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Sl(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=Sl(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 yg(t,e){return new kn({values:t,typeName:D.ZodEnum,...le(e)})}function hg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function bg(t,e={},r){return t?Dr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=hg(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=hg(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Dr.create()}var Nt,pg,de,nT,oT,sT,iT,aT,cT,lT,uT,dT,$l,pT,hT,fT,mT,gT,yT,fg,bT,Lr,hn,fn,mn,gn,to,yn,bn,Dr,kr,Yt,ro,$r,kt,wn,xr,Oi,vn,ur,Ci,no,oo,Ni,_n,xn,kn,$n,Ur,zt,xt,dr,Sn,Tn,so,$T,rs,ns,En,ST,D,TT,wg,vg,ET,RT,_g,PT,AT,IT,OT,CT,NT,zT,jT,LT,Tl,DT,UT,MT,qT,ZT,BT,FT,HT,VT,KT,GT,WT,JT,YT,QT,XT,e0,t0,r0,n0,o0,s0,i0,a0,xg=N(()=>{Ri();Pi();dg();kl();es();Nt=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}},pg=(t,e)=>{if(jr(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 _t(t.common.issues);return this._error=r,this._error}}};de=class{get description(){return this._def.description}_getType(e){return lr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nt,ctx:{common:e.parent.common,data:e.data,parsedType:lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Xn(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:lr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return pg(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:lr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return jr(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=>jr(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:lr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Xn(o)?o:Promise.resolve(o));return pg(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:L.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 zt({schema:this,typeName:D.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 xt.create(this,this._def)}nullable(){return dr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $r.create(this)}promise(){return Ur.create(this,this._def)}or(e){return wn.create([this,e],this._def)}and(e){return vn.create(this,e,this._def)}transform(e){return new zt({...le(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Sn({...le(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new rs({typeName:D.ZodBranded,type:this,...le(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Tn({...le(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ns.create(this,e)}readonly(){return En.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},nT=/^c[^\s-]{8,}$/i,oT=/^[0-9a-z]+$/,sT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,iT=/^[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,aT=/^[a-z0-9_-]{21}$/i,cT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,lT=/^[-+]?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)?)??$/,uT=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,dT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",pT=/^(?:(?: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])$/,hT=/^(?:(?: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])$/,fT=/^(([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]))$/,mT=/^(([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])$/,gT=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yT=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fg="((\\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])))",bT=new RegExp(`^${fg}$`);Lr=class t extends de{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==F.string){let s=this._getOrReturnCtx(e);return B(s,{code:L.invalid_type,expected:F.string,received:s.parsedType}),ee}let n=new nt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),B(o,{code:L.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),B(o,{code:L.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?B(o,{code:L.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&B(o,{code:L.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")uT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"email",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")$l||($l=new RegExp(dT,"u")),$l.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"emoji",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")iT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"uuid",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")aT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"nanoid",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")nT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"cuid",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")oT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"cuid2",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")sT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"ulid",code:L.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),B(o,{validation:"url",code:L.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),B(o,{validation:"regex",code:L.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),B(o,{code:L.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),B(o,{code:L.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),B(o,{code:L.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?gg(s).test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{code:L.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?bT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{code:L.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?wT(s).test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{code:L.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?lT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"duration",code:L.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?vT(e.data,s.version)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"ip",code:L.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?_T(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"jwt",code:L.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?xT(e.data,s.version)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"cidr",code:L.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?gT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"base64",code:L.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?yT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"base64url",code:L.invalid_string,message:s.message}),n.dirty()):ge.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:L.invalid_string,...K.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...K.errToObj(e)})}url(e){return this._addCheck({kind:"url",...K.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...K.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...K.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...K.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...K.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...K.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...K.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...K.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...K.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...K.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...K.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...K.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,...K.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,...K.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...K.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...K.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...K.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...K.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...K.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...K.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...K.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...K.errToObj(r)})}nonempty(e){return this.min(1,K.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}};Lr.create=t=>new Lr({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...le(t)});hn=class t extends de{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 B(s,{code:L.invalid_type,expected:F.number,received:s.parsedType}),ee}let n,o=new nt;for(let s of this._def.checks)s.kind==="int"?ge.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:L.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),B(n,{code:L.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),B(n,{code:L.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?kT(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),B(n,{code:L.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:L.not_finite,message:s.message}),o.dirty()):ge.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,K.toString(r))}gt(e,r){return this.setLimit("min",e,!1,K.toString(r))}lte(e,r){return this.setLimit("max",e,!0,K.toString(r))}lt(e,r){return this.setLimit("max",e,!1,K.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:K.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:K.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:K.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:K.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.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"&&ge.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)}};hn.create=t=>new hn({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...le(t)});fn=class t extends de{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 nt;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),B(n,{code:L.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),B(n,{code:L.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),B(n,{code:L.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ge.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return B(r,{code:L.invalid_type,expected:F.bigint,received:r.parsedType}),ee}gte(e,r){return this.setLimit("min",e,!0,K.toString(r))}gt(e,r){return this.setLimit("min",e,!1,K.toString(r))}lte(e,r){return this.setLimit("max",e,!0,K.toString(r))}lt(e,r){return this.setLimit("max",e,!1,K.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:K.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:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:K.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}};fn.create=t=>new fn({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...le(t)});mn=class extends de{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==F.boolean){let n=this._getOrReturnCtx(e);return B(n,{code:L.invalid_type,expected:F.boolean,received:n.parsedType}),ee}return lt(e.data)}};mn.create=t=>new mn({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...le(t)});gn=class t extends de{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==F.date){let s=this._getOrReturnCtx(e);return B(s,{code:L.invalid_type,expected:F.date,received:s.parsedType}),ee}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return B(s,{code:L.invalid_date}),ee}let n=new nt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),B(o,{code:L.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),B(o,{code:L.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ge.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:K.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:K.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}};gn.create=t=>new gn({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...le(t)});to=class extends de{_parse(e){if(this._getType(e)!==F.symbol){let n=this._getOrReturnCtx(e);return B(n,{code:L.invalid_type,expected:F.symbol,received:n.parsedType}),ee}return lt(e.data)}};to.create=t=>new to({typeName:D.ZodSymbol,...le(t)});yn=class extends de{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return B(n,{code:L.invalid_type,expected:F.undefined,received:n.parsedType}),ee}return lt(e.data)}};yn.create=t=>new yn({typeName:D.ZodUndefined,...le(t)});bn=class extends de{_parse(e){if(this._getType(e)!==F.null){let n=this._getOrReturnCtx(e);return B(n,{code:L.invalid_type,expected:F.null,received:n.parsedType}),ee}return lt(e.data)}};bn.create=t=>new bn({typeName:D.ZodNull,...le(t)});Dr=class extends de{constructor(){super(...arguments),this._any=!0}_parse(e){return lt(e.data)}};Dr.create=t=>new Dr({typeName:D.ZodAny,...le(t)});kr=class extends de{constructor(){super(...arguments),this._unknown=!0}_parse(e){return lt(e.data)}};kr.create=t=>new kr({typeName:D.ZodUnknown,...le(t)});Yt=class extends de{_parse(e){let r=this._getOrReturnCtx(e);return B(r,{code:L.invalid_type,expected:F.never,received:r.parsedType}),ee}};Yt.create=t=>new Yt({typeName:D.ZodNever,...le(t)});ro=class extends de{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return B(n,{code:L.invalid_type,expected:F.void,received:n.parsedType}),ee}return lt(e.data)}};ro.create=t=>new ro({typeName:D.ZodVoid,...le(t)});$r=class t extends de{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==F.array)return B(r,{code:L.invalid_type,expected:F.array,received:r.parsedType}),ee;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(B(r,{code:i?L.too_big:L.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&&(B(r,{code:L.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&&(B(r,{code:L.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 Nt(r,i,r.path,a)))).then(i=>nt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Nt(r,i,r.path,a)));return nt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:K.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:K.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:K.toString(r)}})}nonempty(e){return this.min(1,e)}};$r.create=(t,e)=>new $r({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...le(e)});kt=class t extends de{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=ge.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 B(l,{code:L.invalid_type,expected:F.object,received:l.parsedType}),ee}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Yt&&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],p=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Nt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Yt){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&&(B(o,{code:L.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 p=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Nt(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,w=await u.value;l.push({key:p,value:w,alwaysSet:u.alwaysSet})}return l}).then(l=>nt.mergeObjectSync(n,l)):nt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return K.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:K.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:D.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 ge.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 ge.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return eo(this)}partial(e){let r={};for(let n of ge.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 ge.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof xt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return yg(ge.objectKeys(this.shape))}};kt.create=(t,e)=>new kt({shape:()=>t,unknownKeys:"strip",catchall:Yt.create(),typeName:D.ZodObject,...le(e)});kt.strictCreate=(t,e)=>new kt({shape:()=>t,unknownKeys:"strict",catchall:Yt.create(),typeName:D.ZodObject,...le(e)});kt.lazycreate=(t,e)=>new kt({shape:t,unknownKeys:"strip",catchall:Yt.create(),typeName:D.ZodObject,...le(e)});wn=class extends de{_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 _t(a.ctx.common.issues));return B(r,{code:L.invalid_union,unionErrors:i}),ee}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 _t(c));return B(r,{code:L.invalid_union,unionErrors:a}),ee}}get options(){return this._def.options}};wn.create=(t,e)=>new wn({options:t,typeName:D.ZodUnion,...le(e)});xr=t=>t instanceof _n?xr(t.schema):t instanceof zt?xr(t.innerType()):t instanceof xn?[t.value]:t instanceof kn?t.options:t instanceof $n?ge.objectValues(t.enum):t instanceof Sn?xr(t._def.innerType):t instanceof yn?[void 0]:t instanceof bn?[null]:t instanceof xt?[void 0,...xr(t.unwrap())]:t instanceof dr?[null,...xr(t.unwrap())]:t instanceof rs||t instanceof En?xr(t.unwrap()):t instanceof Tn?xr(t._def.innerType):[],Oi=class t extends de{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.object)return B(r,{code:L.invalid_type,expected:F.object,received:r.parsedType}),ee;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}):(B(r,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ee)}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=xr(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:D.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...le(n)})}};vn=class extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Ai(s)||Ai(i))return ee;let a=Sl(s.value,i.value);return a.valid?((Ii(s)||Ii(i))&&r.dirty(),{status:r.value,value:a.data}):(B(n,{code:L.invalid_intersection_types}),ee)};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}))}};vn.create=(t,e,r)=>new vn({left:t,right:e,typeName:D.ZodIntersection,...le(r)});ur=class t extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.array)return B(n,{code:L.invalid_type,expected:F.array,received:n.parsedType}),ee;if(n.data.length<this._def.items.length)return B(n,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&n.data.length>this._def.items.length&&(B(n,{code:L.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 Nt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>nt.mergeArray(r,i)):nt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ur.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ur({items:t,typeName:D.ZodTuple,rest:null,...le(e)})};Ci=class t extends de{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 B(n,{code:L.invalid_type,expected:F.object,received:n.parsedType}),ee;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Nt(n,a,n.path,a)),value:i._parse(new Nt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?nt.mergeObjectAsync(r,o):nt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof de?new t({keyType:e,valueType:r,typeName:D.ZodRecord,...le(n)}):new t({keyType:Lr.create(),valueType:e,typeName:D.ZodRecord,...le(r)})}},no=class extends de{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 B(n,{code:L.invalid_type,expected:F.map,received:n.parsedType}),ee;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new Nt(n,a,n.path,[l,"key"])),value:s._parse(new Nt(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 ee;(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 ee;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};no.create=(t,e,r)=>new no({valueType:e,keyType:t,typeName:D.ZodMap,...le(r)});oo=class t extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.set)return B(n,{code:L.invalid_type,expected:F.set,received:n.parsedType}),ee;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(B(n,{code:L.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&&(B(n,{code:L.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 ee;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 Nt(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:K.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:K.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};oo.create=(t,e)=>new oo({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...le(e)});Ni=class t extends de{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.function)return B(r,{code:L.invalid_type,expected:F.function,received:r.parsedType}),ee;function n(a,c){return ts({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Qn(),_r].filter(l=>!!l),issueData:{code:L.invalid_arguments,argumentsError:c}})}function o(a,c){return ts({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Qn(),_r].filter(l=>!!l),issueData:{code:L.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Ur){let a=this;return lt(async function(...c){let l=new _t([]),u=await a._def.args.parseAsync(c,s).catch(m=>{throw l.addIssue(n(c,m)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(m=>{throw l.addIssue(o(p,m)),l})})}else{let a=this;return lt(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new _t([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new _t([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ur.create(e).rest(kr.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||ur.create([]).rest(kr.create()),returns:r||kr.create(),typeName:D.ZodFunction,...le(n)})}},_n=class extends de{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})}};_n.create=(t,e)=>new _n({getter:t,typeName:D.ZodLazy,...le(e)});xn=class extends de{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return B(r,{received:r.data,code:L.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}};xn.create=(t,e)=>new xn({value:t,typeName:D.ZodLiteral,...le(e)});kn=class t extends de{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return B(r,{expected:ge.joinValues(n),received:r.parsedType,code:L.invalid_type}),ee}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 B(r,{received:r.data,code:L.invalid_enum_value,options:n}),ee}return lt(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})}};kn.create=yg;$n=class extends de{_parse(e){let r=ge.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==F.string&&n.parsedType!==F.number){let o=ge.objectValues(r);return B(n,{expected:ge.joinValues(o),received:n.parsedType,code:L.invalid_type}),ee}if(this._cache||(this._cache=new Set(ge.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ge.objectValues(r);return B(n,{received:n.data,code:L.invalid_enum_value,options:o}),ee}return lt(e.data)}get enum(){return this._def.values}};$n.create=(t,e)=>new $n({values:t,typeName:D.ZodNativeEnum,...le(e)});Ur=class extends de{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.promise&&r.common.async===!1)return B(r,{code:L.invalid_type,expected:F.promise,received:r.parsedType}),ee;let n=r.parsedType===F.promise?r.data:Promise.resolve(r.data);return lt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ur.create=(t,e)=>new Ur({type:t,typeName:D.ZodPromise,...le(e)});zt=class extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.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=>{B(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 ee;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?ee:c.status==="dirty"?pn(c.value):r.value==="dirty"?pn(c.value):c});{if(r.value==="aborted")return ee;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?ee:a.status==="dirty"?pn(a.value):r.value==="dirty"?pn(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"?ee:(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"?ee:(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(!jr(i))return ee;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=>jr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):ee);ge.assertNever(o)}};zt.create=(t,e,r)=>new zt({schema:t,typeName:D.ZodEffects,effect:e,...le(r)});zt.createWithPreprocess=(t,e,r)=>new zt({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...le(r)});xt=class extends de{_parse(e){return this._getType(e)===F.undefined?lt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xt.create=(t,e)=>new xt({innerType:t,typeName:D.ZodOptional,...le(e)});dr=class extends de{_parse(e){return this._getType(e)===F.null?lt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};dr.create=(t,e)=>new dr({innerType:t,typeName:D.ZodNullable,...le(e)});Sn=class extends de{_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}};Sn.create=(t,e)=>new Sn({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...le(e)});Tn=class extends de{_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 Xn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Tn.create=(t,e)=>new Tn({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...le(e)});so=class extends de{_parse(e){if(this._getType(e)!==F.nan){let n=this._getOrReturnCtx(e);return B(n,{code:L.invalid_type,expected:F.nan,received:n.parsedType}),ee}return{status:"valid",value:e.data}}};so.create=t=>new so({typeName:D.ZodNaN,...le(t)});$T=Symbol("zod_brand"),rs=class extends de{_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}},ns=class t extends de{_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"?ee:s.status==="dirty"?(r.dirty(),pn(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"?ee: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:D.ZodPipeline})}},En=class extends de{_parse(e){let r=this._def.innerType._parse(e),n=o=>(jr(o)&&(o.value=Object.freeze(o.value)),o);return Xn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};En.create=(t,e)=>new En({innerType:t,typeName:D.ZodReadonly,...le(e)});ST={object:kt.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"})(D||(D={}));TT=(t,e={message:`Input not instance of ${t.name}`})=>bg(r=>r instanceof t,e),wg=Lr.create,vg=hn.create,ET=so.create,RT=fn.create,_g=mn.create,PT=gn.create,AT=to.create,IT=yn.create,OT=bn.create,CT=Dr.create,NT=kr.create,zT=Yt.create,jT=ro.create,LT=$r.create,Tl=kt.create,DT=kt.strictCreate,UT=wn.create,MT=Oi.create,qT=vn.create,ZT=ur.create,BT=Ci.create,FT=no.create,HT=oo.create,VT=Ni.create,KT=_n.create,GT=xn.create,WT=kn.create,JT=$n.create,YT=Ur.create,QT=zt.create,XT=xt.create,e0=dr.create,t0=zt.createWithPreprocess,r0=ns.create,n0=()=>wg().optional(),o0=()=>vg().optional(),s0=()=>_g().optional(),i0={string:(t=>Lr.create({...t,coerce:!0})),number:(t=>hn.create({...t,coerce:!0})),boolean:(t=>mn.create({...t,coerce:!0})),bigint:(t=>fn.create({...t,coerce:!0})),date:(t=>gn.create({...t,coerce:!0}))},a0=ee});var j={};Yo(j,{BRAND:()=>$T,DIRTY:()=>pn,EMPTY_PATH:()=>rT,INVALID:()=>ee,NEVER:()=>a0,OK:()=>lt,ParseStatus:()=>nt,Schema:()=>de,ZodAny:()=>Dr,ZodArray:()=>$r,ZodBigInt:()=>fn,ZodBoolean:()=>mn,ZodBranded:()=>rs,ZodCatch:()=>Tn,ZodDate:()=>gn,ZodDefault:()=>Sn,ZodDiscriminatedUnion:()=>Oi,ZodEffects:()=>zt,ZodEnum:()=>kn,ZodError:()=>_t,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Ni,ZodIntersection:()=>vn,ZodIssueCode:()=>L,ZodLazy:()=>_n,ZodLiteral:()=>xn,ZodMap:()=>no,ZodNaN:()=>so,ZodNativeEnum:()=>$n,ZodNever:()=>Yt,ZodNull:()=>bn,ZodNullable:()=>dr,ZodNumber:()=>hn,ZodObject:()=>kt,ZodOptional:()=>xt,ZodParsedType:()=>F,ZodPipeline:()=>ns,ZodPromise:()=>Ur,ZodReadonly:()=>En,ZodRecord:()=>Ci,ZodSchema:()=>de,ZodSet:()=>oo,ZodString:()=>Lr,ZodSymbol:()=>to,ZodTransformer:()=>zt,ZodTuple:()=>ur,ZodType:()=>de,ZodUndefined:()=>yn,ZodUnion:()=>wn,ZodUnknown:()=>kr,ZodVoid:()=>ro,addIssueToContext:()=>B,any:()=>CT,array:()=>LT,bigint:()=>RT,boolean:()=>_g,coerce:()=>i0,custom:()=>bg,date:()=>PT,datetimeRegex:()=>gg,defaultErrorMap:()=>_r,discriminatedUnion:()=>MT,effect:()=>QT,enum:()=>WT,function:()=>VT,getErrorMap:()=>Qn,getParsedType:()=>lr,instanceof:()=>TT,intersection:()=>qT,isAborted:()=>Ai,isAsync:()=>Xn,isDirty:()=>Ii,isValid:()=>jr,late:()=>ST,lazy:()=>KT,literal:()=>GT,makeIssue:()=>ts,map:()=>FT,nan:()=>ET,nativeEnum:()=>JT,never:()=>zT,null:()=>OT,nullable:()=>e0,number:()=>vg,object:()=>Tl,objectUtil:()=>_l,oboolean:()=>s0,onumber:()=>o0,optional:()=>XT,ostring:()=>n0,pipeline:()=>r0,preprocess:()=>t0,promise:()=>YT,quotelessJson:()=>XS,record:()=>BT,set:()=>HT,setErrorMap:()=>tT,strictObject:()=>DT,string:()=>wg,symbol:()=>AT,transformer:()=>QT,tuple:()=>ZT,undefined:()=>IT,union:()=>UT,unknown:()=>NT,util:()=>ge,void:()=>jT});var zi=N(()=>{Pi();kl();ug();es();xg();Ri()});var io=N(()=>{zi();zi()});function ji(t){let e=El.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Rl(t,e){let r=El.safeParse(t);if(!r.success)throw new Mr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(kg.test(e))throw new Mr('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(kg.test(n))throw new Mr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var $g,Sg,El,Mr,kg,Tg=N(()=>{io();$g=j.object({type:j.literal("connection"),source_system:j.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:j.string().min(1).max(200).optional()}),Sg=j.discriminatedUnion("type",[$g]),El=j.object({inputs:j.array(Sg).optional()}).passthrough(),Mr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};kg=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Li,Pl=N(()=>{Li=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var Al,Eg,Rg=N(()=>{io();Ei();Pl();Al=j.object({id:j.string().min(1,"hook id must be non-empty"),recordType:j.union([j.string().min(1),j.array(j.string().min(1)).min(1),j.literal("*")]),event:j.enum(Li),source:j.string().min(1).optional(),when:j.unknown().optional(),run:j.unknown(),failClosed:j.boolean().optional(),timeoutMs:j.number().int().positive().optional(),description:j.string().optional(),systemReserved:j.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"})}),Eg=Xo({kind:"hook",schema:Al,factoryName:"defineHook"})});var Pg=N(()=>{Rg();Pl()});var Di,Il=N(()=>{Di=["after_canonicalize_inbound","after_sync_success_outbound"]});var Ol,Ag,Ig=N(()=>{io();Ei();Il();Ol=j.object({id:j.string().min(1,"conduit id must be non-empty"),on:j.enum(Di),from:j.object({source:j.string().min(1,"from.source must be non-empty"),recordType:j.string().min(1,"from.recordType must be non-empty"),when:j.unknown().optional()}),to:j.object({source:j.string().min(1,"to.source must be non-empty"),recordType:j.string().min(1,"to.recordType must be non-empty")}),mode:j.enum(["dual-bind","one-shot"]).optional(),transform:j.unknown(),idempotencyKey:j.unknown().optional(),cycleBudget:j.number().int().positive().optional(),conflictStrategy:j.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:j.number().int().positive().optional(),description:j.string().optional(),systemReserved:j.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"})}),Ag=Xo({kind:"conduit",schema:Ol,factoryName:"defineConduit"})});var Og=N(()=>{Ig();Il()});async function p0(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 Ui(t,e={}){return(e.transform??p0)(t)}var Cl=N(()=>{});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 Cg(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function zl(t){return`${Cg(t.source)}${Cg(t.recordType)}`}function h0(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function f0(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 jl(t){let e=zl(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 eg(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function tg(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})}rg.Command=_l});var ag=Z((Gt,ig)=>{var{Argument:JS}=Ti(),{Command:og}=ng(),{CommanderError:YS,InvalidArgumentError:sg}=Yo(),{Help:XS}=fl(),{Option:QS}=yl();Gt=ig.exports=new og;Gt.program=Gt;Gt.Command=og;Gt.Option=QS;Gt.Argument=JS;Gt.Help=XS;Gt.CommanderError=YS;Gt.InvalidArgumentError=sg;Gt.InvalidOptionArgumentError=sg});function Xo(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var Ri=O(()=>{});var ge,xl,F,cr,Qo=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})(ge||(ge={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(xl||(xl={}));F=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),cr=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 D,eT,_t,Pi=O(()=>{Qo();D=ge.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"]),eT=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),_t=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,ge.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()}};_t.create=t=>new _t(t)});var tT,vr,kl=O(()=>{Pi();Qo();tT=(t,e)=>{let r;switch(t.code){case D.invalid_type:t.received===F.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case D.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ge.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:r=`Unrecognized key(s) in object: ${ge.joinValues(t.keys,", ")}`;break;case D.invalid_union:r="Invalid input";break;case D.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ge.joinValues(t.options)}`;break;case D.invalid_enum_value:r=`Invalid enum value. Expected ${ge.joinValues(t.options)}, received '${t.received}'`;break;case D.invalid_arguments:r="Invalid function arguments";break;case D.invalid_return_type:r="Invalid function return type";break;case D.invalid_date:r="Invalid date";break;case D.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}"`:ge.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case D.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 D.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 D.custom:r="Invalid input";break;case D.invalid_intersection_types:r="Intersection results could not be merged";break;case D.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case D.not_finite:r="Number must be finite";break;default:r=e.defaultError,ge.assertNever(t)}return{message:r}},vr=tT});function rT(t){ug=t}function Yn(){return ug}var ug,Ai=O(()=>{kl();ug=vr});function B(t,e){let r=Yn(),n=es({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===vr?void 0:vr].filter(o=>!!o)});t.common.issues.push(n)}var es,nT,nt,re,dn,lt,Ii,Oi,Lr,Xn,$l=O(()=>{Ai();kl();es=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}},nT=[];nt=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 re;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 re;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}}},re=Object.freeze({status:"aborted"}),dn=t=>({status:"dirty",value:t}),lt=t=>({status:"valid",value:t}),Ii=t=>t.status==="aborted",Oi=t=>t.status==="dirty",Lr=t=>t.status==="valid",Xn=t=>typeof Promise<"u"&&t instanceof Promise});var dg=O(()=>{});var W,pg=O(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(W||(W={}))});function le(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 gg(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 vT(t){return new RegExp(`^${gg(t)}$`)}function yg(t){let e=`${mg}T${gg(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 _T(t,e){return!!((e==="v4"||!e)&&hT.test(t)||(e==="v6"||!e)&&mT.test(t))}function xT(t,e){if(!lT.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 kT(t,e){return!!((e==="v4"||!e)&&fT.test(t)||(e==="v6"||!e)&&gT.test(t))}function $T(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 Qn(t){if(t instanceof kt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=xt.create(Qn(n))}return new kt({...t._def,shape:()=>e})}else return t instanceof kr?new kr({...t._def,type:Qn(t.element)}):t instanceof xt?xt.create(Qn(t.unwrap())):t instanceof ur?ur.create(Qn(t.unwrap())):t instanceof lr?lr.create(t.items.map(e=>Qn(e))):t}function Tl(t,e){let r=cr(t),n=cr(e);if(t===e)return{valid:!0,data:t};if(r===F.object&&n===F.object){let o=ge.objectKeys(e),s=ge.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Tl(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=Tl(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 bg(t,e){return new xn({values:t,typeName:U.ZodEnum,...le(e)})}function fg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function wg(t,e={},r){return t?Ur.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=fg(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=fg(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Ur.create()}var zt,hg,de,oT,sT,iT,aT,cT,lT,uT,dT,pT,Sl,hT,fT,mT,gT,yT,bT,mg,wT,Dr,pn,hn,fn,mn,eo,gn,yn,Ur,xr,Jt,to,kr,kt,bn,_r,Ci,wn,lr,Ni,ro,no,zi,vn,_n,xn,kn,Mr,jt,xt,ur,$n,Sn,oo,ST,ts,rs,Tn,TT,U,ET,vg,_g,RT,PT,xg,AT,IT,OT,CT,NT,zT,jT,LT,DT,El,UT,MT,qT,ZT,BT,FT,HT,VT,KT,WT,GT,JT,YT,XT,QT,eE,tE,rE,nE,oE,sE,iE,aE,cE,kg=O(()=>{Pi();Ai();pg();$l();Qo();zt=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}},hg=(t,e)=>{if(Lr(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 _t(t.common.issues);return this._error=r,this._error}}};de=class{get description(){return this._def.description}_getType(e){return cr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:cr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nt,ctx:{common:e.parent.common,data:e.data,parsedType:cr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Xn(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:cr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return hg(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:cr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Lr(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=>Lr(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:cr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Xn(o)?o:Promise.resolve(o));return hg(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:D.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 jt({schema:this,typeName:U.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 xt.create(this,this._def)}nullable(){return ur.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return kr.create(this)}promise(){return Mr.create(this,this._def)}or(e){return bn.create([this,e],this._def)}and(e){return wn.create(this,e,this._def)}transform(e){return new jt({...le(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new $n({...le(this._def),innerType:this,defaultValue:r,typeName:U.ZodDefault})}brand(){return new ts({typeName:U.ZodBranded,type:this,...le(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Sn({...le(this._def),innerType:this,catchValue:r,typeName:U.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return rs.create(this,e)}readonly(){return Tn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},oT=/^c[^\s-]{8,}$/i,sT=/^[0-9a-z]+$/,iT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,aT=/^[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,cT=/^[a-z0-9_-]{21}$/i,lT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,uT=/^[-+]?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)?)??$/,dT=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,pT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",hT=/^(?:(?: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])$/,fT=/^(?:(?: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])$/,mT=/^(([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]))$/,gT=/^(([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])$/,yT=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,bT=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mg="((\\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])))",wT=new RegExp(`^${mg}$`);Dr=class t extends de{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==F.string){let s=this._getOrReturnCtx(e);return B(s,{code:D.invalid_type,expected:F.string,received:s.parsedType}),re}let n=new nt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),B(o,{code:D.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),B(o,{code:D.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?B(o,{code:D.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&B(o,{code:D.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")dT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"email",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Sl||(Sl=new RegExp(pT,"u")),Sl.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"emoji",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")aT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"uuid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")cT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"nanoid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")oT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"cuid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")sT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"cuid2",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")iT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"ulid",code:D.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),B(o,{validation:"url",code:D.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),B(o,{validation:"regex",code:D.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),B(o,{code:D.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),B(o,{code:D.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),B(o,{code:D.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?yg(s).test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{code:D.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?wT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{code:D.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?vT(s).test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{code:D.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?uT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"duration",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?_T(e.data,s.version)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"ip",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?xT(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"jwt",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?kT(e.data,s.version)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"cidr",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?yT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"base64",code:D.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?bT.test(e.data)||(o=this._getOrReturnCtx(e,o),B(o,{validation:"base64url",code:D.invalid_string,message:s.message}),n.dirty()):ge.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:D.invalid_string,...W.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.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,...W.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,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...W.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...W.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...W.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...W.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...W.errToObj(r)})}nonempty(e){return this.min(1,W.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}};Dr.create=t=>new Dr({checks:[],typeName:U.ZodString,coerce:t?.coerce??!1,...le(t)});pn=class t extends de{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 B(s,{code:D.invalid_type,expected:F.number,received:s.parsedType}),re}let n,o=new nt;for(let s of this._def.checks)s.kind==="int"?ge.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:D.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),B(n,{code:D.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),B(n,{code:D.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?$T(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),B(n,{code:D.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),B(n,{code:D.not_finite,message:s.message}),o.dirty()):ge.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,W.toString(r))}gt(e,r){return this.setLimit("min",e,!1,W.toString(r))}lte(e,r){return this.setLimit("max",e,!0,W.toString(r))}lt(e,r){return this.setLimit("max",e,!1,W.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:W.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.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"&&ge.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)}};pn.create=t=>new pn({checks:[],typeName:U.ZodNumber,coerce:t?.coerce||!1,...le(t)});hn=class t extends de{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 nt;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),B(n,{code:D.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),B(n,{code:D.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),B(n,{code:D.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ge.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return B(r,{code:D.invalid_type,expected:F.bigint,received:r.parsedType}),re}gte(e,r){return this.setLimit("min",e,!0,W.toString(r))}gt(e,r){return this.setLimit("min",e,!1,W.toString(r))}lte(e,r){return this.setLimit("max",e,!0,W.toString(r))}lt(e,r){return this.setLimit("max",e,!1,W.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:W.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:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:W.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}};hn.create=t=>new hn({checks:[],typeName:U.ZodBigInt,coerce:t?.coerce??!1,...le(t)});fn=class extends de{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==F.boolean){let n=this._getOrReturnCtx(e);return B(n,{code:D.invalid_type,expected:F.boolean,received:n.parsedType}),re}return lt(e.data)}};fn.create=t=>new fn({typeName:U.ZodBoolean,coerce:t?.coerce||!1,...le(t)});mn=class t extends de{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==F.date){let s=this._getOrReturnCtx(e);return B(s,{code:D.invalid_type,expected:F.date,received:s.parsedType}),re}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return B(s,{code:D.invalid_date}),re}let n=new nt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),B(o,{code:D.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),B(o,{code:D.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ge.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:W.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:W.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}};mn.create=t=>new mn({checks:[],coerce:t?.coerce||!1,typeName:U.ZodDate,...le(t)});eo=class extends de{_parse(e){if(this._getType(e)!==F.symbol){let n=this._getOrReturnCtx(e);return B(n,{code:D.invalid_type,expected:F.symbol,received:n.parsedType}),re}return lt(e.data)}};eo.create=t=>new eo({typeName:U.ZodSymbol,...le(t)});gn=class extends de{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return B(n,{code:D.invalid_type,expected:F.undefined,received:n.parsedType}),re}return lt(e.data)}};gn.create=t=>new gn({typeName:U.ZodUndefined,...le(t)});yn=class extends de{_parse(e){if(this._getType(e)!==F.null){let n=this._getOrReturnCtx(e);return B(n,{code:D.invalid_type,expected:F.null,received:n.parsedType}),re}return lt(e.data)}};yn.create=t=>new yn({typeName:U.ZodNull,...le(t)});Ur=class extends de{constructor(){super(...arguments),this._any=!0}_parse(e){return lt(e.data)}};Ur.create=t=>new Ur({typeName:U.ZodAny,...le(t)});xr=class extends de{constructor(){super(...arguments),this._unknown=!0}_parse(e){return lt(e.data)}};xr.create=t=>new xr({typeName:U.ZodUnknown,...le(t)});Jt=class extends de{_parse(e){let r=this._getOrReturnCtx(e);return B(r,{code:D.invalid_type,expected:F.never,received:r.parsedType}),re}};Jt.create=t=>new Jt({typeName:U.ZodNever,...le(t)});to=class extends de{_parse(e){if(this._getType(e)!==F.undefined){let n=this._getOrReturnCtx(e);return B(n,{code:D.invalid_type,expected:F.void,received:n.parsedType}),re}return lt(e.data)}};to.create=t=>new to({typeName:U.ZodVoid,...le(t)});kr=class t extends de{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==F.array)return B(r,{code:D.invalid_type,expected:F.array,received:r.parsedType}),re;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(B(r,{code:i?D.too_big:D.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&&(B(r,{code:D.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&&(B(r,{code:D.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 zt(r,i,r.path,a)))).then(i=>nt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new zt(r,i,r.path,a)));return nt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:W.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:W.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:W.toString(r)}})}nonempty(e){return this.min(1,e)}};kr.create=(t,e)=>new kr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...le(e)});kt=class t extends de{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=ge.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 B(l,{code:D.invalid_type,expected:F.object,received:l.parsedType}),re}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Jt&&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],p=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new zt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Jt){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&&(B(o,{code:D.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 p=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new zt(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,w=await u.value;l.push({key:p,value:w,alwaysSet:u.alwaysSet})}return l}).then(l=>nt.mergeObjectSync(n,l)):nt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return W.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:W.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:U.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 ge.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 ge.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Qn(this)}partial(e){let r={};for(let n of ge.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 ge.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof xt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return bg(ge.objectKeys(this.shape))}};kt.create=(t,e)=>new kt({shape:()=>t,unknownKeys:"strip",catchall:Jt.create(),typeName:U.ZodObject,...le(e)});kt.strictCreate=(t,e)=>new kt({shape:()=>t,unknownKeys:"strict",catchall:Jt.create(),typeName:U.ZodObject,...le(e)});kt.lazycreate=(t,e)=>new kt({shape:t,unknownKeys:"strip",catchall:Jt.create(),typeName:U.ZodObject,...le(e)});bn=class extends de{_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 _t(a.ctx.common.issues));return B(r,{code:D.invalid_union,unionErrors:i}),re}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 _t(c));return B(r,{code:D.invalid_union,unionErrors:a}),re}}get options(){return this._def.options}};bn.create=(t,e)=>new bn({options:t,typeName:U.ZodUnion,...le(e)});_r=t=>t instanceof vn?_r(t.schema):t instanceof jt?_r(t.innerType()):t instanceof _n?[t.value]:t instanceof xn?t.options:t instanceof kn?ge.objectValues(t.enum):t instanceof $n?_r(t._def.innerType):t instanceof gn?[void 0]:t instanceof yn?[null]:t instanceof xt?[void 0,..._r(t.unwrap())]:t instanceof ur?[null,..._r(t.unwrap())]:t instanceof ts||t instanceof Tn?_r(t.unwrap()):t instanceof Sn?_r(t._def.innerType):[],Ci=class t extends de{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.object)return B(r,{code:D.invalid_type,expected:F.object,received:r.parsedType}),re;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}):(B(r,{code:D.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),re)}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=_r(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:U.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...le(n)})}};wn=class extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Ii(s)||Ii(i))return re;let a=Tl(s.value,i.value);return a.valid?((Oi(s)||Oi(i))&&r.dirty(),{status:r.value,value:a.data}):(B(n,{code:D.invalid_intersection_types}),re)};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}))}};wn.create=(t,e,r)=>new wn({left:t,right:e,typeName:U.ZodIntersection,...le(r)});lr=class t extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.array)return B(n,{code:D.invalid_type,expected:F.array,received:n.parsedType}),re;if(n.data.length<this._def.items.length)return B(n,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),re;!this._def.rest&&n.data.length>this._def.items.length&&(B(n,{code:D.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 zt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>nt.mergeArray(r,i)):nt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};lr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new lr({items:t,typeName:U.ZodTuple,rest:null,...le(e)})};Ni=class t extends de{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 B(n,{code:D.invalid_type,expected:F.object,received:n.parsedType}),re;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new zt(n,a,n.path,a)),value:i._parse(new zt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?nt.mergeObjectAsync(r,o):nt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof de?new t({keyType:e,valueType:r,typeName:U.ZodRecord,...le(n)}):new t({keyType:Dr.create(),valueType:e,typeName:U.ZodRecord,...le(r)})}},ro=class extends de{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 B(n,{code:D.invalid_type,expected:F.map,received:n.parsedType}),re;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new zt(n,a,n.path,[l,"key"])),value:s._parse(new zt(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 re;(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 re;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};ro.create=(t,e,r)=>new ro({valueType:e,keyType:t,typeName:U.ZodMap,...le(r)});no=class t extends de{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==F.set)return B(n,{code:D.invalid_type,expected:F.set,received:n.parsedType}),re;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(B(n,{code:D.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&&(B(n,{code:D.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 re;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 zt(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:W.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:W.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};no.create=(t,e)=>new no({valueType:t,minSize:null,maxSize:null,typeName:U.ZodSet,...le(e)});zi=class t extends de{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.function)return B(r,{code:D.invalid_type,expected:F.function,received:r.parsedType}),re;function n(a,c){return es({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Yn(),vr].filter(l=>!!l),issueData:{code:D.invalid_arguments,argumentsError:c}})}function o(a,c){return es({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Yn(),vr].filter(l=>!!l),issueData:{code:D.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Mr){let a=this;return lt(async function(...c){let l=new _t([]),u=await a._def.args.parseAsync(c,s).catch(m=>{throw l.addIssue(n(c,m)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(m=>{throw l.addIssue(o(p,m)),l})})}else{let a=this;return lt(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new _t([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new _t([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:lr.create(e).rest(xr.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||lr.create([]).rest(xr.create()),returns:r||xr.create(),typeName:U.ZodFunction,...le(n)})}},vn=class extends de{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})}};vn.create=(t,e)=>new vn({getter:t,typeName:U.ZodLazy,...le(e)});_n=class extends de{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return B(r,{received:r.data,code:D.invalid_literal,expected:this._def.value}),re}return{status:"valid",value:e.data}}get value(){return this._def.value}};_n.create=(t,e)=>new _n({value:t,typeName:U.ZodLiteral,...le(e)});xn=class t extends de{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return B(r,{expected:ge.joinValues(n),received:r.parsedType,code:D.invalid_type}),re}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 B(r,{received:r.data,code:D.invalid_enum_value,options:n}),re}return lt(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})}};xn.create=bg;kn=class extends de{_parse(e){let r=ge.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==F.string&&n.parsedType!==F.number){let o=ge.objectValues(r);return B(n,{expected:ge.joinValues(o),received:n.parsedType,code:D.invalid_type}),re}if(this._cache||(this._cache=new Set(ge.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ge.objectValues(r);return B(n,{received:n.data,code:D.invalid_enum_value,options:o}),re}return lt(e.data)}get enum(){return this._def.values}};kn.create=(t,e)=>new kn({values:t,typeName:U.ZodNativeEnum,...le(e)});Mr=class extends de{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==F.promise&&r.common.async===!1)return B(r,{code:D.invalid_type,expected:F.promise,received:r.parsedType}),re;let n=r.parsedType===F.promise?r.data:Promise.resolve(r.data);return lt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Mr.create=(t,e)=>new Mr({type:t,typeName:U.ZodPromise,...le(e)});jt=class extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.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=>{B(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 re;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?re:c.status==="dirty"?dn(c.value):r.value==="dirty"?dn(c.value):c});{if(r.value==="aborted")return re;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?re:a.status==="dirty"?dn(a.value):r.value==="dirty"?dn(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"?re:(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"?re:(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(!Lr(i))return re;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=>Lr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):re);ge.assertNever(o)}};jt.create=(t,e,r)=>new jt({schema:t,typeName:U.ZodEffects,effect:e,...le(r)});jt.createWithPreprocess=(t,e,r)=>new jt({schema:e,effect:{type:"preprocess",transform:t},typeName:U.ZodEffects,...le(r)});xt=class extends de{_parse(e){return this._getType(e)===F.undefined?lt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xt.create=(t,e)=>new xt({innerType:t,typeName:U.ZodOptional,...le(e)});ur=class extends de{_parse(e){return this._getType(e)===F.null?lt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ur.create=(t,e)=>new ur({innerType:t,typeName:U.ZodNullable,...le(e)});$n=class extends de{_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}};$n.create=(t,e)=>new $n({innerType:t,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...le(e)});Sn=class extends de{_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 Xn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Sn.create=(t,e)=>new Sn({innerType:t,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...le(e)});oo=class extends de{_parse(e){if(this._getType(e)!==F.nan){let n=this._getOrReturnCtx(e);return B(n,{code:D.invalid_type,expected:F.nan,received:n.parsedType}),re}return{status:"valid",value:e.data}}};oo.create=t=>new oo({typeName:U.ZodNaN,...le(t)});ST=Symbol("zod_brand"),ts=class extends de{_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}},rs=class t extends de{_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"?re:s.status==="dirty"?(r.dirty(),dn(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"?re: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:U.ZodPipeline})}},Tn=class extends de{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Lr(o)&&(o.value=Object.freeze(o.value)),o);return Xn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Tn.create=(t,e)=>new Tn({innerType:t,typeName:U.ZodReadonly,...le(e)});TT={object:kt.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"})(U||(U={}));ET=(t,e={message:`Input not instance of ${t.name}`})=>wg(r=>r instanceof t,e),vg=Dr.create,_g=pn.create,RT=oo.create,PT=hn.create,xg=fn.create,AT=mn.create,IT=eo.create,OT=gn.create,CT=yn.create,NT=Ur.create,zT=xr.create,jT=Jt.create,LT=to.create,DT=kr.create,El=kt.create,UT=kt.strictCreate,MT=bn.create,qT=Ci.create,ZT=wn.create,BT=lr.create,FT=Ni.create,HT=ro.create,VT=no.create,KT=zi.create,WT=vn.create,GT=_n.create,JT=xn.create,YT=kn.create,XT=Mr.create,QT=jt.create,eE=xt.create,tE=ur.create,rE=jt.createWithPreprocess,nE=rs.create,oE=()=>vg().optional(),sE=()=>_g().optional(),iE=()=>xg().optional(),aE={string:(t=>Dr.create({...t,coerce:!0})),number:(t=>pn.create({...t,coerce:!0})),boolean:(t=>fn.create({...t,coerce:!0})),bigint:(t=>hn.create({...t,coerce:!0})),date:(t=>mn.create({...t,coerce:!0}))},cE=re});var L={};Jo(L,{BRAND:()=>ST,DIRTY:()=>dn,EMPTY_PATH:()=>nT,INVALID:()=>re,NEVER:()=>cE,OK:()=>lt,ParseStatus:()=>nt,Schema:()=>de,ZodAny:()=>Ur,ZodArray:()=>kr,ZodBigInt:()=>hn,ZodBoolean:()=>fn,ZodBranded:()=>ts,ZodCatch:()=>Sn,ZodDate:()=>mn,ZodDefault:()=>$n,ZodDiscriminatedUnion:()=>Ci,ZodEffects:()=>jt,ZodEnum:()=>xn,ZodError:()=>_t,ZodFirstPartyTypeKind:()=>U,ZodFunction:()=>zi,ZodIntersection:()=>wn,ZodIssueCode:()=>D,ZodLazy:()=>vn,ZodLiteral:()=>_n,ZodMap:()=>ro,ZodNaN:()=>oo,ZodNativeEnum:()=>kn,ZodNever:()=>Jt,ZodNull:()=>yn,ZodNullable:()=>ur,ZodNumber:()=>pn,ZodObject:()=>kt,ZodOptional:()=>xt,ZodParsedType:()=>F,ZodPipeline:()=>rs,ZodPromise:()=>Mr,ZodReadonly:()=>Tn,ZodRecord:()=>Ni,ZodSchema:()=>de,ZodSet:()=>no,ZodString:()=>Dr,ZodSymbol:()=>eo,ZodTransformer:()=>jt,ZodTuple:()=>lr,ZodType:()=>de,ZodUndefined:()=>gn,ZodUnion:()=>bn,ZodUnknown:()=>xr,ZodVoid:()=>to,addIssueToContext:()=>B,any:()=>NT,array:()=>DT,bigint:()=>PT,boolean:()=>xg,coerce:()=>aE,custom:()=>wg,date:()=>AT,datetimeRegex:()=>yg,defaultErrorMap:()=>vr,discriminatedUnion:()=>qT,effect:()=>QT,enum:()=>JT,function:()=>KT,getErrorMap:()=>Yn,getParsedType:()=>cr,instanceof:()=>ET,intersection:()=>ZT,isAborted:()=>Ii,isAsync:()=>Xn,isDirty:()=>Oi,isValid:()=>Lr,late:()=>TT,lazy:()=>WT,literal:()=>GT,makeIssue:()=>es,map:()=>HT,nan:()=>RT,nativeEnum:()=>YT,never:()=>jT,null:()=>CT,nullable:()=>tE,number:()=>_g,object:()=>El,objectUtil:()=>xl,oboolean:()=>iE,onumber:()=>sE,optional:()=>eE,ostring:()=>oE,pipeline:()=>nE,preprocess:()=>rE,promise:()=>XT,quotelessJson:()=>eT,record:()=>FT,set:()=>VT,setErrorMap:()=>rT,strictObject:()=>UT,string:()=>vg,symbol:()=>IT,transformer:()=>QT,tuple:()=>BT,undefined:()=>OT,union:()=>MT,unknown:()=>zT,util:()=>ge,void:()=>LT});var ji=O(()=>{Ai();$l();dg();Qo();kg();Pi()});var so=O(()=>{ji();ji()});function Li(t){let e=Rl.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Pl(t,e){let r=Rl.safeParse(t);if(!r.success)throw new qr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if($g.test(e))throw new qr('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($g.test(n))throw new qr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Sg,Tg,Rl,qr,$g,Eg=O(()=>{so();Sg=L.object({type:L.literal("connection"),source_system:L.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:L.string().min(1).max(200).optional()}),Tg=L.discriminatedUnion("type",[Sg]),Rl=L.object({inputs:L.array(Tg).optional()}).passthrough(),qr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};$g=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Di,Al=O(()=>{Di=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var Il,Rg,Pg=O(()=>{so();Ri();Al();Il=L.object({id:L.string().min(1,"hook id must be non-empty"),recordType:L.union([L.string().min(1),L.array(L.string().min(1)).min(1),L.literal("*")]),event:L.enum(Di),source:L.string().min(1).optional(),when:L.unknown().optional(),run:L.unknown(),failClosed:L.boolean().optional(),timeoutMs:L.number().int().positive().optional(),description:L.string().optional(),systemReserved:L.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"})}),Rg=Xo({kind:"hook",schema:Il,factoryName:"defineHook"})});var Ag=O(()=>{Pg();Al()});var Ui,Ol=O(()=>{Ui=["after_canonicalize_inbound","after_sync_success_outbound"]});var Cl,Ig,Og=O(()=>{so();Ri();Ol();Cl=L.object({id:L.string().min(1,"conduit id must be non-empty"),on:L.enum(Ui),from:L.object({source:L.string().min(1,"from.source must be non-empty"),recordType:L.string().min(1,"from.recordType must be non-empty"),when:L.unknown().optional()}),to:L.object({source:L.string().min(1,"to.source must be non-empty"),recordType:L.string().min(1,"to.recordType must be non-empty")}),mode:L.enum(["dual-bind","one-shot"]).optional(),transform:L.unknown(),idempotencyKey:L.unknown().optional(),cycleBudget:L.number().int().positive().optional(),conflictStrategy:L.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:L.number().int().positive().optional(),description:L.string().optional(),systemReserved:L.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"})}),Ig=Xo({kind:"conduit",schema:Cl,factoryName:"defineConduit"})});var Cg=O(()=>{Og();Ol()});async function hE(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 Mi(t,e={}){return(e.transform??hE)(t)}var Nl=O(()=>{});function zl(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 Ng(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function jl(t){return`${Ng(t.source)}${Ng(t.recordType)}`}function fE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function mE(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 Ll(t){let e=jl(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=
|
|
32
|
-
${
|
|
31
|
+
}`;let o=t.columns.map(s=>{let i=zl(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${mE(s)} */
|
|
32
|
+
${fE(s.name)}${a}: ${i}${c};`});return`${n}
|
|
33
33
|
export interface ${e} {
|
|
34
34
|
${o.join(`
|
|
35
35
|
`)}
|
|
36
|
-
}`}function
|
|
36
|
+
}`}function qi(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Ll).join(`
|
|
37
37
|
|
|
38
|
-
`)}function
|
|
39
|
-
`)}var
|
|
38
|
+
`)}function zg(t){let e=new Map,r=(o,s)=>{let i=e.get(o);i||e.set(o,i=new Map);for(let a of s)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let o of t.records){o.table&&r(o.table,o.columns);for(let s of o.lines??[])r(s.table,s.columns)}let n={};for(let[o,s]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>s.get(a)===!1);if(s.get("parent_pg_row_id")===!1&&i){n[o]=["parent_pg_row_id",i];continue}if(s.get("pg_row_id")===!1){n[o]="pg_row_id";continue}if(s.get("external_id")===!1){n[o]="external_id";continue}}return n}function gE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Dl(t){let e=zg(t);return["/**"," * The seek key each table can be keyset-paged 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."," *"," * An entry may be a TUPLE, and it is passed exactly the same way. A line"," * table is keyed `(parent_pg_row_id, line_index)` and has no correct single"," * column \u2014 every line of one parent shares `parent_pg_row_id`, and"," * `line_index` is unique only within a parent \u2014 so `selectPage` seeks the"," * pair with a row-wise comparison."," *"," * A table with no entry has no keyset-safe key at all; page it by filtering"," * to a bounded subset rather than seeking across the whole table."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,o])=>{let s=Array.isArray(o)?`[${o.map(i=>`'${i}'`).join(", ")}]`:`'${o}'`;return` ${gE(n)}: ${s},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
|
|
39
|
+
`)}var Ul=O(()=>{});function yE(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function jg(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 En(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=yE(t.baseUrl),n=await jg(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=qi(n),s=[bE,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",Dl(n)];if(!t.recordsOnly){let i=await jg(r.openapi,t.token,e),a=await Mi(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
|
|
40
40
|
|
|
41
41
|
`)+`
|
|
42
|
-
`}var
|
|
43
|
-
`)});var
|
|
44
|
-
`,{mode:384})}async function Ug(t){let e=jt(t.baseUrl),r=await os(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await ql(r),{baseUrl:e,token:t.token,updatedAt:n}}async function Qt(t){let e=await os();if(t){let s=jt(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 Zi(t){let e=jt(t),r=await os(),n=r.tenants[e];return n?(r.active=e,await ql(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function Zl(t){let e=await os(),r=t?jt(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 ql(e),r}async function Sr(){let t=await os();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var ss=N(()=>{});function Mg(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 qg(t){return t.replace(/\/+$/,"")}function Bl(t=process.env){let e=(t[ao]??"").trim(),r=(t[Bi]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function Fl(t){let e;try{e=new URL(t)}catch{return`${ao} 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:`${ao} 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 pe,Y,ao,Bi,is,Tr=N(()=>{pe=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};Y=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=qg(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=Mg(a);throw new pe(`${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 proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}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 platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),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/events${n}`)).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}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");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}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}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,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes: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)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode: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`)}},ao="TURBOBASE_REGISTRY_URL",Bi="TURBOBASE_REGISTRY_TOKEN";is=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=qg(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=Mg(a);throw new pe(`${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 _0(t){if(v0.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function k0(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:_0(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:")||S0(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:x0,loader:"js"}))}}}function S0(t){let e=t.startsWith("node:")?t.slice(5):t;return $0.has(e.split("/")[0])}function Zg(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 T0(){try{return(await import("esbuild")).build}catch(t){throw Zg("esbuild",t)}}async function E0(){try{return(await import("isolated-vm")).default}catch(t){throw Zg("isolated-vm",t)}}async function Fi(t){let e=await T0(),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:[k0()]})}catch(n){let s=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new Hl(s||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function as(t,e,r={}){let n=r.timeoutMs??200,o=r.memoryLimitMb??16,s=r.member??"run",i={patches:[],logs:[]},a=await E0(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,p=new a.Callback(P=>{let z=JSON.parse(String(P));i.rejection||(i.rejection=z)}),w=new a.Callback(P=>{i.patches.push(JSON.parse(String(P)))}),m=new a.Callback(P=>{let z=JSON.parse(String(P));i.logs.push(z)}),h=new a.Callback(P=>{i.result=JSON.parse(String(P))});await u.set("__tb_reject",p),await u.set("__tb_patch",w),await u.set("__tb_log",m),await u.set("__tb_result",h),await u.set("__tb_ctx_json",JSON.stringify(R0(e)));let b=P0(t,s),E=await(await c.compileScript(b)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!E}:{effects:i}}finally{c.isDisposed||c.dispose()}}function R0(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 P0(t,e){return`
|
|
42
|
+
`}var bE,Lg=O(()=>{Nl();Ul();Ul();Nl();bE=["/**"," * 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 Ml=O(()=>{Ri();Eg();Ag();Cg();Lg()});import{homedir as wE}from"node:os";import{join as Dg}from"node:path";import{promises as ql}from"node:fs";function Lt(t){return t.trim().replace(/\/+$/,"")}function Zi(){let t=process.env.TURBOBASE_HOME??Dg(wE(),".turbobase");return{dir:t,file:Dg(t,"credentials")}}function Ug(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function ns(){let{file:t}=Zi(),e;try{let s=await ql.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))Ug(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))Ug(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:vE(n),tenants:n}}function vE(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 Zl(t){let{dir:e,file:r}=Zi();await ql.mkdir(e,{recursive:!0,mode:448}),await ql.writeFile(r,JSON.stringify(t,null,2)+`
|
|
44
|
+
`,{mode:384})}async function Mg(t){let e=Lt(t.baseUrl),r=await ns(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await Zl(r),{baseUrl:e,token:t.token,updatedAt:n}}async function Yt(t){let e=await ns();if(t){let s=Lt(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 Bi(t){let e=Lt(t),r=await ns(),n=r.tenants[e];return n?(r.active=e,await Zl(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function Bl(t){let e=await ns(),r=t?Lt(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 Zl(e),r}async function $r(){let t=await ns();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var os=O(()=>{});function qg(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 Zg(t){return t.replace(/\/+$/,"")}function Fl(t=process.env){let e=(t[io]??"").trim(),r=(t[Fi]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function Hl(t){let e;try{e=new URL(t)}catch{return`${io} 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:`${io} 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 pe,X,io,Fi,ss,Sr=O(()=>{pe=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};X=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Zg(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=qg(a);throw new pe(`${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 proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}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 platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),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/events${n}`)).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}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");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}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}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,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],roles:e.roles??[]})}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)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode: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`)}},io="TURBOBASE_REGISTRY_URL",Fi="TURBOBASE_REGISTRY_TOKEN";ss=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Zg(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=qg(a);throw new pe(`${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 xE(t){if(_E.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function $E(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:xE(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:")||TE(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:kE,loader:"js"}))}}}function TE(t){let e=t.startsWith("node:")?t.slice(5):t;return SE.has(e.split("/")[0])}function Bg(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 EE(){try{return(await import("esbuild")).build}catch(t){throw Bg("esbuild",t)}}async function RE(){try{return(await import("isolated-vm")).default}catch(t){throw Bg("isolated-vm",t)}}async function Hi(t){let e=await EE(),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:[$E()]})}catch(n){let s=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new Vl(s||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function is(t,e,r={}){let n=r.timeoutMs??200,o=r.memoryLimitMb??16,s=r.member??"run",i={patches:[],logs:[]},a=await RE(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,p=new a.Callback(P=>{let z=JSON.parse(String(P));i.rejection||(i.rejection=z)}),w=new a.Callback(P=>{i.patches.push(JSON.parse(String(P)))}),m=new a.Callback(P=>{let z=JSON.parse(String(P));i.logs.push(z)}),h=new a.Callback(P=>{i.result=JSON.parse(String(P))});await u.set("__tb_reject",p),await u.set("__tb_patch",w),await u.set("__tb_log",m),await u.set("__tb_result",h),await u.set("__tb_ctx_json",JSON.stringify(PE(e)));let b=AE(t,s),E=await(await c.compileScript(b)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!E}:{effects:i}}finally{c.isDisposed||c.dispose()}}function PE(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 AE(t,e){return`
|
|
45
45
|
"use strict";
|
|
46
46
|
(async () => {
|
|
47
47
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -110,16 +110,16 @@ ${o.join(`
|
|
|
110
110
|
${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
|
|
111
111
|
return ${e==="when"?"out":"undefined"};
|
|
112
112
|
})()
|
|
113
|
-
`}var
|
|
113
|
+
`}var _E,kE,Vl,SE,Kl=O(()=>{_E=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);kE=`
|
|
114
114
|
export const defineHook = (def) => def;
|
|
115
115
|
export const defineConduit = (def) => def;
|
|
116
116
|
export default defineHook;
|
|
117
|
-
`,
|
|
117
|
+
`,Vl=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};SE=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 Wl}from"node:fs";import{join as IE}from"node:path";function OE(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 CE(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await is(t,OE(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 Vi(t,e){let r=await Hi(t),n=[];for(let o=0;o<e.length;o+=1)n.push(await CE(r,e[o],`sample[${o}]`));return n}async function as(t){let e;try{e=await Wl.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 Wl.readFile(IE(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 cs(t){return Wl.readFile(t,"utf8")}var Gl=O(()=>{Kl()});function Fr(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function u0(t){let e=t.recordType;if(!e)throw new qt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
|
|
118
118
|
source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
|
|
119
119
|
run: (ctx) => {
|
|
120
120
|
// Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
|
|
121
121
|
// with ctx.patch({...}); observe with ctx.log('info', '...').
|
|
122
|
-
},`,a="custom";else if(n==="require-field"){let w=t.field;if(!w)throw new
|
|
122
|
+
},`,a="custom";else if(n==="require-field"){let w=t.field;if(!w)throw new qt("require-field template needs --field=<name>");i=`
|
|
123
123
|
run: (ctx) => {
|
|
124
124
|
const v = ctx.payload[${JSON.stringify(w)}];
|
|
125
125
|
if (v === undefined || v === null || v === '') {
|
|
@@ -129,7 +129,7 @@ export default defineHook;
|
|
|
129
129
|
message: ${JSON.stringify(`${w} is required`)},
|
|
130
130
|
});
|
|
131
131
|
}
|
|
132
|
-
},`,a=`require-field-${w}`}else if(n==="enforce-format"){let w=t.field;if(!w)throw new
|
|
132
|
+
},`,a=`require-field-${w}`}else if(n==="enforce-format"){let w=t.field;if(!w)throw new qt("enforce-format template needs --field=<name>");if(!t.regex)throw new qt("enforce-format template needs --regex=<pattern>");i=`
|
|
133
133
|
run: (ctx) => {
|
|
134
134
|
const v = ctx.payload[${JSON.stringify(w)}];
|
|
135
135
|
if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
|
|
@@ -139,7 +139,7 @@ export default defineHook;
|
|
|
139
139
|
message: ${JSON.stringify(`${w} does not match expected format`)},
|
|
140
140
|
});
|
|
141
141
|
}
|
|
142
|
-
},`,a=`enforce-format-${w}`}else throw new
|
|
142
|
+
},`,a=`enforce-format-${w}`}else throw new qt(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${Fr(t.regex).slice(0,24)}`:""}`,u=`/**
|
|
143
143
|
* ${t.description??`${a} on ${e}.${r}`}
|
|
144
144
|
*
|
|
145
145
|
* Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
|
|
@@ -152,7 +152,7 @@ export default defineHook<Record<string, unknown>>({
|
|
|
152
152
|
recordType: ${JSON.stringify(e)},
|
|
153
153
|
event: ${JSON.stringify(r)},${s}${i}
|
|
154
154
|
});
|
|
155
|
-
`;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function
|
|
155
|
+
`;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function d0(t){let e=t.recordType;if(!e)throw new qt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new qt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new qt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new qt(`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??`${Fr(r)}2${Fr(n)}:${Fr(e)}`,c=`/**
|
|
156
156
|
* ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
|
|
157
157
|
*
|
|
158
158
|
* Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
|
|
@@ -195,7 +195,7 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
195
195
|
},
|
|
196
196
|
idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
|
|
197
197
|
});
|
|
198
|
-
`;return{relativePath:`conduits/${
|
|
198
|
+
`;return{relativePath:`conduits/${Fr(r)}-${Fr(e)}-to-${Fr(n)}-${Fr(o)}.ts`,content:c}}function Hr(t,e){let r=p0[t];if(!r)throw new qt(`unknown extension kind '${t}'. Scaffoldable kinds: ${my.join(", ")}.`);return r(e)}var my,qt,p0,Yi=O(()=>{my=["hook","conduit"];qt=class extends Error{};p0={hook:u0,conduit:d0}});function dP(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 pP(t){return Rb[dP(t)%Rb.length]}function hP(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 Pb(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Ab(t,e){let[r,n]=pP(t),o=Pb(hP(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Pb(e)}">
|
|
199
199
|
<defs>
|
|
200
200
|
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
201
201
|
<stop offset="0" stop-color="${r}"/>
|
|
@@ -205,9 +205,9 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
205
205
|
<rect width="64" height="64" rx="14" fill="url(#tile)"/>
|
|
206
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>
|
|
207
207
|
</svg>
|
|
208
|
-
`}var
|
|
209
|
-
`}function
|
|
210
|
-
`}function
|
|
208
|
+
`}var Rb,Ib=O(()=>{Rb=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Ob,Cb=O(()=>{Ob=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var Gb={};Jo(Gb,{CN_UTIL:()=>Ub,COMPONENTS_JSON:()=>Db,MAIN_TSX:()=>qb,STYLES_CSS:()=>Zb,TSCONFIG:()=>Lb,TURBOBASE_CLIENT:()=>Nb,UI_BADGE:()=>Hb,UI_BUTTON:()=>Bb,UI_CARD:()=>Fb,UI_INPUT:()=>Kb,UI_LABEL:()=>Wb,UI_TABLE:()=>Vb,indexHtml:()=>Mb,instanceOriginFromEnv:()=>vP,packageJson:()=>zb,scaffoldAppFiles:()=>xP,starterApp:()=>kP,viteConfig:()=>jb});function mP(t){let e={name:t.title},r=(t.description??"").trim().slice(0,fP);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Ob},JSON.stringify(e,null,2)+`
|
|
209
|
+
`}function zb(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:gP},dependencies:{react:"^18.3.1","react-dom":"^18.3.1","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
|
|
210
|
+
`}function wP(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 vP(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function jb(t,e={}){let r=wP(e.instanceOrigin);return`import { defineConfig } from 'vite';
|
|
211
211
|
import { fileURLToPath, URL } from 'node:url';
|
|
212
212
|
import react from '@vitejs/plugin-react';
|
|
213
213
|
// Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
|
|
@@ -226,8 +226,8 @@ import tailwindcss from '@tailwindcss/vite';
|
|
|
226
226
|
// you sign in, and the cookies land on localhost:3000. Override the targets
|
|
227
227
|
// with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
|
|
228
228
|
// them at boot; restart the dev server after changing one).
|
|
229
|
-
const TENANT = process.env.SUPABASE_URL || '${r??
|
|
230
|
-
const API = process.env.TURBOBASE_API_URL || '${r??
|
|
229
|
+
const TENANT = process.env.SUPABASE_URL || '${r??yP}'; // /rest + the Realtime WS
|
|
230
|
+
const API = process.env.TURBOBASE_API_URL || '${r??bP}'; // /v1, /auth, /login, /_app
|
|
231
231
|
|
|
232
232
|
// Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
|
|
233
233
|
// this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
|
|
@@ -265,7 +265,7 @@ export default defineConfig({
|
|
|
265
265
|
},
|
|
266
266
|
build: { outDir: 'dist' },
|
|
267
267
|
});
|
|
268
|
-
`}function
|
|
268
|
+
`}function Mb(t){return`<!doctype html>
|
|
269
269
|
<html lang="en">
|
|
270
270
|
<head>
|
|
271
271
|
<meta charset="UTF-8" />
|
|
@@ -278,7 +278,7 @@ export default defineConfig({
|
|
|
278
278
|
<script type="module" src="/src/main.tsx"></script>
|
|
279
279
|
</body>
|
|
280
280
|
</html>
|
|
281
|
-
`}function
|
|
281
|
+
`}function xP(t){return{"package.json":zb(t.slug),"vite.config.ts":jb(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":_P,"tsconfig.json":Lb,"index.html":Mb(t.title),"public/turbobase.json":mP(t),"public/favicon.svg":Ab(t.slug,t.title),"src/main.tsx":qb,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Nb,"src/styles.css":Zb,"components.json":Db,"src/lib/utils.ts":Ub,"src/components/ui/button.tsx":Bb,"src/components/ui/card.tsx":Fb,"src/components/ui/badge.tsx":Hb,"src/components/ui/table.tsx":Vb,"src/components/ui/input.tsx":Kb,"src/components/ui/label.tsx":Wb,"README.md":`# ${t.title}
|
|
282
282
|
|
|
283
283
|
\`\`\`sh
|
|
284
284
|
npm install
|
|
@@ -299,7 +299,7 @@ every read comes back "permission denied", which looks like an RLS problem.
|
|
|
299
299
|
|
|
300
300
|
\`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
|
|
301
301
|
live access token and is gitignored \u2014 keep it that way.
|
|
302
|
-
`}}function
|
|
302
|
+
`}}function kP(t){return`import React from 'react';
|
|
303
303
|
import { Loader2, Trash2 } from 'lucide-react';
|
|
304
304
|
|
|
305
305
|
import { select, write, del } from '@/lib/turbobase';
|
|
@@ -524,7 +524,7 @@ export default function App() {
|
|
|
524
524
|
</main>
|
|
525
525
|
);
|
|
526
526
|
}
|
|
527
|
-
`}var
|
|
527
|
+
`}var fP,Nb,ys,gP,yP,bP,_P,Lb,Db,Ub,qb,Zb,Bb,Fb,Hb,Vb,Kb,Wb,Jb=O(()=>{Ib();Cb();fP=200;Nb=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
|
|
528
528
|
// Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
|
|
529
529
|
// A cold first paint that fans out many reads should use batch() \u2014 ONE request
|
|
530
530
|
// that multiplexes them, sidestepping the per-request rate limiter.
|
|
@@ -584,6 +584,80 @@ export class TurbobaseCursorError extends Error {
|
|
|
584
584
|
}
|
|
585
585
|
}
|
|
586
586
|
|
|
587
|
+
/** Thrown when a write or delete is refused because the signed-in user lacks
|
|
588
|
+
* the capability for it \u2014 as opposed to the record being invalid. Catch this
|
|
589
|
+
* to tell the user WHICH ROLE to ask for, instead of showing a raw error. */
|
|
590
|
+
export class TurbobasePermissionError extends Error {
|
|
591
|
+
constructor(message: string, readonly recordType?: string) {
|
|
592
|
+
super(message);
|
|
593
|
+
this.name = 'TurbobasePermissionError';
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// ---------------------------------------------------------------------------
|
|
598
|
+
// Capabilities \u2014 gate your UI so a denial is EXPLAINED, never silent.
|
|
599
|
+
//
|
|
600
|
+
// THIS IS UX, NOT SECURITY. RLS is the guarantee: the served app runs with the
|
|
601
|
+
// signed-in user's own JWT, so anything hidden here is still refused by the
|
|
602
|
+
// database if the user calls it directly. Hiding a screen is a courtesy to the
|
|
603
|
+
// user, not a boundary \u2014 never rely on it for safety.
|
|
604
|
+
//
|
|
605
|
+
// WHY YOU MUST STILL DO IT \u2014 reads and writes fail in two DIFFERENT ways:
|
|
606
|
+
//
|
|
607
|
+
// read RLS filters the rows out, so the request SUCCEEDS and returns []. An
|
|
608
|
+
// "Invoices (0)" screen is indistinguishable from "you may not see
|
|
609
|
+
// invoices", and the user reports missing data. CHECK THE CAPABILITY
|
|
610
|
+
// BEFORE RENDERING so an empty list is attributable.
|
|
611
|
+
// write the boundary answers 403, which surfaces here as
|
|
612
|
+
// TurbobasePermissionError. Catch it and name the role to ask for.
|
|
613
|
+
//
|
|
614
|
+
// The capabilities themselves come from the roles your app declares in
|
|
615
|
+
// public/turbobase.json \u2014 declare the role, gate on the same strings, and an
|
|
616
|
+
// admin assigns it in Admin -> Users.
|
|
617
|
+
// ---------------------------------------------------------------------------
|
|
618
|
+
|
|
619
|
+
/** Decoded claims from the readable tb_jwt cookie. Empty if absent/unreadable. */
|
|
620
|
+
export function sessionClaims(): { app_role?: string; capabilities?: string[] } {
|
|
621
|
+
const token = jwt();
|
|
622
|
+
if (!token) return {};
|
|
623
|
+
try {
|
|
624
|
+
const payload = token.split('.')[1];
|
|
625
|
+
if (!payload) return {};
|
|
626
|
+
const json = atob(payload.replace(/-/g, '+').replace(/_/g, '/'));
|
|
627
|
+
const claims = JSON.parse(json) as { app_role?: string; capabilities?: string[] };
|
|
628
|
+
return claims && typeof claims === 'object' ? claims : {};
|
|
629
|
+
} catch {
|
|
630
|
+
return {};
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* Does the signed-in user hold this capability? Mirrors the database's
|
|
636
|
+
* turbobase.has_capability() exactly:
|
|
637
|
+
*
|
|
638
|
+
* - an ADMIN bypasses every check (admin claims omit \`capabilities\`
|
|
639
|
+
* entirely \u2014 absent means bypass, NOT "holds nothing");
|
|
640
|
+
* - otherwise an exact match, or the \`<verb>:*\` wildcard a Data admin holds.
|
|
641
|
+
*/
|
|
642
|
+
export function hasCapability(cap: string): boolean {
|
|
643
|
+
const claims = sessionClaims();
|
|
644
|
+
if (claims.app_role === 'admin') return true;
|
|
645
|
+
const caps = claims.capabilities;
|
|
646
|
+
if (!Array.isArray(caps)) return false;
|
|
647
|
+
if (caps.includes(cap)) return true;
|
|
648
|
+
const verb = cap.split(':', 1)[0] ?? '';
|
|
649
|
+
return verb.length > 0 && caps.includes(verb + ':*');
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/** Throw unless the user holds \`cap\` \u2014 for guarding a route/screen entry. */
|
|
653
|
+
export function requireCapability(cap: string): void {
|
|
654
|
+
if (!hasCapability(cap)) {
|
|
655
|
+
throw new TurbobasePermissionError(
|
|
656
|
+
\`You don't have permission to do this (missing "\${cap}"). Ask an administrator to assign you a role that includes it.\`,
|
|
657
|
+
);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
587
661
|
/** Does this path already carry an explicit \`limit=\`? Such a caller opted into a
|
|
588
662
|
* bounded read, so the truncation warning below stays quiet for it. */
|
|
589
663
|
function hasExplicitLimit(pathAndQuery: string): boolean {
|
|
@@ -847,10 +921,30 @@ export async function write<T = unknown>(recordType: string, body: unknown): Pro
|
|
|
847
921
|
headers: { 'content-type': 'application/json' },
|
|
848
922
|
body: JSON.stringify(body),
|
|
849
923
|
});
|
|
850
|
-
if (!res.ok) throw
|
|
924
|
+
if (!res.ok) throw await writeError(res, recordType);
|
|
851
925
|
return (await res.json()) as T;
|
|
852
926
|
}
|
|
853
927
|
|
|
928
|
+
/**
|
|
929
|
+
* A failed write, as the RIGHT error type.
|
|
930
|
+
*
|
|
931
|
+
* The boundary answers 403 \`{error:'forbidden'}\` when RLS refused the write \u2014
|
|
932
|
+
* i.e. this user's role lacks the capability. That is a completely different
|
|
933
|
+
* thing from a 422 validation failure, and the app needs to tell the user
|
|
934
|
+
* different things about them, so it gets its own class rather than making
|
|
935
|
+
* every caller string-match a message.
|
|
936
|
+
*/
|
|
937
|
+
async function writeError(res: Response, recordType: string): Promise<Error> {
|
|
938
|
+
const body = await res.text();
|
|
939
|
+
if (res.status === 403 && jwt() !== '') {
|
|
940
|
+
return new TurbobasePermissionError(
|
|
941
|
+
\`You don't have permission to change \${recordType}. Ask an administrator to assign you a role that includes it.\`,
|
|
942
|
+
recordType,
|
|
943
|
+
);
|
|
944
|
+
}
|
|
945
|
+
return new Error(readErrorFromBody(res.status, body));
|
|
946
|
+
}
|
|
947
|
+
|
|
854
948
|
/** Delete a record through the canonical boundary DELETE /v1/data/<recordType>.
|
|
855
949
|
* Identify the row by \`pgRowId\` OR \`externalId\` (one is required). NEVER issue a
|
|
856
950
|
* hard SQL DELETE against a table \u2014 apps hold no DELETE grant, and it would not
|
|
@@ -880,7 +974,7 @@ export async function del(
|
|
|
880
974
|
): Promise<{ deleted: boolean; enqueued: boolean }> {
|
|
881
975
|
const q = 'pgRowId' in key ? \`pgRowId=\${encodeURIComponent(key.pgRowId)}\` : \`externalId=\${encodeURIComponent(key.externalId)}\`;
|
|
882
976
|
const res = await req(\`/v1/data/\${recordType}?\${q}\`, { method: 'DELETE' });
|
|
883
|
-
if (!res.ok) throw
|
|
977
|
+
if (!res.ok) throw await writeError(res, recordType);
|
|
884
978
|
return (await res.json()) as { deleted: boolean; enqueued: boolean };
|
|
885
979
|
}
|
|
886
980
|
|
|
@@ -1447,7 +1541,7 @@ export async function selectPage<T = unknown>(
|
|
|
1447
1541
|
}
|
|
1448
1542
|
return { rows, nextCursor };
|
|
1449
1543
|
}
|
|
1450
|
-
`,
|
|
1544
|
+
`,ys="src/types.ts",gP=`turbobase project types -o ${ys} || node -e "if(require('node:fs').existsSync('${ys}')){console.error('turbobase: could not refresh ${ys} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${ys} is missing. It is generated from the instance catalog and gitignored, so a fresh checkout has no copy. Run: turbobase auth login --base-url <your-instance> --token tb_pat_... , then turbobase project types -o ${ys}');process.exit(1)}"`;yP="http://localhost:54331",bP="http://localhost:4100";_P=`node_modules/
|
|
1451
1545
|
dist/
|
|
1452
1546
|
build/
|
|
1453
1547
|
|
|
@@ -1459,9 +1553,9 @@ build/
|
|
|
1459
1553
|
!.env.example
|
|
1460
1554
|
|
|
1461
1555
|
.DS_Store
|
|
1462
|
-
`,
|
|
1463
|
-
`,
|
|
1464
|
-
`,
|
|
1556
|
+
`,Lb=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
|
|
1557
|
+
`,Db=`${JSON.stringify({$schema:"https://ui.shadcn.com/schema.json",style:"new-york",rsc:!1,tsx:!0,tailwind:{config:"",css:"src/styles.css",baseColor:"neutral",cssVariables:!0,prefix:""},aliases:{components:"@/components",utils:"@/lib/utils",ui:"@/components/ui",lib:"@/lib",hooks:"@/hooks"},iconLibrary:"lucide"},null,2)}
|
|
1558
|
+
`,Ub=`import { clsx, type ClassValue } from 'clsx';
|
|
1465
1559
|
import { twMerge } from 'tailwind-merge';
|
|
1466
1560
|
|
|
1467
1561
|
/**
|
|
@@ -1475,7 +1569,7 @@ import { twMerge } from 'tailwind-merge';
|
|
|
1475
1569
|
export function cn(...inputs: ClassValue[]) {
|
|
1476
1570
|
return twMerge(clsx(inputs));
|
|
1477
1571
|
}
|
|
1478
|
-
`;
|
|
1572
|
+
`;qb=`import React from 'react';
|
|
1479
1573
|
import { createRoot } from 'react-dom/client';
|
|
1480
1574
|
import App from './App';
|
|
1481
1575
|
import './styles.css';
|
|
@@ -1485,7 +1579,7 @@ createRoot(document.getElementById('root')!).render(
|
|
|
1485
1579
|
<App />
|
|
1486
1580
|
</React.StrictMode>,
|
|
1487
1581
|
);
|
|
1488
|
-
`,
|
|
1582
|
+
`,Zb=`@import 'tailwindcss';
|
|
1489
1583
|
@import 'tw-animate-css';
|
|
1490
1584
|
|
|
1491
1585
|
/* Inter, self-hosted \u2014 the design system's font.
|
|
@@ -1573,7 +1667,7 @@ createRoot(document.getElementById('root')!).render(
|
|
|
1573
1667
|
transition-duration: 0.01ms !important;
|
|
1574
1668
|
}
|
|
1575
1669
|
}
|
|
1576
|
-
`,
|
|
1670
|
+
`,Bb=`import * as React from 'react';
|
|
1577
1671
|
import { cva, type VariantProps } from 'class-variance-authority';
|
|
1578
1672
|
|
|
1579
1673
|
import { cn } from '@/lib/utils';
|
|
@@ -1613,7 +1707,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
|
|
1613
1707
|
Button.displayName = 'Button';
|
|
1614
1708
|
|
|
1615
1709
|
export { Button, buttonVariants };
|
|
1616
|
-
`,
|
|
1710
|
+
`,Fb=`import * as React from 'react';
|
|
1617
1711
|
|
|
1618
1712
|
import { cn } from '@/lib/utils';
|
|
1619
1713
|
|
|
@@ -1651,7 +1745,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
|
|
|
1651
1745
|
CardContent.displayName = 'CardContent';
|
|
1652
1746
|
|
|
1653
1747
|
export { Card, CardHeader, CardTitle, CardDescription, CardContent };
|
|
1654
|
-
`,
|
|
1748
|
+
`,Hb=`import * as React from 'react';
|
|
1655
1749
|
import { cva, type VariantProps } from 'class-variance-authority';
|
|
1656
1750
|
|
|
1657
1751
|
import { cn } from '@/lib/utils';
|
|
@@ -1686,7 +1780,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
|
|
|
1686
1780
|
}
|
|
1687
1781
|
|
|
1688
1782
|
export { Badge, badgeVariants };
|
|
1689
|
-
`,
|
|
1783
|
+
`,Vb=`import * as React from 'react';
|
|
1690
1784
|
|
|
1691
1785
|
import { cn } from '@/lib/utils';
|
|
1692
1786
|
|
|
@@ -1745,7 +1839,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
|
|
|
1745
1839
|
TableCell.displayName = 'TableCell';
|
|
1746
1840
|
|
|
1747
1841
|
export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
|
|
1748
|
-
`,
|
|
1842
|
+
`,Kb=`import * as React from 'react';
|
|
1749
1843
|
|
|
1750
1844
|
import { cn } from '@/lib/utils';
|
|
1751
1845
|
|
|
@@ -1765,7 +1859,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
|
|
|
1765
1859
|
Input.displayName = 'Input';
|
|
1766
1860
|
|
|
1767
1861
|
export { Input };
|
|
1768
|
-
`,
|
|
1862
|
+
`,Wb=`import * as React from 'react';
|
|
1769
1863
|
|
|
1770
1864
|
import { cn } from '@/lib/utils';
|
|
1771
1865
|
|
|
@@ -1782,9 +1876,9 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
|
|
|
1782
1876
|
Label.displayName = 'Label';
|
|
1783
1877
|
|
|
1784
1878
|
export { Label };
|
|
1785
|
-
`});var ws=N(()=>{zi()});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 It(t){return t&&Object.assign(ua,t),ua}var kP,Ar,ua,bo=N(()=>{kP=Object.freeze({status:"aborted"});Ar=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ua={}});var be={};Yo(be,{BIGINT_FORMAT_RANGES:()=>Yb,Class:()=>ku,NUMBER_FORMAT_RANGES:()=>Au,aborted:()=>On,allowsEval:()=>Eu,assert:()=>RP,assertEqual:()=>$P,assertIs:()=>TP,assertNever:()=>EP,assertNotEqual:()=>SP,assignProp:()=>Tu,cached:()=>xs,captureStackTrace:()=>pa,cleanEnum:()=>qP,cleanRegex:()=>$s,clone:()=>Ot,createTransparentProxy:()=>NP,defineLazy:()=>Ce,esc:()=>In,escapeRegex:()=>Kr,extend:()=>LP,finalizeIssue:()=>er,floatSafeRemainder:()=>Su,getElementAtPath:()=>PP,getEnumValues:()=>_s,getLengthableOrigin:()=>Ss,getParsedType:()=>CP,getSizableOrigin:()=>Qb,isObject:()=>wo,isPlainObject:()=>vo,issue:()=>Iu,joinValues:()=>da,jsonStringifyReplacer:()=>$u,merge:()=>DP,normalizeParams:()=>re,nullish:()=>ks,numKeys:()=>OP,omit:()=>jP,optionalKeys:()=>Pu,partial:()=>UP,pick:()=>zP,prefixIssues:()=>pr,primitiveTypes:()=>Jb,promiseAllObject:()=>AP,propertyKeyTypes:()=>Ru,randomString:()=>IP,required:()=>MP,stringifyPrimitive:()=>ha,unwrapMessage:()=>vs});function $P(t){return t}function SP(t){return t}function TP(t){}function EP(t){throw new Error}function RP(t){}function _s(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 da(t,e="|"){return t.map(r=>ha(r)).join(e)}function $u(t,e){return typeof e=="bigint"?e.toString():e}function xs(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ks(t){return t==null}function $s(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Su(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 Ce(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 Tu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function PP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function AP(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 IP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function In(t){return JSON.stringify(t)}function wo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vo(t){if(wo(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(wo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function OP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Kr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ot(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function re(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 NP(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 ha(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Pu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function zP(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 Ot(t,{...t._zod.def,shape:r,checks:[]})}function jP(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 Ot(t,{...t._zod.def,shape:r,checks:[]})}function LP(t,e){if(!vo(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 Tu(this,"shape",n),n},checks:[]};return Ot(t,r)}function DP(t,e){return Ot(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Tu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function UP(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 Ot(e,{...e._zod.def,shape:o,checks:[]})}function MP(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 Ot(e,{...e._zod.def,shape:o,checks:[]})}function On(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function pr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function vs(t){return typeof t=="string"?t:t?.message}function er(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=vs(t.inst?._zod.def?.error?.(t))??vs(e?.error?.(t))??vs(r.customError?.(t))??vs(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Qb(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ss(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Iu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function qP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var pa,Eu,CP,Ru,Jb,Au,Yb,ku,hr=N(()=>{pa=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Eu=xs(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});CP=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}`)}},Ru=new Set(["string","number","symbol"]),Jb=new Set(["string","number","bigint","boolean","symbol","undefined"]);Au={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]},Yb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};ku=class{constructor(...e){}}});function Ou(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 Cu(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 Xb,fa,Ts,Nu=N(()=>{bo();hr();Xb=(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,$u,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},fa=I("$ZodError",Xb),Ts=I("$ZodError",Xb,{Parent:Error})});var zu,ju,Lu,Du,Uu,Cn,Mu,Nn,qu=N(()=>{bo();Nu();hr();zu=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 Ar;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>er(c,s,It())));throw pa(a,o?.callee),a}return i.value},ju=zu(Ts),Lu=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=>er(c,s,It())));throw pa(a,o?.callee),a}return i.value},Du=Lu(Ts),Uu=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 Ar;return s.issues.length?{success:!1,error:new(t??fa)(s.issues.map(i=>er(i,o,It())))}:{success:!0,data:s.value}},Cn=Uu(Ts),Mu=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=>er(i,o,It())))}:{success:!0,data:s.value}},Nn=Mu(Ts)});function lw(){return new RegExp(BP,"u")}function ww(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 vw(t){return new RegExp(`^${ww(t)}$`)}function _w(t){let e=ww({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(`^${yw}T(?:${n})$`)}var ew,tw,rw,nw,ow,sw,iw,aw,Zu,cw,BP,uw,dw,pw,hw,fw,Bu,mw,gw,yw,bw,xw,kw,$w,Sw,Tw,Ew,Rw,ga=N(()=>{ew=/^[cC][^\s-]{8,}$/,tw=/^[0-9a-z]+$/,rw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,nw=/^[0-9a-vA-V]{20}$/,ow=/^[A-Za-z0-9]{27}$/,sw=/^[a-zA-Z0-9_-]{21}$/,iw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,aw=/^([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})$/,Zu=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)$/,cw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,BP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";uw=/^(?:(?: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])$/,dw=/^(([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})$/,pw=/^((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])$/,hw=/^(([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])$/,fw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Bu=/^[A-Za-z0-9_-]*$/,mw=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,gw=/^\+(?:[0-9]){6,14}[0-9]$/,yw="(?:(?:\\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])))",bw=new RegExp(`^${yw}$`);xw=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},kw=/^\d+$/,$w=/^-?\d+(?:\.\d+)?/i,Sw=/true|false/i,Tw=/null/i,Ew=/^[^A-Z]*$/,Rw=/^[^a-z]*$/});var ot,Pw,Fu,Hu,Aw,Iw,Ow,Cw,Nw,Es,zw,jw,Lw,Dw,Uw,Mw,qw,ya=N(()=>{bo();ga();hr();ot=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Pw={number:"number",bigint:"bigint",object:"date"},Fu=I("$ZodCheckLessThan",(t,e)=>{ot.init(t,e);let r=Pw[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})}}),Hu=I("$ZodCheckGreaterThan",(t,e)=>{ot.init(t,e);let r=Pw[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})}}),Aw=I("$ZodCheckMultipleOf",(t,e)=>{ot.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):Su(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})}}),Iw=I("$ZodCheckNumberFormat",(t,e)=>{ot.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Au[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=kw)}),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})}}),Ow=I("$ZodCheckMaxLength",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ks(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=Ss(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Cw=I("$ZodCheckMinLength",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ks(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=Ss(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Nw=I("$ZodCheckLengthEquals",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ks(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=Ss(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})}}),Es=I("$ZodCheckStringFormat",(t,e)=>{var r,n;ot.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=()=>{})}),zw=I("$ZodCheckRegex",(t,e)=>{Es.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})}}),jw=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ew),Es.init(t,e)}),Lw=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Rw),Es.init(t,e)}),Dw=I("$ZodCheckIncludes",(t,e)=>{ot.init(t,e);let r=Kr(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})}}),Uw=I("$ZodCheckStartsWith",(t,e)=>{ot.init(t,e);let r=new RegExp(`^${Kr(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})}}),Mw=I("$ZodCheckEndsWith",(t,e)=>{ot.init(t,e);let r=new RegExp(`.*${Kr(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})}}),qw=I("$ZodCheckOverwrite",(t,e)=>{ot.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ba,Vu=N(()=>{ba=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(`
|
|
1879
|
+
`});var bs=O(()=>{ji()});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 Ot(t){return t&&Object.assign(da,t),da}var SP,Pr,da,yo=O(()=>{SP=Object.freeze({status:"aborted"});Pr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},da={}});var be={};Jo(be,{BIGINT_FORMAT_RANGES:()=>Xb,Class:()=>$u,NUMBER_FORMAT_RANGES:()=>Iu,aborted:()=>In,allowsEval:()=>Ru,assert:()=>AP,assertEqual:()=>TP,assertIs:()=>RP,assertNever:()=>PP,assertNotEqual:()=>EP,assignProp:()=>Eu,cached:()=>_s,captureStackTrace:()=>ha,cleanEnum:()=>BP,cleanRegex:()=>ks,clone:()=>Ct,createTransparentProxy:()=>jP,defineLazy:()=>Ce,esc:()=>An,escapeRegex:()=>Wr,extend:()=>UP,finalizeIssue:()=>Qt,floatSafeRemainder:()=>Tu,getElementAtPath:()=>IP,getEnumValues:()=>vs,getLengthableOrigin:()=>$s,getParsedType:()=>zP,getSizableOrigin:()=>Qb,isObject:()=>bo,isPlainObject:()=>wo,issue:()=>Ou,joinValues:()=>pa,jsonStringifyReplacer:()=>Su,merge:()=>MP,normalizeParams:()=>oe,nullish:()=>xs,numKeys:()=>NP,omit:()=>DP,optionalKeys:()=>Au,partial:()=>qP,pick:()=>LP,prefixIssues:()=>dr,primitiveTypes:()=>Yb,promiseAllObject:()=>OP,propertyKeyTypes:()=>Pu,randomString:()=>CP,required:()=>ZP,stringifyPrimitive:()=>fa,unwrapMessage:()=>ws});function TP(t){return t}function EP(t){return t}function RP(t){}function PP(t){throw new Error}function AP(t){}function vs(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 pa(t,e="|"){return t.map(r=>fa(r)).join(e)}function Su(t,e){return typeof e=="bigint"?e.toString():e}function _s(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function xs(t){return t==null}function ks(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Tu(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 Ce(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 Eu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function IP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function OP(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 CP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function An(t){return JSON.stringify(t)}function bo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function wo(t){if(bo(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(bo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function NP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Wr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ct(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function oe(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 jP(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 fa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Au(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function LP(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 Ct(t,{...t._zod.def,shape:r,checks:[]})}function DP(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 Ct(t,{...t._zod.def,shape:r,checks:[]})}function UP(t,e){if(!wo(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 Eu(this,"shape",n),n},checks:[]};return Ct(t,r)}function MP(t,e){return Ct(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Eu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function qP(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 Ct(e,{...e._zod.def,shape:o,checks:[]})}function ZP(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 Ct(e,{...e._zod.def,shape:o,checks:[]})}function In(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function dr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ws(t){return typeof t=="string"?t:t?.message}function Qt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=ws(t.inst?._zod.def?.error?.(t))??ws(e?.error?.(t))??ws(r.customError?.(t))??ws(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Qb(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function $s(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ou(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function BP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var ha,Ru,zP,Pu,Yb,Iu,Xb,$u,pr=O(()=>{ha=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Ru=_s(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});zP=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}`)}},Pu=new Set(["string","number","symbol"]),Yb=new Set(["string","number","bigint","boolean","symbol","undefined"]);Iu={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]},Xb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};$u=class{constructor(...e){}}});function Cu(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 Nu(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 ew,ma,Ss,zu=O(()=>{yo();pr();ew=(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,Su,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ma=I("$ZodError",ew),Ss=I("$ZodError",ew,{Parent:Error})});var ju,Lu,Du,Uu,Mu,On,qu,Cn,Zu=O(()=>{yo();zu();pr();ju=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 Pr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Qt(c,s,Ot())));throw ha(a,o?.callee),a}return i.value},Lu=ju(Ss),Du=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=>Qt(c,s,Ot())));throw ha(a,o?.callee),a}return i.value},Uu=Du(Ss),Mu=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 Pr;return s.issues.length?{success:!1,error:new(t??ma)(s.issues.map(i=>Qt(i,o,Ot())))}:{success:!0,data:s.value}},On=Mu(Ss),qu=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=>Qt(i,o,Ot())))}:{success:!0,data:s.value}},Cn=qu(Ss)});function uw(){return new RegExp(HP,"u")}function vw(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 _w(t){return new RegExp(`^${vw(t)}$`)}function xw(t){let e=vw({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(`^${bw}T(?:${n})$`)}var tw,rw,nw,ow,sw,iw,aw,cw,Bu,lw,HP,dw,pw,hw,fw,mw,Fu,gw,yw,bw,ww,kw,$w,Sw,Tw,Ew,Rw,Pw,ya=O(()=>{tw=/^[cC][^\s-]{8,}$/,rw=/^[0-9a-z]+$/,nw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ow=/^[0-9a-vA-V]{20}$/,sw=/^[A-Za-z0-9]{27}$/,iw=/^[a-zA-Z0-9_-]{21}$/,aw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,cw=/^([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})$/,Bu=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)$/,lw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,HP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";dw=/^(?:(?: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])$/,pw=/^(([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})$/,hw=/^((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])$/,fw=/^(([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])$/,mw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fu=/^[A-Za-z0-9_-]*$/,gw=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,yw=/^\+(?:[0-9]){6,14}[0-9]$/,bw="(?:(?:\\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])))",ww=new RegExp(`^${bw}$`);kw=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},$w=/^\d+$/,Sw=/^-?\d+(?:\.\d+)?/i,Tw=/true|false/i,Ew=/null/i,Rw=/^[^A-Z]*$/,Pw=/^[^a-z]*$/});var ot,Aw,Hu,Vu,Iw,Ow,Cw,Nw,zw,Ts,jw,Lw,Dw,Uw,Mw,qw,Zw,ba=O(()=>{yo();ya();pr();ot=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Aw={number:"number",bigint:"bigint",object:"date"},Hu=I("$ZodCheckLessThan",(t,e)=>{ot.init(t,e);let r=Aw[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})}}),Vu=I("$ZodCheckGreaterThan",(t,e)=>{ot.init(t,e);let r=Aw[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})}}),Iw=I("$ZodCheckMultipleOf",(t,e)=>{ot.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):Tu(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})}}),Ow=I("$ZodCheckNumberFormat",(t,e)=>{ot.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Iu[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=$w)}),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})}}),Cw=I("$ZodCheckMaxLength",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!xs(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=$s(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Nw=I("$ZodCheckMinLength",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!xs(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=$s(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),zw=I("$ZodCheckLengthEquals",(t,e)=>{var r;ot.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!xs(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=$s(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})}}),Ts=I("$ZodCheckStringFormat",(t,e)=>{var r,n;ot.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=()=>{})}),jw=I("$ZodCheckRegex",(t,e)=>{Ts.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})}}),Lw=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Rw),Ts.init(t,e)}),Dw=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Pw),Ts.init(t,e)}),Uw=I("$ZodCheckIncludes",(t,e)=>{ot.init(t,e);let r=Wr(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})}}),Mw=I("$ZodCheckStartsWith",(t,e)=>{ot.init(t,e);let r=new RegExp(`^${Wr(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})}}),qw=I("$ZodCheckEndsWith",(t,e)=>{ot.init(t,e);let r=new RegExp(`.*${Wr(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})}}),Zw=I("$ZodCheckOverwrite",(t,e)=>{ot.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var wa,Ku=O(()=>{wa=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(`
|
|
1786
1880
|
`).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(`
|
|
1787
|
-
`))}}});var
|
|
1881
|
+
`))}}});var Fw,Wu=O(()=>{Fw={major:4,minor:0,patch:0}});function ov(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function VP(t){if(!Fu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return ov(r)}function KP(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 Hw(t,e,r){t.issues.length&&e.issues.push(...dr(r,t.issues)),e.value[r]=t.value}function va(t,e,r){t.issues.length&&e.issues.push(...dr(r,t.issues)),e.value[r]=t.value}function Vw(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(...dr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Kw(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=>Qt(s,n,Ot())))}),e}function Gu(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(wo(t)&&wo(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=Gu(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=Gu(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 Ww(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),In(t))return t;let n=Gu(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 Gw(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Jw(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 Yw(t,e,r){return In(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Xw(t){return t.value=Object.freeze(t.value),t}function Qw(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(Ou(o))}}var Pe,Es,Ne,Ju,Yu,Xu,Qu,ed,td,rd,nd,od,sd,id,ev,tv,rv,nv,ad,cd,ld,ud,dd,pd,hd,fd,_a,md,gd,yd,bd,wd,vd,xa,ka,_d,xd,kd,$d,Sd,Td,Ed,Rd,Pd,Ad,Id,Od,Cd,Nd,zd,sv=O(()=>{ba();yo();Ku();Zu();ya();pr();Wu();pr();Pe=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Fw;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=In(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,w=u._zod.check(s);if(w instanceof Promise&&a?.async===!1)throw new Pr;if(l||w instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await w,s.issues.length!==p&&(c||(c=In(s,p)))});else{if(s.issues.length===p)continue;c||(c=In(s,p))}}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 Pr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=On(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Cn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Es=I("$ZodString",(t,e)=>{Pe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??kw(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}}),Ne=I("$ZodStringFormat",(t,e)=>{Ts.init(t,e),Es.init(t,e)}),Ju=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=cw),Ne.init(t,e)}),Yu=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=Bu(n))}else e.pattern??(e.pattern=Bu());Ne.init(t,e)}),Xu=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=lw),Ne.init(t,e)}),Qu=I("$ZodURL",(t,e)=>{Ne.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:gw.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})}}}),ed=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=uw()),Ne.init(t,e)}),td=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=iw),Ne.init(t,e)}),rd=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=tw),Ne.init(t,e)}),nd=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=rw),Ne.init(t,e)}),od=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=nw),Ne.init(t,e)}),sd=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ow),Ne.init(t,e)}),id=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=sw),Ne.init(t,e)}),ev=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=xw(e)),Ne.init(t,e)}),tv=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=ww),Ne.init(t,e)}),rv=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=_w(e)),Ne.init(t,e)}),nv=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=aw),Ne.init(t,e)}),ad=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=dw),Ne.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),cd=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=pw),Ne.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})}}}),ld=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=hw),Ne.init(t,e)}),ud=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=fw),Ne.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})}}});dd=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=mw),Ne.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{ov(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});pd=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Fu),Ne.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{VP(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),hd=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=yw),Ne.init(t,e)});fd=I("$ZodJWT",(t,e)=>{Ne.init(t,e),t._zod.check=r=>{KP(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),_a=I("$ZodNumber",(t,e)=>{Pe.init(t,e),t._zod.pattern=t._zod.bag.pattern??Sw,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}}),md=I("$ZodNumber",(t,e)=>{Ow.init(t,e),_a.init(t,e)}),gd=I("$ZodBoolean",(t,e)=>{Pe.init(t,e),t._zod.pattern=Tw,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}}),yd=I("$ZodNull",(t,e)=>{Pe.init(t,e),t._zod.pattern=Ew,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}}),bd=I("$ZodUnknown",(t,e)=>{Pe.init(t,e),t._zod.parse=r=>r}),wd=I("$ZodNever",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});vd=I("$ZodArray",(t,e)=>{Pe.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=>Hw(l,r,i))):Hw(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});xa=I("$ZodObject",(t,e)=>{Pe.init(t,e);let r=_s(()=>{let p=Object.keys(e.shape);for(let m of p)if(!(e.shape[m]instanceof Pe))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let w=Au(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(w)}});Ce(t._zod,"propValues",()=>{let p=e.shape,w={};for(let m in p){let h=p[m]._zod;if(h.values){w[m]??(w[m]=new Set);for(let b of h.values)w[m].add(b)}}return w});let n=p=>{let w=new wa(["shape","payload","ctx"]),m=r.value,h=P=>{let z=An(P);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};w.write("const input = payload.value;");let b=Object.create(null),$=0;for(let P of m.keys)b[P]=`key_${$++}`;w.write("const newResult = {}");for(let P of m.keys)if(m.optionalKeys.has(P)){let z=b[P];w.write(`const ${z} = ${h(P)};`);let V=An(P);w.write(`
|
|
1788
1882
|
if (${z}.issues.length) {
|
|
1789
1883
|
if (input[${V}] === undefined) {
|
|
1790
1884
|
if (${V} in input) {
|
|
@@ -1806,54 +1900,54 @@ export { Label };
|
|
|
1806
1900
|
`)}else{let z=b[P];w.write(`const ${z} = ${h(P)};`),w.write(`
|
|
1807
1901
|
if (${z}.issues.length) payload.issues = payload.issues.concat(${z}.issues.map(iss => ({
|
|
1808
1902
|
...iss,
|
|
1809
|
-
path: iss.path ? [${
|
|
1810
|
-
})));`),w.write(`newResult[${In(P)}] = ${z}.value`)}w.write("payload.value = newResult;"),w.write("return payload;");let E=w.compile();return(P,z)=>E(p,P,z)},o,s=wo,i=!ua.jitless,c=i&&Eu.value,l=e.catchall,u;t._zod.parse=(p,w)=>{u??(u=r.value);let m=p.value;if(!s(m))return p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p;let h=[];if(i&&c&&w?.async===!1&&w.jitless!==!0)o||(o=n(e.shape)),p=o(p,w);else{p.value={};let z=u.shape;for(let V of u.keys){let Q=z[V],Ge=Q._zod.run({value:m[V],issues:[]},w),rt=Q._zod.optin==="optional"&&Q._zod.optout==="optional";Ge instanceof Promise?h.push(Ge.then(Gt=>rt?Hw(Gt,p,V,m):wa(Gt,p,V))):rt?Hw(Ge,p,V,m):wa(Ge,p,V)}}if(!l)return h.length?Promise.all(h).then(()=>p):p;let b=[],k=u.keySet,E=l._zod,P=E.def.type;for(let z of Object.keys(m)){if(k.has(z))continue;if(P==="never"){b.push(z);continue}let V=E.run({value:m[z],issues:[]},w);V instanceof Promise?h.push(V.then(Q=>wa(Q,p,z))):wa(V,p,z)}return b.length&&p.issues.push({code:"unrecognized_keys",keys:b,input:m,inst:t}),h.length?Promise.all(h).then(()=>p):p}});xa=I("$ZodUnion",(t,e)=>{Pe.init(t,e),Ce(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ce(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ce(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ce(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=>$s(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=>Vw(i,r,t,n)):Vw(s,r,t,n)}}),vd=I("$ZodDiscriminatedUnion",(t,e)=>{xa.init(t,e);let r=t._zod.parse;Ce(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=xs(()=>{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(!wo(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)}}),_d=I("$ZodIntersection",(t,e)=>{Pe.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])=>Kw(r,c,l)):Kw(r,s,i)}});xd=I("$ZodRecord",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!vo(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(...pr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...pr(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=>er(l,n,It())),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(...pr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...pr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),kd=I("$ZodEnum",(t,e)=>{Pe.init(t,e);let r=_s(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Ru.has(typeof n)).map(n=>typeof n=="string"?Kr(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}}),$d=I("$ZodLiteral",(t,e)=>{Pe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Kr(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}}),Sd=I("$ZodTransform",(t,e)=>{Pe.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 Ar;return r.value=o,r}}),Td=I("$ZodOptional",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ce(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ce(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${$s(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)}),Ed=I("$ZodNullable",(t,e)=>{Pe.init(t,e),Ce(t._zod,"optin",()=>e.innerType._zod.optin),Ce(t._zod,"optout",()=>e.innerType._zod.optout),Ce(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${$s(r.source)}|null)$`):void 0}),Ce(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)}),Rd=I("$ZodDefault",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Ce(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=>Gw(s,e)):Gw(o,e)}});Pd=I("$ZodPrefault",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Ce(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))}),Ad=I("$ZodNonOptional",(t,e)=>{Pe.init(t,e),Ce(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=>Ww(s,t)):Ww(o,t)}});Id=I("$ZodCatch",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Ce(t._zod,"optout",()=>e.innerType._zod.optout),Ce(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=>er(i,n,It()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>er(s,n,It()))},input:r.value}),r.issues=[]),r)}}),Od=I("$ZodPipe",(t,e)=>{Pe.init(t,e),Ce(t._zod,"values",()=>e.in._zod.values),Ce(t._zod,"optin",()=>e.in._zod.optin),Ce(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=>Jw(s,e,n)):Jw(o,e,n)}});Cd=I("$ZodReadonly",(t,e)=>{Pe.init(t,e),Ce(t._zod,"propValues",()=>e.innerType._zod.propValues),Ce(t._zod,"values",()=>e.innerType._zod.values),Ce(t._zod,"optin",()=>e.innerType._zod.optin),Ce(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(Yw):Yw(o)}});Nd=I("$ZodCustom",(t,e)=>{ot.init(t,e),Pe.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=>Qw(s,r,n,t));Qw(o,r,n,t)}})});function sv(){return{localeError:KP()}}var VP,KP,iv=N(()=>{hr();VP=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},KP=()=>{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 ${VP(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ha(n.values[0])}`:`Invalid option: expected one of ${da(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":""}: ${da(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 ka=N(()=>{});function av(){return new Ps}var Ps,Gr,jd=N(()=>{Ps=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)}};Gr=av()});function Ld(t,e){return new t({type:"string",...re(e)})}function Dd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...re(e)})}function $a(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...re(e)})}function Ud(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...re(e)})}function Md(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...re(e)})}function qd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...re(e)})}function Zd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...re(e)})}function Bd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...re(e)})}function Fd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...re(e)})}function Hd(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...re(e)})}function Vd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...re(e)})}function Kd(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...re(e)})}function Gd(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...re(e)})}function Wd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...re(e)})}function Jd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...re(e)})}function Yd(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...re(e)})}function Qd(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...re(e)})}function Xd(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...re(e)})}function ep(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...re(e)})}function tp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...re(e)})}function rp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...re(e)})}function np(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...re(e)})}function op(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...re(e)})}function cv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...re(e)})}function lv(t,e){return new t({type:"string",format:"date",check:"string_format",...re(e)})}function uv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...re(e)})}function dv(t,e){return new t({type:"string",format:"duration",check:"string_format",...re(e)})}function sp(t,e){return new t({type:"number",checks:[],...re(e)})}function ip(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...re(e)})}function ap(t,e){return new t({type:"boolean",...re(e)})}function cp(t,e){return new t({type:"null",...re(e)})}function lp(t){return new t({type:"unknown"})}function up(t,e){return new t({type:"never",...re(e)})}function Sa(t,e){return new Fu({check:"less_than",...re(e),value:t,inclusive:!1})}function As(t,e){return new Fu({check:"less_than",...re(e),value:t,inclusive:!0})}function Ta(t,e){return new Hu({check:"greater_than",...re(e),value:t,inclusive:!1})}function Is(t,e){return new Hu({check:"greater_than",...re(e),value:t,inclusive:!0})}function Ea(t,e){return new Aw({check:"multiple_of",...re(e),value:t})}function Ra(t,e){return new Ow({check:"max_length",...re(e),maximum:t})}function _o(t,e){return new Cw({check:"min_length",...re(e),minimum:t})}function Pa(t,e){return new Nw({check:"length_equals",...re(e),length:t})}function dp(t,e){return new zw({check:"string_format",format:"regex",...re(e),pattern:t})}function pp(t){return new jw({check:"string_format",format:"lowercase",...re(t)})}function hp(t){return new Lw({check:"string_format",format:"uppercase",...re(t)})}function fp(t,e){return new Dw({check:"string_format",format:"includes",...re(e),includes:t})}function mp(t,e){return new Uw({check:"string_format",format:"starts_with",...re(e),prefix:t})}function gp(t,e){return new Mw({check:"string_format",format:"ends_with",...re(e),suffix:t})}function zn(t){return new qw({check:"overwrite",tx:t})}function yp(t){return zn(e=>e.normalize(t))}function bp(){return zn(t=>t.trim())}function wp(){return zn(t=>t.toLowerCase())}function vp(){return zn(t=>t.toUpperCase())}function pv(t,e,r){return new t({type:"array",element:e,...re(r)})}function _p(t,e,r){let n=re(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function xp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...re(r)})}var hv=N(()=>{ya();hr()});var fv=N(()=>{});function kp(t,e){if(t instanceof Ps){let n=new Aa(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 Aa(e);return r.process(t),r.emit(t,e)}function Ye(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 Ye(o.element,r);case"object":{for(let s in o.shape)if(Ye(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ye(s,r))return!0;return!1}case"intersection":return Ye(o.left,r)||Ye(o.right,r);case"tuple":{for(let s of o.items)if(Ye(s,r))return!0;return!!(o.rest&&Ye(o.rest,r))}case"record":return Ye(o.keyType,r)||Ye(o.valueType,r);case"map":return Ye(o.keyType,r)||Ye(o.valueType,r);case"set":return Ye(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ye(o.innerType,r);case"lazy":return Ye(o.getter(),r);case"default":return Ye(o.innerType,r);case"prefault":return Ye(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ye(o.in,r)||Ye(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Aa,mv=N(()=>{jd();hr();Aa=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Gr,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 p={...r,schemaPath:[...r.schemaPath,e],path:r.path},w=e._zod.parent;if(w)a.ref=w,this.process(w,p),this.seen.get(w).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let h=m;h.type="string";let{minimum:b,maximum:k,format:E,patterns:P,contentEncoding:z}=e._zod.bag;if(typeof b=="number"&&(h.minLength=b),typeof k=="number"&&(h.maxLength=k),E&&(h.format=s[E]??E,h.format===""&&delete h.format),z&&(h.contentEncoding=z),P&&P.size>0){let V=[...P];V.length===1?h.pattern=V[0].source:V.length>1&&(a.schema.allOf=[...V.map(Q=>({...this.target==="draft-7"?{type:"string"}:{},pattern:Q.source}))])}break}case"number":{let h=m,{minimum:b,maximum:k,format:E,multipleOf:P,exclusiveMaximum:z,exclusiveMinimum:V}=e._zod.bag;typeof E=="string"&&E.includes("int")?h.type="integer":h.type="number",typeof V=="number"&&(h.exclusiveMinimum=V),typeof b=="number"&&(h.minimum=b,typeof V=="number"&&(V>=b?delete h.minimum:delete h.exclusiveMinimum)),typeof z=="number"&&(h.exclusiveMaximum=z),typeof k=="number"&&(h.maximum=k,typeof z=="number"&&(z<=k?delete h.maximum:delete h.exclusiveMaximum)),typeof P=="number"&&(h.multipleOf=P);break}case"boolean":{let h=m;h.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":{m.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":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let h=m,{minimum:b,maximum:k}=e._zod.bag;typeof b=="number"&&(h.minItems=b),typeof k=="number"&&(h.maxItems=k),h.type="array",h.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let h=m;h.type="object",h.properties={};let b=o.shape;for(let P in b)h.properties[P]=this.process(b[P],{...p,path:[...p.path,"properties",P]});let k=new Set(Object.keys(b)),E=new Set([...k].filter(P=>{let z=o.shape[P]._zod;return this.io==="input"?z.optin===void 0:z.optout===void 0}));E.size>0&&(h.required=Array.from(E)),o.catchall?._zod.def.type==="never"?h.additionalProperties=!1:o.catchall?o.catchall&&(h.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{let h=m;h.anyOf=o.options.map((b,k)=>this.process(b,{...p,path:[...p.path,"anyOf",k]}));break}case"intersection":{let h=m,b=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),k=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),E=z=>"allOf"in z&&Object.keys(z).length===1,P=[...E(b)?b.allOf:[b],...E(k)?k.allOf:[k]];h.allOf=P;break}case"tuple":{let h=m;h.type="array";let b=o.items.map((P,z)=>this.process(P,{...p,path:[...p.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?h.prefixItems=b:h.items=b,o.rest){let P=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?h.items=P:h.additionalItems=P}o.rest&&(h.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:k,maximum:E}=e._zod.bag;typeof k=="number"&&(h.minItems=k),typeof E=="number"&&(h.maxItems=E);break}case"record":{let h=m;h.type="object",h.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),h.additionalProperties=this.process(o.valueType,{...p,path:[...p.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 h=m,b=_s(o.entries);b.every(k=>typeof k=="number")&&(h.type="number"),b.every(k=>typeof k=="string")&&(h.type="string"),h.enum=b;break}case"literal":{let h=m,b=[];for(let k of o.values)if(k===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof k=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(k))}else b.push(k);if(b.length!==0)if(b.length===1){let k=b[0];h.type=k===null?"null":typeof k,h.const=k}else b.every(k=>typeof k=="number")&&(h.type="number"),b.every(k=>typeof k=="string")&&(h.type="string"),b.every(k=>typeof k=="boolean")&&(h.type="string"),b.every(k=>k===null)&&(h.type="null"),h.enum=b;break}case"file":{let h=m,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:k,maximum:E,mime:P}=e._zod.bag;k!==void 0&&(b.minLength=k),E!==void 0&&(b.maxLength=E),P?P.length===1?(b.contentMediaType=P[0],Object.assign(h,b)):h.anyOf=P.map(z=>({...b,contentMediaType:z})):Object.assign(h,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let h=this.process(o.innerType,p);m.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let h=m;h.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let h=m,b=e._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=b.source;break}case"pipe":{let h=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(h,p),a.ref=h;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,p),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"lazy":{let h=e._zod.innerType;this.process(h,p),a.ref=h;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"&&Ye(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 p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let b=n.external.registry.get(u[0])?.id,k=n.external.uri??(P=>P);if(b)return{ref:k(b)};let E=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=E,{defId:E,ref:`${k("__shared")}#/${p}/${E}`}}if(u[1]===o)return{ref:"#"};let m=`#/${p}/`,h=u[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:m+h}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:w,defId:m}=s(u);p.def={...p.schema},m&&(p.defId=m);let h=p.schema;for(let b in h)delete h[b];h.$ref=w};if(n.cycles==="throw")for(let u of this.seen.entries()){let p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
|
|
1903
|
+
path: iss.path ? [${An(P)}, ...iss.path] : [${An(P)}]
|
|
1904
|
+
})));`),w.write(`newResult[${An(P)}] = ${z}.value`)}w.write("payload.value = newResult;"),w.write("return payload;");let E=w.compile();return(P,z)=>E(p,P,z)},o,s=bo,i=!da.jitless,c=i&&Ru.value,l=e.catchall,u;t._zod.parse=(p,w)=>{u??(u=r.value);let m=p.value;if(!s(m))return p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p;let h=[];if(i&&c&&w?.async===!1&&w.jitless!==!0)o||(o=n(e.shape)),p=o(p,w);else{p.value={};let z=u.shape;for(let V of u.keys){let Q=z[V],Je=Q._zod.run({value:m[V],issues:[]},w),Qe=Q._zod.optin==="optional"&&Q._zod.optout==="optional";Je instanceof Promise?h.push(Je.then(Nr=>Qe?Vw(Nr,p,V,m):va(Nr,p,V))):Qe?Vw(Je,p,V,m):va(Je,p,V)}}if(!l)return h.length?Promise.all(h).then(()=>p):p;let b=[],$=u.keySet,E=l._zod,P=E.def.type;for(let z of Object.keys(m)){if($.has(z))continue;if(P==="never"){b.push(z);continue}let V=E.run({value:m[z],issues:[]},w);V instanceof Promise?h.push(V.then(Q=>va(Q,p,z))):va(V,p,z)}return b.length&&p.issues.push({code:"unrecognized_keys",keys:b,input:m,inst:t}),h.length?Promise.all(h).then(()=>p):p}});ka=I("$ZodUnion",(t,e)=>{Pe.init(t,e),Ce(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ce(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ce(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ce(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=>ks(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=>Kw(i,r,t,n)):Kw(s,r,t,n)}}),_d=I("$ZodDiscriminatedUnion",(t,e)=>{ka.init(t,e);let r=t._zod.parse;Ce(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=_s(()=>{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(!bo(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)}}),xd=I("$ZodIntersection",(t,e)=>{Pe.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])=>Ww(r,c,l)):Ww(r,s,i)}});kd=I("$ZodRecord",(t,e)=>{Pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!wo(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(...dr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...dr(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=>Qt(l,n,Ot())),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(...dr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...dr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),$d=I("$ZodEnum",(t,e)=>{Pe.init(t,e);let r=vs(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Pu.has(typeof n)).map(n=>typeof n=="string"?Wr(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}}),Sd=I("$ZodLiteral",(t,e)=>{Pe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Wr(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}}),Td=I("$ZodTransform",(t,e)=>{Pe.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 Pr;return r.value=o,r}}),Ed=I("$ZodOptional",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ce(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ce(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ks(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)}),Rd=I("$ZodNullable",(t,e)=>{Pe.init(t,e),Ce(t._zod,"optin",()=>e.innerType._zod.optin),Ce(t._zod,"optout",()=>e.innerType._zod.optout),Ce(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ks(r.source)}|null)$`):void 0}),Ce(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)}),Pd=I("$ZodDefault",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Ce(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=>Gw(s,e)):Gw(o,e)}});Ad=I("$ZodPrefault",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Ce(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))}),Id=I("$ZodNonOptional",(t,e)=>{Pe.init(t,e),Ce(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=>Jw(s,t)):Jw(o,t)}});Od=I("$ZodCatch",(t,e)=>{Pe.init(t,e),t._zod.optin="optional",Ce(t._zod,"optout",()=>e.innerType._zod.optout),Ce(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=>Qt(i,n,Ot()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Qt(s,n,Ot()))},input:r.value}),r.issues=[]),r)}}),Cd=I("$ZodPipe",(t,e)=>{Pe.init(t,e),Ce(t._zod,"values",()=>e.in._zod.values),Ce(t._zod,"optin",()=>e.in._zod.optin),Ce(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=>Yw(s,e,n)):Yw(o,e,n)}});Nd=I("$ZodReadonly",(t,e)=>{Pe.init(t,e),Ce(t._zod,"propValues",()=>e.innerType._zod.propValues),Ce(t._zod,"values",()=>e.innerType._zod.values),Ce(t._zod,"optin",()=>e.innerType._zod.optin),Ce(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(Xw):Xw(o)}});zd=I("$ZodCustom",(t,e)=>{ot.init(t,e),Pe.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=>Qw(s,r,n,t));Qw(o,r,n,t)}})});function iv(){return{localeError:GP()}}var WP,GP,av=O(()=>{pr();WP=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},GP=()=>{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 ${WP(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${fa(n.values[0])}`:`Invalid option: expected one of ${pa(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":""}: ${pa(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 $a=O(()=>{});function cv(){return new Rs}var Rs,Gr,Ld=O(()=>{Rs=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)}};Gr=cv()});function Dd(t,e){return new t({type:"string",...oe(e)})}function Ud(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...oe(e)})}function Sa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...oe(e)})}function Md(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...oe(e)})}function qd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...oe(e)})}function Zd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...oe(e)})}function Bd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...oe(e)})}function Fd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...oe(e)})}function Hd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...oe(e)})}function Vd(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...oe(e)})}function Kd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...oe(e)})}function Wd(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...oe(e)})}function Gd(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...oe(e)})}function Jd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...oe(e)})}function Yd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...oe(e)})}function Xd(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...oe(e)})}function Qd(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...oe(e)})}function ep(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...oe(e)})}function tp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...oe(e)})}function rp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...oe(e)})}function np(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...oe(e)})}function op(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...oe(e)})}function sp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...oe(e)})}function lv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...oe(e)})}function uv(t,e){return new t({type:"string",format:"date",check:"string_format",...oe(e)})}function dv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...oe(e)})}function pv(t,e){return new t({type:"string",format:"duration",check:"string_format",...oe(e)})}function ip(t,e){return new t({type:"number",checks:[],...oe(e)})}function ap(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...oe(e)})}function cp(t,e){return new t({type:"boolean",...oe(e)})}function lp(t,e){return new t({type:"null",...oe(e)})}function up(t){return new t({type:"unknown"})}function dp(t,e){return new t({type:"never",...oe(e)})}function Ta(t,e){return new Hu({check:"less_than",...oe(e),value:t,inclusive:!1})}function Ps(t,e){return new Hu({check:"less_than",...oe(e),value:t,inclusive:!0})}function Ea(t,e){return new Vu({check:"greater_than",...oe(e),value:t,inclusive:!1})}function As(t,e){return new Vu({check:"greater_than",...oe(e),value:t,inclusive:!0})}function Ra(t,e){return new Iw({check:"multiple_of",...oe(e),value:t})}function Pa(t,e){return new Cw({check:"max_length",...oe(e),maximum:t})}function vo(t,e){return new Nw({check:"min_length",...oe(e),minimum:t})}function Aa(t,e){return new zw({check:"length_equals",...oe(e),length:t})}function pp(t,e){return new jw({check:"string_format",format:"regex",...oe(e),pattern:t})}function hp(t){return new Lw({check:"string_format",format:"lowercase",...oe(t)})}function fp(t){return new Dw({check:"string_format",format:"uppercase",...oe(t)})}function mp(t,e){return new Uw({check:"string_format",format:"includes",...oe(e),includes:t})}function gp(t,e){return new Mw({check:"string_format",format:"starts_with",...oe(e),prefix:t})}function yp(t,e){return new qw({check:"string_format",format:"ends_with",...oe(e),suffix:t})}function Nn(t){return new Zw({check:"overwrite",tx:t})}function bp(t){return Nn(e=>e.normalize(t))}function wp(){return Nn(t=>t.trim())}function vp(){return Nn(t=>t.toLowerCase())}function _p(){return Nn(t=>t.toUpperCase())}function hv(t,e,r){return new t({type:"array",element:e,...oe(r)})}function xp(t,e,r){let n=oe(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function kp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...oe(r)})}var fv=O(()=>{ba();pr()});var mv=O(()=>{});function $p(t,e){if(t instanceof Rs){let n=new Ia(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 Ia(e);return r.process(t),r.emit(t,e)}function Ye(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 Ye(o.element,r);case"object":{for(let s in o.shape)if(Ye(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ye(s,r))return!0;return!1}case"intersection":return Ye(o.left,r)||Ye(o.right,r);case"tuple":{for(let s of o.items)if(Ye(s,r))return!0;return!!(o.rest&&Ye(o.rest,r))}case"record":return Ye(o.keyType,r)||Ye(o.valueType,r);case"map":return Ye(o.keyType,r)||Ye(o.valueType,r);case"set":return Ye(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ye(o.innerType,r);case"lazy":return Ye(o.getter(),r);case"default":return Ye(o.innerType,r);case"prefault":return Ye(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ye(o.in,r)||Ye(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Ia,gv=O(()=>{Ld();pr();Ia=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Gr,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 p={...r,schemaPath:[...r.schemaPath,e],path:r.path},w=e._zod.parent;if(w)a.ref=w,this.process(w,p),this.seen.get(w).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let h=m;h.type="string";let{minimum:b,maximum:$,format:E,patterns:P,contentEncoding:z}=e._zod.bag;if(typeof b=="number"&&(h.minLength=b),typeof $=="number"&&(h.maxLength=$),E&&(h.format=s[E]??E,h.format===""&&delete h.format),z&&(h.contentEncoding=z),P&&P.size>0){let V=[...P];V.length===1?h.pattern=V[0].source:V.length>1&&(a.schema.allOf=[...V.map(Q=>({...this.target==="draft-7"?{type:"string"}:{},pattern:Q.source}))])}break}case"number":{let h=m,{minimum:b,maximum:$,format:E,multipleOf:P,exclusiveMaximum:z,exclusiveMinimum:V}=e._zod.bag;typeof E=="string"&&E.includes("int")?h.type="integer":h.type="number",typeof V=="number"&&(h.exclusiveMinimum=V),typeof b=="number"&&(h.minimum=b,typeof V=="number"&&(V>=b?delete h.minimum:delete h.exclusiveMinimum)),typeof z=="number"&&(h.exclusiveMaximum=z),typeof $=="number"&&(h.maximum=$,typeof z=="number"&&(z<=$?delete h.maximum:delete h.exclusiveMaximum)),typeof P=="number"&&(h.multipleOf=P);break}case"boolean":{let h=m;h.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":{m.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":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let h=m,{minimum:b,maximum:$}=e._zod.bag;typeof b=="number"&&(h.minItems=b),typeof $=="number"&&(h.maxItems=$),h.type="array",h.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let h=m;h.type="object",h.properties={};let b=o.shape;for(let P in b)h.properties[P]=this.process(b[P],{...p,path:[...p.path,"properties",P]});let $=new Set(Object.keys(b)),E=new Set([...$].filter(P=>{let z=o.shape[P]._zod;return this.io==="input"?z.optin===void 0:z.optout===void 0}));E.size>0&&(h.required=Array.from(E)),o.catchall?._zod.def.type==="never"?h.additionalProperties=!1:o.catchall?o.catchall&&(h.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{let h=m;h.anyOf=o.options.map((b,$)=>this.process(b,{...p,path:[...p.path,"anyOf",$]}));break}case"intersection":{let h=m,b=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),$=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),E=z=>"allOf"in z&&Object.keys(z).length===1,P=[...E(b)?b.allOf:[b],...E($)?$.allOf:[$]];h.allOf=P;break}case"tuple":{let h=m;h.type="array";let b=o.items.map((P,z)=>this.process(P,{...p,path:[...p.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?h.prefixItems=b:h.items=b,o.rest){let P=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?h.items=P:h.additionalItems=P}o.rest&&(h.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:$,maximum:E}=e._zod.bag;typeof $=="number"&&(h.minItems=$),typeof E=="number"&&(h.maxItems=E);break}case"record":{let h=m;h.type="object",h.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),h.additionalProperties=this.process(o.valueType,{...p,path:[...p.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 h=m,b=vs(o.entries);b.every($=>typeof $=="number")&&(h.type="number"),b.every($=>typeof $=="string")&&(h.type="string"),h.enum=b;break}case"literal":{let h=m,b=[];for(let $ of o.values)if($===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof $=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number($))}else b.push($);if(b.length!==0)if(b.length===1){let $=b[0];h.type=$===null?"null":typeof $,h.const=$}else b.every($=>typeof $=="number")&&(h.type="number"),b.every($=>typeof $=="string")&&(h.type="string"),b.every($=>typeof $=="boolean")&&(h.type="string"),b.every($=>$===null)&&(h.type="null"),h.enum=b;break}case"file":{let h=m,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:$,maximum:E,mime:P}=e._zod.bag;$!==void 0&&(b.minLength=$),E!==void 0&&(b.maxLength=E),P?P.length===1?(b.contentMediaType=P[0],Object.assign(h,b)):h.anyOf=P.map(z=>({...b,contentMediaType:z})):Object.assign(h,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let h=this.process(o.innerType,p);m.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let h=m;h.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let h=m,b=e._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=b.source;break}case"pipe":{let h=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(h,p),a.ref=h;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,p),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"lazy":{let h=e._zod.innerType;this.process(h,p),a.ref=h;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"&&Ye(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 p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let b=n.external.registry.get(u[0])?.id,$=n.external.uri??(P=>P);if(b)return{ref:$(b)};let E=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=E,{defId:E,ref:`${$("__shared")}#/${p}/${E}`}}if(u[1]===o)return{ref:"#"};let m=`#/${p}/`,h=u[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:m+h}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:w,defId:m}=s(u);p.def={...p.schema},m&&(p.defId=m);let h=p.schema;for(let b in h)delete h[b];h.$ref=w};if(n.cycles==="throw")for(let u of this.seen.entries()){let p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
|
|
1811
1905
|
|
|
1812
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(e===u[0]){i(u);continue}if(n.external){let m=n.external.registry.get(u[0])?.id;if(e!==u[0]&&m){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(p.cycle){i(u);continue}if(p.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,p)=>{let w=this.seen.get(u),m=w.def??w.schema,h={...m};if(w.ref===null)return;let b=w.ref;if(w.ref=null,b){a(b,p);let
|
|
1813
|
-
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function $v(t){return t.description}function Sv(t){if(fr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function ko(t){if(fr(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 Os=N(()=>{ws();Tp()});var Ep=N(()=>{mt()});var Cs={};Yo(Cs,{ZodISODate:()=>Ev,ZodISODateTime:()=>Tv,ZodISODuration:()=>Pv,ZodISOTime:()=>Rv,date:()=>Pp,datetime:()=>Rp,duration:()=>Ip,time:()=>Ap});function Rp(t){return cv(Tv,t)}function Pp(t){return lv(Ev,t)}function Ap(t){return uv(Rv,t)}function Ip(t){return dv(Pv,t)}var Tv,Ev,Rv,Pv,Op=N(()=>{mt();Cp();Tv=I("ZodISODateTime",(t,e)=>{Xw.init(t,e),Me.init(t,e)});Ev=I("ZodISODate",(t,e)=>{ev.init(t,e),Me.init(t,e)});Rv=I("ZodISOTime",(t,e)=>{tv.init(t,e),Me.init(t,e)});Pv=I("ZodISODuration",(t,e)=>{rv.init(t,e),Me.init(t,e)})});var Av,UB,Ns,Np=N(()=>{mt();mt();Av=(t,e)=>{fa.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Cu(t,r)},flatten:{value:r=>Ou(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},UB=I("ZodError",Av),Ns=I("ZodError",Av,{Parent:Error})});var Iv,Ov,Cv,Nv,zp=N(()=>{mt();Np();Iv=zu(Ns),Ov=Lu(Ns),Cv=Uu(Ns),Nv=Mu(Ns)});function A(t){return Ld(MA,t)}function Ee(t){return sp(Uv,t)}function jv(t){return ip(oI,t)}function tt(t){return ap(sI,t)}function Mv(t){return cp(iI,t)}function qe(){return lp(aI)}function lI(t){return up(cI,t)}function we(t,e){return pv(uI,t,e)}function H(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new qv(r)}function gt(t,e){return new qv({type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},catchall:qe(),...be.normalizeParams(e)})}function je(t,e){return new Zv({type:"union",options:t,...be.normalizeParams(e)})}function Dp(t,e,r){return new dI({type:"union",options:e,discriminator:t,...be.normalizeParams(r)})}function Na(t,e){return new pI({type:"intersection",left:t,right:e})}function ze(t,e,r){return new hI({type:"record",keyType:t,valueType:e,...be.normalizeParams(r)})}function St(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new jp({type:"enum",entries:r,...be.normalizeParams(e)})}function W(t,e){return new fI({type:"literal",values:Array.isArray(t)?t:[t],...be.normalizeParams(e)})}function Bv(t){return new mI({type:"transform",transform:t})}function Ze(t){return new Fv({type:"optional",innerType:t})}function Lv(t){return new gI({type:"nullable",innerType:t})}function bI(t,e){return new yI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function vI(t,e){return new wI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function _I(t,e){return new Hv({type:"nonoptional",innerType:t,...be.normalizeParams(e)})}function kI(t,e){return new xI({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Lp(t,e){return new $I({type:"pipe",in:t,out:e})}function TI(t){return new SI({type:"readonly",innerType:t})}function EI(t){let e=new ot({check:"custom"});return e._zod.check=t,e}function Kv(t,e){return _p(Vv,t??(()=>!0),e)}function RI(t,e={}){return xp(Vv,t,e)}function PI(t){let e=EI(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(be.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(be.issue(o))}},t(r.value,r)));return e}function Up(t,e){return Lp(Bv(t),e)}var Fe,Dv,MA,Me,qA,zv,Ca,ZA,BA,FA,HA,VA,KA,GA,WA,JA,YA,QA,XA,eI,tI,rI,nI,Uv,oI,sI,iI,aI,cI,uI,qv,Zv,dI,pI,hI,jp,fI,mI,Fv,gI,yI,wI,Hv,xI,$I,SI,Vv,Cp=N(()=>{mt();mt();Ep();Op();zp();Fe=I("ZodType",(t,e)=>(Pe.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)=>Ot(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Iv(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Cv(t,r,n),t.parseAsync=async(r,n)=>Ov(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Nv(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(RI(r,n)),t.superRefine=r=>t.check(PI(r)),t.overwrite=r=>t.check(zn(r)),t.optional=()=>Ze(t),t.nullable=()=>Lv(t),t.nullish=()=>Ze(Lv(t)),t.nonoptional=r=>_I(t,r),t.array=()=>we(t),t.or=r=>je([t,r]),t.and=r=>Na(t,r),t.transform=r=>Lp(t,Bv(r)),t.default=r=>bI(t,r),t.prefault=r=>vI(t,r),t.catch=r=>kI(t,r),t.pipe=r=>Lp(t,r),t.readonly=()=>TI(t),t.describe=r=>{let n=t.clone();return Gr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Gr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Gr.get(t);let n=t.clone();return Gr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Dv=I("_ZodString",(t,e)=>{Rs.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(dp(...n)),t.includes=(...n)=>t.check(fp(...n)),t.startsWith=(...n)=>t.check(mp(...n)),t.endsWith=(...n)=>t.check(gp(...n)),t.min=(...n)=>t.check(_o(...n)),t.max=(...n)=>t.check(Ra(...n)),t.length=(...n)=>t.check(Pa(...n)),t.nonempty=(...n)=>t.check(_o(1,...n)),t.lowercase=n=>t.check(pp(n)),t.uppercase=n=>t.check(hp(n)),t.trim=()=>t.check(bp()),t.normalize=(...n)=>t.check(yp(...n)),t.toLowerCase=()=>t.check(wp()),t.toUpperCase=()=>t.check(vp())}),MA=I("ZodString",(t,e)=>{Rs.init(t,e),Dv.init(t,e),t.email=r=>t.check(Dd(qA,r)),t.url=r=>t.check(Bd(ZA,r)),t.jwt=r=>t.check(op(nI,r)),t.emoji=r=>t.check(Fd(BA,r)),t.guid=r=>t.check($a(zv,r)),t.uuid=r=>t.check(Ud(Ca,r)),t.uuidv4=r=>t.check(Md(Ca,r)),t.uuidv6=r=>t.check(qd(Ca,r)),t.uuidv7=r=>t.check(Zd(Ca,r)),t.nanoid=r=>t.check(Hd(FA,r)),t.guid=r=>t.check($a(zv,r)),t.cuid=r=>t.check(Vd(HA,r)),t.cuid2=r=>t.check(Kd(VA,r)),t.ulid=r=>t.check(Gd(KA,r)),t.base64=r=>t.check(tp(eI,r)),t.base64url=r=>t.check(rp(tI,r)),t.xid=r=>t.check(Wd(GA,r)),t.ksuid=r=>t.check(Jd(WA,r)),t.ipv4=r=>t.check(Yd(JA,r)),t.ipv6=r=>t.check(Qd(YA,r)),t.cidrv4=r=>t.check(Xd(QA,r)),t.cidrv6=r=>t.check(ep(XA,r)),t.e164=r=>t.check(np(rI,r)),t.datetime=r=>t.check(Rp(r)),t.date=r=>t.check(Pp(r)),t.time=r=>t.check(Ap(r)),t.duration=r=>t.check(Ip(r))});Me=I("ZodStringFormat",(t,e)=>{Ne.init(t,e),Dv.init(t,e)}),qA=I("ZodEmail",(t,e)=>{Yu.init(t,e),Me.init(t,e)}),zv=I("ZodGUID",(t,e)=>{Wu.init(t,e),Me.init(t,e)}),Ca=I("ZodUUID",(t,e)=>{Ju.init(t,e),Me.init(t,e)}),ZA=I("ZodURL",(t,e)=>{Qu.init(t,e),Me.init(t,e)}),BA=I("ZodEmoji",(t,e)=>{Xu.init(t,e),Me.init(t,e)}),FA=I("ZodNanoID",(t,e)=>{ed.init(t,e),Me.init(t,e)}),HA=I("ZodCUID",(t,e)=>{td.init(t,e),Me.init(t,e)}),VA=I("ZodCUID2",(t,e)=>{rd.init(t,e),Me.init(t,e)}),KA=I("ZodULID",(t,e)=>{nd.init(t,e),Me.init(t,e)}),GA=I("ZodXID",(t,e)=>{od.init(t,e),Me.init(t,e)}),WA=I("ZodKSUID",(t,e)=>{sd.init(t,e),Me.init(t,e)}),JA=I("ZodIPv4",(t,e)=>{id.init(t,e),Me.init(t,e)}),YA=I("ZodIPv6",(t,e)=>{ad.init(t,e),Me.init(t,e)}),QA=I("ZodCIDRv4",(t,e)=>{cd.init(t,e),Me.init(t,e)}),XA=I("ZodCIDRv6",(t,e)=>{ld.init(t,e),Me.init(t,e)}),eI=I("ZodBase64",(t,e)=>{ud.init(t,e),Me.init(t,e)}),tI=I("ZodBase64URL",(t,e)=>{dd.init(t,e),Me.init(t,e)}),rI=I("ZodE164",(t,e)=>{pd.init(t,e),Me.init(t,e)}),nI=I("ZodJWT",(t,e)=>{hd.init(t,e),Me.init(t,e)}),Uv=I("ZodNumber",(t,e)=>{va.init(t,e),Fe.init(t,e),t.gt=(n,o)=>t.check(Ta(n,o)),t.gte=(n,o)=>t.check(Is(n,o)),t.min=(n,o)=>t.check(Is(n,o)),t.lt=(n,o)=>t.check(Sa(n,o)),t.lte=(n,o)=>t.check(As(n,o)),t.max=(n,o)=>t.check(As(n,o)),t.int=n=>t.check(jv(n)),t.safe=n=>t.check(jv(n)),t.positive=n=>t.check(Ta(0,n)),t.nonnegative=n=>t.check(Is(0,n)),t.negative=n=>t.check(Sa(0,n)),t.nonpositive=n=>t.check(As(0,n)),t.multipleOf=(n,o)=>t.check(Ea(n,o)),t.step=(n,o)=>t.check(Ea(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});oI=I("ZodNumberFormat",(t,e)=>{fd.init(t,e),Uv.init(t,e)});sI=I("ZodBoolean",(t,e)=>{md.init(t,e),Fe.init(t,e)});iI=I("ZodNull",(t,e)=>{gd.init(t,e),Fe.init(t,e)});aI=I("ZodUnknown",(t,e)=>{yd.init(t,e),Fe.init(t,e)});cI=I("ZodNever",(t,e)=>{bd.init(t,e),Fe.init(t,e)});uI=I("ZodArray",(t,e)=>{wd.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(_o(r,n)),t.nonempty=r=>t.check(_o(1,r)),t.max=(r,n)=>t.check(Ra(r,n)),t.length=(r,n)=>t.check(Pa(r,n)),t.unwrap=()=>t.element});qv=I("ZodObject",(t,e)=>{_a.init(t,e),Fe.init(t,e),be.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>St(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:qe()}),t.loose=()=>t.clone({...t._zod.def,catchall:qe()}),t.strict=()=>t.clone({...t._zod.def,catchall:lI()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>be.extend(t,r),t.merge=r=>be.merge(t,r),t.pick=r=>be.pick(t,r),t.omit=r=>be.omit(t,r),t.partial=(...r)=>be.partial(Fv,t,r[0]),t.required=(...r)=>be.required(Hv,t,r[0])});Zv=I("ZodUnion",(t,e)=>{xa.init(t,e),Fe.init(t,e),t.options=e.options});dI=I("ZodDiscriminatedUnion",(t,e)=>{Zv.init(t,e),vd.init(t,e)});pI=I("ZodIntersection",(t,e)=>{_d.init(t,e),Fe.init(t,e)});hI=I("ZodRecord",(t,e)=>{xd.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});jp=I("ZodEnum",(t,e)=>{kd.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 jp({...e,checks:[],...be.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 jp({...e,checks:[],...be.normalizeParams(o),entries:s})}});fI=I("ZodLiteral",(t,e)=>{$d.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]}})});mI=I("ZodTransform",(t,e)=>{Sd.init(t,e),Fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(be.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(be.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Fv=I("ZodOptional",(t,e)=>{Td.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});gI=I("ZodNullable",(t,e)=>{Ed.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});yI=I("ZodDefault",(t,e)=>{Rd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});wI=I("ZodPrefault",(t,e)=>{Pd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});Hv=I("ZodNonOptional",(t,e)=>{Ad.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});xI=I("ZodCatch",(t,e)=>{Id.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});$I=I("ZodPipe",(t,e)=>{Od.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});SI=I("ZodReadonly",(t,e)=>{Cd.init(t,e),Fe.init(t,e)});Vv=I("ZodCustom",(t,e)=>{Nd.init(t,e),Fe.init(t,e)})});var Gv=N(()=>{});var Wv=N(()=>{});var Jv=N(()=>{mt();Cp();Ep();Np();zp();Gv();mt();iv();ka();Op();Wv();It(sv())});var Yv=N(()=>{Jv()});var Qv=N(()=>{Yv()});function m_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function g_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var qp,Xv,Yr,ja,Qe,e_,t_,tF,OI,CI,Zp,Ct,zs,r_,st,qt,Zt,it,La,n_,Bp,o_,s_,Fp,js,X,Hp,i_,a_,rF,Da,NI,Ua,zI,Ls,$o,c_,jI,LI,DI,UI,MI,qI,Vp,ZI,BI,Kp,Ma,FI,HI,qa,VI,Ds,Us,KI,Ms,So,GI,qs,Za,Ba,Fa,nF,Ha,Va,Ka,l_,u_,d_,Gp,p_,Zs,To,h_,WI,Ga,JI,Wa,YI,Wp,QI,Ja,XI,eO,tO,rO,nO,oO,sO,iO,aO,cO,Ya,lO,uO,Qa,Jp,Yp,Qp,dO,pO,hO,Xp,fO,mO,gO,yO,bO,f_,Xa,wO,ec,oF,vO,Eo,_O,sF,Bs,xO,eh,kO,$O,SO,TO,EO,RO,PO,za,AO,IO,OO,Fs,th,CO,NO,zO,jO,LO,DO,UO,MO,qO,ZO,BO,FO,HO,VO,KO,GO,WO,JO,Ro,YO,QO,XO,tc,eC,tC,rC,rh,nC,iF,aF,cF,lF,uF,dF,G,Mp,Po=N(()=>{Qv();qp="2025-11-25",Xv=[qp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Yr="io.modelcontextprotocol/related-task",ja="2.0",Qe=Kv(t=>t!==null&&(typeof t=="object"||typeof t=="function")),e_=je([A(),Ee().int()]),t_=A(),tF=gt({ttl:Ee().optional(),pollInterval:Ee().optional()}),OI=H({ttl:Ee().optional()}),CI=H({taskId:A()}),Zp=gt({progressToken:e_.optional(),[Yr]:CI.optional()}),Ct=H({_meta:Zp.optional()}),zs=Ct.extend({task:OI.optional()}),r_=t=>zs.safeParse(t).success,st=H({method:A(),params:Ct.loose().optional()}),qt=H({_meta:Zp.optional()}),Zt=H({method:A(),params:qt.loose().optional()}),it=gt({_meta:Zp.optional()}),La=je([A(),Ee().int()]),n_=H({jsonrpc:W(ja),id:La,...st.shape}).strict(),Bp=t=>n_.safeParse(t).success,o_=H({jsonrpc:W(ja),...Zt.shape}).strict(),s_=t=>o_.safeParse(t).success,Fp=H({jsonrpc:W(ja),id:La,result:it}).strict(),js=t=>Fp.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"})(X||(X={}));Hp=H({jsonrpc:W(ja),id:La.optional(),error:H({code:Ee().int(),message:A(),data:qe().optional()})}).strict(),i_=t=>Hp.safeParse(t).success,a_=je([n_,o_,Fp,Hp]),rF=je([Fp,Hp]),Da=it.strict(),NI=qt.extend({requestId:La.optional(),reason:A().optional()}),Ua=Zt.extend({method:W("notifications/cancelled"),params:NI}),zI=H({src:A(),mimeType:A().optional(),sizes:we(A()).optional(),theme:St(["light","dark"]).optional()}),Ls=H({icons:we(zI).optional()}),$o=H({name:A(),title:A().optional()}),c_=$o.extend({...$o.shape,...Ls.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),jI=Na(H({applyDefaults:tt().optional()}),ze(A(),qe())),LI=Up(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Na(H({form:jI.optional(),url:Qe.optional()}),ze(A(),qe()).optional())),DI=gt({list:Qe.optional(),cancel:Qe.optional(),requests:gt({sampling:gt({createMessage:Qe.optional()}).optional(),elicitation:gt({create:Qe.optional()}).optional()}).optional()}),UI=gt({list:Qe.optional(),cancel:Qe.optional(),requests:gt({tools:gt({call:Qe.optional()}).optional()}).optional()}),MI=H({experimental:ze(A(),Qe).optional(),sampling:H({context:Qe.optional(),tools:Qe.optional()}).optional(),elicitation:LI.optional(),roots:H({listChanged:tt().optional()}).optional(),tasks:DI.optional(),extensions:ze(A(),Qe).optional()}),qI=Ct.extend({protocolVersion:A(),capabilities:MI,clientInfo:c_}),Vp=st.extend({method:W("initialize"),params:qI}),ZI=H({experimental:ze(A(),Qe).optional(),logging:Qe.optional(),completions:Qe.optional(),prompts:H({listChanged:tt().optional()}).optional(),resources:H({subscribe:tt().optional(),listChanged:tt().optional()}).optional(),tools:H({listChanged:tt().optional()}).optional(),tasks:UI.optional(),extensions:ze(A(),Qe).optional()}),BI=it.extend({protocolVersion:A(),capabilities:ZI,serverInfo:c_,instructions:A().optional()}),Kp=Zt.extend({method:W("notifications/initialized"),params:qt.optional()}),Ma=st.extend({method:W("ping"),params:Ct.optional()}),FI=H({progress:Ee(),total:Ze(Ee()),message:Ze(A())}),HI=H({...qt.shape,...FI.shape,progressToken:e_}),qa=Zt.extend({method:W("notifications/progress"),params:HI}),VI=Ct.extend({cursor:t_.optional()}),Ds=st.extend({params:VI.optional()}),Us=it.extend({nextCursor:t_.optional()}),KI=St(["working","input_required","completed","failed","cancelled"]),Ms=H({taskId:A(),status:KI,ttl:je([Ee(),Mv()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Ze(Ee()),statusMessage:Ze(A())}),So=it.extend({task:Ms}),GI=qt.merge(Ms),qs=Zt.extend({method:W("notifications/tasks/status"),params:GI}),Za=st.extend({method:W("tasks/get"),params:Ct.extend({taskId:A()})}),Ba=it.merge(Ms),Fa=st.extend({method:W("tasks/result"),params:Ct.extend({taskId:A()})}),nF=it.loose(),Ha=Ds.extend({method:W("tasks/list")}),Va=Us.extend({tasks:we(Ms)}),Ka=st.extend({method:W("tasks/cancel"),params:Ct.extend({taskId:A()})}),l_=it.merge(Ms),u_=H({uri:A(),mimeType:Ze(A()),_meta:ze(A(),qe()).optional()}),d_=u_.extend({text:A()}),Gp=A().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),p_=u_.extend({blob:Gp}),Zs=St(["user","assistant"]),To=H({audience:we(Zs).optional(),priority:Ee().min(0).max(1).optional(),lastModified:Cs.datetime({offset:!0}).optional()}),h_=H({...$o.shape,...Ls.shape,uri:A(),description:Ze(A()),mimeType:Ze(A()),size:Ze(Ee()),annotations:To.optional(),_meta:Ze(gt({}))}),WI=H({...$o.shape,...Ls.shape,uriTemplate:A(),description:Ze(A()),mimeType:Ze(A()),annotations:To.optional(),_meta:Ze(gt({}))}),Ga=Ds.extend({method:W("resources/list")}),JI=Us.extend({resources:we(h_)}),Wa=Ds.extend({method:W("resources/templates/list")}),YI=Us.extend({resourceTemplates:we(WI)}),Wp=Ct.extend({uri:A()}),QI=Wp,Ja=st.extend({method:W("resources/read"),params:QI}),XI=it.extend({contents:we(je([d_,p_]))}),eO=Zt.extend({method:W("notifications/resources/list_changed"),params:qt.optional()}),tO=Wp,rO=st.extend({method:W("resources/subscribe"),params:tO}),nO=Wp,oO=st.extend({method:W("resources/unsubscribe"),params:nO}),sO=qt.extend({uri:A()}),iO=Zt.extend({method:W("notifications/resources/updated"),params:sO}),aO=H({name:A(),description:Ze(A()),required:Ze(tt())}),cO=H({...$o.shape,...Ls.shape,description:Ze(A()),arguments:Ze(we(aO)),_meta:Ze(gt({}))}),Ya=Ds.extend({method:W("prompts/list")}),lO=Us.extend({prompts:we(cO)}),uO=Ct.extend({name:A(),arguments:ze(A(),A()).optional()}),Qa=st.extend({method:W("prompts/get"),params:uO}),Jp=H({type:W("text"),text:A(),annotations:To.optional(),_meta:ze(A(),qe()).optional()}),Yp=H({type:W("image"),data:Gp,mimeType:A(),annotations:To.optional(),_meta:ze(A(),qe()).optional()}),Qp=H({type:W("audio"),data:Gp,mimeType:A(),annotations:To.optional(),_meta:ze(A(),qe()).optional()}),dO=H({type:W("tool_use"),name:A(),id:A(),input:ze(A(),qe()),_meta:ze(A(),qe()).optional()}),pO=H({type:W("resource"),resource:je([d_,p_]),annotations:To.optional(),_meta:ze(A(),qe()).optional()}),hO=h_.extend({type:W("resource_link")}),Xp=je([Jp,Yp,Qp,hO,pO]),fO=H({role:Zs,content:Xp}),mO=it.extend({description:A().optional(),messages:we(fO)}),gO=Zt.extend({method:W("notifications/prompts/list_changed"),params:qt.optional()}),yO=H({title:A().optional(),readOnlyHint:tt().optional(),destructiveHint:tt().optional(),idempotentHint:tt().optional(),openWorldHint:tt().optional()}),bO=H({taskSupport:St(["required","optional","forbidden"]).optional()}),f_=H({...$o.shape,...Ls.shape,description:A().optional(),inputSchema:H({type:W("object"),properties:ze(A(),Qe).optional(),required:we(A()).optional()}).catchall(qe()),outputSchema:H({type:W("object"),properties:ze(A(),Qe).optional(),required:we(A()).optional()}).catchall(qe()).optional(),annotations:yO.optional(),execution:bO.optional(),_meta:ze(A(),qe()).optional()}),Xa=Ds.extend({method:W("tools/list")}),wO=Us.extend({tools:we(f_)}),ec=it.extend({content:we(Xp).default([]),structuredContent:ze(A(),qe()).optional(),isError:tt().optional()}),oF=ec.or(it.extend({toolResult:qe()})),vO=zs.extend({name:A(),arguments:ze(A(),qe()).optional()}),Eo=st.extend({method:W("tools/call"),params:vO}),_O=Zt.extend({method:W("notifications/tools/list_changed"),params:qt.optional()}),sF=H({autoRefresh:tt().default(!0),debounceMs:Ee().int().nonnegative().default(300)}),Bs=St(["debug","info","notice","warning","error","critical","alert","emergency"]),xO=Ct.extend({level:Bs}),eh=st.extend({method:W("logging/setLevel"),params:xO}),kO=qt.extend({level:Bs,logger:A().optional(),data:qe()}),$O=Zt.extend({method:W("notifications/message"),params:kO}),SO=H({name:A().optional()}),TO=H({hints:we(SO).optional(),costPriority:Ee().min(0).max(1).optional(),speedPriority:Ee().min(0).max(1).optional(),intelligencePriority:Ee().min(0).max(1).optional()}),EO=H({mode:St(["auto","required","none"]).optional()}),RO=H({type:W("tool_result"),toolUseId:A().describe("The unique identifier for the corresponding tool call."),content:we(Xp).default([]),structuredContent:H({}).loose().optional(),isError:tt().optional(),_meta:ze(A(),qe()).optional()}),PO=Dp("type",[Jp,Yp,Qp]),za=Dp("type",[Jp,Yp,Qp,dO,RO]),AO=H({role:Zs,content:je([za,we(za)]),_meta:ze(A(),qe()).optional()}),IO=zs.extend({messages:we(AO),modelPreferences:TO.optional(),systemPrompt:A().optional(),includeContext:St(["none","thisServer","allServers"]).optional(),temperature:Ee().optional(),maxTokens:Ee().int(),stopSequences:we(A()).optional(),metadata:Qe.optional(),tools:we(f_).optional(),toolChoice:EO.optional()}),OO=st.extend({method:W("sampling/createMessage"),params:IO}),Fs=it.extend({model:A(),stopReason:Ze(St(["endTurn","stopSequence","maxTokens"]).or(A())),role:Zs,content:PO}),th=it.extend({model:A(),stopReason:Ze(St(["endTurn","stopSequence","maxTokens","toolUse"]).or(A())),role:Zs,content:je([za,we(za)])}),CO=H({type:W("boolean"),title:A().optional(),description:A().optional(),default:tt().optional()}),NO=H({type:W("string"),title:A().optional(),description:A().optional(),minLength:Ee().optional(),maxLength:Ee().optional(),format:St(["email","uri","date","date-time"]).optional(),default:A().optional()}),zO=H({type:St(["number","integer"]),title:A().optional(),description:A().optional(),minimum:Ee().optional(),maximum:Ee().optional(),default:Ee().optional()}),jO=H({type:W("string"),title:A().optional(),description:A().optional(),enum:we(A()),default:A().optional()}),LO=H({type:W("string"),title:A().optional(),description:A().optional(),oneOf:we(H({const:A(),title:A()})),default:A().optional()}),DO=H({type:W("string"),title:A().optional(),description:A().optional(),enum:we(A()),enumNames:we(A()).optional(),default:A().optional()}),UO=je([jO,LO]),MO=H({type:W("array"),title:A().optional(),description:A().optional(),minItems:Ee().optional(),maxItems:Ee().optional(),items:H({type:W("string"),enum:we(A())}),default:we(A()).optional()}),qO=H({type:W("array"),title:A().optional(),description:A().optional(),minItems:Ee().optional(),maxItems:Ee().optional(),items:H({anyOf:we(H({const:A(),title:A()}))}),default:we(A()).optional()}),ZO=je([MO,qO]),BO=je([DO,UO,ZO]),FO=je([BO,CO,NO,zO]),HO=zs.extend({mode:W("form").optional(),message:A(),requestedSchema:H({type:W("object"),properties:ze(A(),FO),required:we(A()).optional()})}),VO=zs.extend({mode:W("url"),message:A(),elicitationId:A(),url:A().url()}),KO=je([HO,VO]),GO=st.extend({method:W("elicitation/create"),params:KO}),WO=qt.extend({elicitationId:A()}),JO=Zt.extend({method:W("notifications/elicitation/complete"),params:WO}),Ro=it.extend({action:St(["accept","decline","cancel"]),content:Up(t=>t===null?void 0:t,ze(A(),je([A(),Ee(),tt(),we(A())])).optional())}),YO=H({type:W("ref/resource"),uri:A()}),QO=H({type:W("ref/prompt"),name:A()}),XO=Ct.extend({ref:je([QO,YO]),argument:H({name:A(),value:A()}),context:H({arguments:ze(A(),A()).optional()}).optional()}),tc=st.extend({method:W("completion/complete"),params:XO});eC=it.extend({completion:gt({values:we(A()).max(100),total:Ze(Ee().int()),hasMore:Ze(tt())})}),tC=H({uri:A().startsWith("file://"),name:A().optional(),_meta:ze(A(),qe()).optional()}),rC=st.extend({method:W("roots/list"),params:Ct.optional()}),rh=it.extend({roots:we(tC)}),nC=Zt.extend({method:W("notifications/roots/list_changed"),params:qt.optional()}),iF=je([Ma,Vp,tc,eh,Qa,Ya,Ga,Wa,Ja,rO,oO,Eo,Xa,Za,Fa,Ha,Ka]),aF=je([Ua,qa,Kp,nC,qs]),cF=je([Da,Fs,th,Ro,rh,Ba,Va,So]),lF=je([Ma,OO,GO,rC,Za,Fa,Ha,Ka]),uF=je([Ua,qa,$O,iO,eO,_O,gO,qs,JO]),dF=je([Da,BI,eC,mO,lO,JI,YI,XI,ec,wO,Ba,Va,So]),G=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===X.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Mp(o.elicitations,r)}return new t(e,r,n)}},Mp=class extends G{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(X.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Qr(t){return t==="completed"||t==="failed"||t==="cancelled"}var y_=N(()=>{});var w_,b_,v_,rc=N(()=>{w_=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"},v_=t=>typeof t=="string"?{...b_,name:t}:{...b_,...t}});var __,nh=N(()=>{rc();__=t=>{let e=v_(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 oh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ve(t,e,r,n,o){t[e]=r,oh(t,e,n,o)}var Xr=N(()=>{});var nc,oc=N(()=>{nc=(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 Be(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?nc(e,t.currentPath):e.join("/")}}var Bt=N(()=>{oc()});function x_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=se(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ve(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ve(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ve(r,"minItems",t.exactLength.value,t.exactLength.message,e),ve(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var sh=N(()=>{ws();Xr();Je()});function k_(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?ve(r,"minimum",n.value,n.message,e):ve(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ve(r,"maximum",n.value,n.message,e):ve(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",n.value,n.message,e));break;case"multipleOf":ve(r,"multipleOf",n.value,n.message,e);break}return r}var ih=N(()=>{Xr()});function $_(){return{type:"boolean"}}var ah=N(()=>{});function sc(t,e){return se(t.type._def,e)}var ic=N(()=>{Je()});var S_,ch=N(()=>{Je();S_=(t,e)=>se(t.innerType._def,e)});function lh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>lh(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 oC(t,e)}}var oC,uh=N(()=>{Xr();oC=(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":ve(r,"minimum",n.value,n.message,e);break;case"max":ve(r,"maximum",n.value,n.message,e);break}return r}});function T_(t,e){return{...se(t.innerType._def,e),default:t.defaultValue()}}var dh=N(()=>{Je()});function E_(t,e){return e.effectStrategy==="input"?se(t.schema._def,e):Be(e)}var ph=N(()=>{Je();Bt()});function R_(t){return{type:"string",enum:Array.from(t.values)}}var hh=N(()=>{});function P_(t,e){let r=[se(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),se(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(sC(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 sC,fh=N(()=>{Je();sC=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function A_(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 mh=N(()=>{});function ac(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ve(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ve(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":rr(r,"email",n.message,e);break;case"format:idn-email":rr(r,"idn-email",n.message,e);break;case"pattern:zod":yt(r,tr.email,n.message,e);break}break;case"url":rr(r,"uri",n.message,e);break;case"uuid":rr(r,"uuid",n.message,e);break;case"regex":yt(r,n.regex,n.message,e);break;case"cuid":yt(r,tr.cuid,n.message,e);break;case"cuid2":yt(r,tr.cuid2,n.message,e);break;case"startsWith":yt(r,RegExp(`^${yh(n.value,e)}`),n.message,e);break;case"endsWith":yt(r,RegExp(`${yh(n.value,e)}$`),n.message,e);break;case"datetime":rr(r,"date-time",n.message,e);break;case"date":rr(r,"date",n.message,e);break;case"time":rr(r,"time",n.message,e);break;case"duration":rr(r,"duration",n.message,e);break;case"length":ve(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ve(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{yt(r,RegExp(yh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&rr(r,"ipv4",n.message,e),n.version!=="v4"&&rr(r,"ipv6",n.message,e);break}case"base64url":yt(r,tr.base64url,n.message,e);break;case"jwt":yt(r,tr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&yt(r,tr.ipv4Cidr,n.message,e),n.version!=="v4"&&yt(r,tr.ipv6Cidr,n.message,e);break}case"emoji":yt(r,tr.emoji(),n.message,e);break;case"ulid":{yt(r,tr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{rr(r,"binary",n.message,e);break}case"contentEncoding:base64":{ve(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{yt(r,tr.base64,n.message,e);break}}break}case"nanoid":yt(r,tr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function yh(t,e){return e.patternStrategy==="escape"?aC(t):t}function aC(t){let e="";for(let r=0;r<t.length;r++)iC.has(t[r])||(e+="\\"),e+=t[r];return e}function rr(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}}})):ve(t,"format",e,r,n)}function yt(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}}})):ve(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
|
|
1906
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(e===u[0]){i(u);continue}if(n.external){let m=n.external.registry.get(u[0])?.id;if(e!==u[0]&&m){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(p.cycle){i(u);continue}if(p.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,p)=>{let w=this.seen.get(u),m=w.def??w.schema,h={...m};if(w.ref===null)return;let b=w.ref;if(w.ref=null,b){a(b,p);let $=this.seen.get(b).schema;$.$ref&&p.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push($)):(Object.assign(m,$),Object.assign(m,h))}w.isParent||this.override({zodSchema:u,jsonSchema:m,path:w.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 p=u[1];p.def&&p.defId&&(l[p.defId]=p.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 yv=O(()=>{});var gt=O(()=>{yo();Zu();zu();sv();ba();Wu();pr();ya();$a();Ld();Ku();mv();fv();gv();yv()});var Sp=O(()=>{gt()});function Tp(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new IA(r)}var AA,IA,bv=O(()=>{gt();gt();Sp();AA=I("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Pe.init(t,e),t.def=e,t.parse=(r,n)=>Lu(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>On(t,r,n),t.parseAsync=async(r,n)=>Uu(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Cn(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)=>Ct(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),IA=I("ZodMiniObject",(t,e)=>{xa.init(t,e),AA.init(t,e),be.defineLazy(t,"shape",()=>e.shape)})});var wv=O(()=>{});var vv=O(()=>{});var _v=O(()=>{});var xv=O(()=>{gt();Sp();bv();wv();gt();$a();vv();_v()});var kv=O(()=>{xv()});var Ep=O(()=>{kv()});function hr(t){return!!t._zod}function jn(t){let e=Object.values(t);if(e.length===0)return Tp({});let r=e.every(hr),n=e.every(o=>!hr(o));if(r)return Tp(t);if(n)return El(t);throw new Error("Mixed Zod versions detected in object shape.")}function Jr(t,e){return hr(t)?On(t,e):t.safeParse(e)}async function Oa(t,e){return hr(t)?await Cn(t,e):await t.safeParseAsync(e)}function Yr(t){if(!t)return;let e;if(hr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function _o(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 jn(t)}}if(hr(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 NA(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Ca(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 ${NA(e.path)}`:e.message).join(`
|
|
1907
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Sv(t){return t.description}function Tv(t){if(hr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function xo(t){if(hr(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 Is=O(()=>{bs();Ep()});var Rp=O(()=>{gt()});var Os={};Jo(Os,{ZodISODate:()=>Rv,ZodISODateTime:()=>Ev,ZodISODuration:()=>Av,ZodISOTime:()=>Pv,date:()=>Ap,datetime:()=>Pp,duration:()=>Op,time:()=>Ip});function Pp(t){return lv(Ev,t)}function Ap(t){return uv(Rv,t)}function Ip(t){return dv(Pv,t)}function Op(t){return pv(Av,t)}var Ev,Rv,Pv,Av,Cp=O(()=>{gt();Np();Ev=I("ZodISODateTime",(t,e)=>{ev.init(t,e),Me.init(t,e)});Rv=I("ZodISODate",(t,e)=>{tv.init(t,e),Me.init(t,e)});Pv=I("ZodISOTime",(t,e)=>{rv.init(t,e),Me.init(t,e)});Av=I("ZodISODuration",(t,e)=>{nv.init(t,e),Me.init(t,e)})});var Iv,qB,Cs,zp=O(()=>{gt();gt();Iv=(t,e)=>{ma.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Nu(t,r)},flatten:{value:r=>Cu(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},qB=I("ZodError",Iv),Cs=I("ZodError",Iv,{Parent:Error})});var Ov,Cv,Nv,zv,jp=O(()=>{gt();zp();Ov=ju(Cs),Cv=Du(Cs),Nv=Mu(Cs),zv=qu(Cs)});function A(t){return Dd(ZA,t)}function Re(t){return ip(Mv,t)}function Lv(t){return ap(iI,t)}function rt(t){return cp(aI,t)}function qv(t){return lp(cI,t)}function qe(){return up(lI)}function dI(t){return dp(uI,t)}function we(t,e){return hv(pI,t,e)}function H(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new Zv(r)}function yt(t,e){return new Zv({type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},catchall:qe(),...be.normalizeParams(e)})}function je(t,e){return new Bv({type:"union",options:t,...be.normalizeParams(e)})}function Up(t,e,r){return new hI({type:"union",options:e,discriminator:t,...be.normalizeParams(r)})}function za(t,e){return new fI({type:"intersection",left:t,right:e})}function ze(t,e,r){return new mI({type:"record",keyType:t,valueType:e,...be.normalizeParams(r)})}function St(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Lp({type:"enum",entries:r,...be.normalizeParams(e)})}function J(t,e){return new gI({type:"literal",values:Array.isArray(t)?t:[t],...be.normalizeParams(e)})}function Fv(t){return new yI({type:"transform",transform:t})}function Ze(t){return new Hv({type:"optional",innerType:t})}function Dv(t){return new bI({type:"nullable",innerType:t})}function vI(t,e){return new wI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function xI(t,e){return new _I({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function kI(t,e){return new Vv({type:"nonoptional",innerType:t,...be.normalizeParams(e)})}function SI(t,e){return new $I({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Dp(t,e){return new TI({type:"pipe",in:t,out:e})}function RI(t){return new EI({type:"readonly",innerType:t})}function PI(t){let e=new ot({check:"custom"});return e._zod.check=t,e}function Wv(t,e){return xp(Kv,t??(()=>!0),e)}function AI(t,e={}){return kp(Kv,t,e)}function II(t){let e=PI(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(be.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(be.issue(o))}},t(r.value,r)));return e}function Mp(t,e){return Dp(Fv(t),e)}var Fe,Uv,ZA,Me,BA,jv,Na,FA,HA,VA,KA,WA,GA,JA,YA,XA,QA,eI,tI,rI,nI,oI,sI,Mv,iI,aI,cI,lI,uI,pI,Zv,Bv,hI,fI,mI,Lp,gI,yI,Hv,bI,wI,_I,Vv,$I,TI,EI,Kv,Np=O(()=>{gt();gt();Rp();Cp();jp();Fe=I("ZodType",(t,e)=>(Pe.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)=>Ct(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Ov(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Nv(t,r,n),t.parseAsync=async(r,n)=>Cv(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>zv(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(AI(r,n)),t.superRefine=r=>t.check(II(r)),t.overwrite=r=>t.check(Nn(r)),t.optional=()=>Ze(t),t.nullable=()=>Dv(t),t.nullish=()=>Ze(Dv(t)),t.nonoptional=r=>kI(t,r),t.array=()=>we(t),t.or=r=>je([t,r]),t.and=r=>za(t,r),t.transform=r=>Dp(t,Fv(r)),t.default=r=>vI(t,r),t.prefault=r=>xI(t,r),t.catch=r=>SI(t,r),t.pipe=r=>Dp(t,r),t.readonly=()=>RI(t),t.describe=r=>{let n=t.clone();return Gr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Gr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Gr.get(t);let n=t.clone();return Gr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Uv=I("_ZodString",(t,e)=>{Es.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(pp(...n)),t.includes=(...n)=>t.check(mp(...n)),t.startsWith=(...n)=>t.check(gp(...n)),t.endsWith=(...n)=>t.check(yp(...n)),t.min=(...n)=>t.check(vo(...n)),t.max=(...n)=>t.check(Pa(...n)),t.length=(...n)=>t.check(Aa(...n)),t.nonempty=(...n)=>t.check(vo(1,...n)),t.lowercase=n=>t.check(hp(n)),t.uppercase=n=>t.check(fp(n)),t.trim=()=>t.check(wp()),t.normalize=(...n)=>t.check(bp(...n)),t.toLowerCase=()=>t.check(vp()),t.toUpperCase=()=>t.check(_p())}),ZA=I("ZodString",(t,e)=>{Es.init(t,e),Uv.init(t,e),t.email=r=>t.check(Ud(BA,r)),t.url=r=>t.check(Fd(FA,r)),t.jwt=r=>t.check(sp(sI,r)),t.emoji=r=>t.check(Hd(HA,r)),t.guid=r=>t.check(Sa(jv,r)),t.uuid=r=>t.check(Md(Na,r)),t.uuidv4=r=>t.check(qd(Na,r)),t.uuidv6=r=>t.check(Zd(Na,r)),t.uuidv7=r=>t.check(Bd(Na,r)),t.nanoid=r=>t.check(Vd(VA,r)),t.guid=r=>t.check(Sa(jv,r)),t.cuid=r=>t.check(Kd(KA,r)),t.cuid2=r=>t.check(Wd(WA,r)),t.ulid=r=>t.check(Gd(GA,r)),t.base64=r=>t.check(rp(rI,r)),t.base64url=r=>t.check(np(nI,r)),t.xid=r=>t.check(Jd(JA,r)),t.ksuid=r=>t.check(Yd(YA,r)),t.ipv4=r=>t.check(Xd(XA,r)),t.ipv6=r=>t.check(Qd(QA,r)),t.cidrv4=r=>t.check(ep(eI,r)),t.cidrv6=r=>t.check(tp(tI,r)),t.e164=r=>t.check(op(oI,r)),t.datetime=r=>t.check(Pp(r)),t.date=r=>t.check(Ap(r)),t.time=r=>t.check(Ip(r)),t.duration=r=>t.check(Op(r))});Me=I("ZodStringFormat",(t,e)=>{Ne.init(t,e),Uv.init(t,e)}),BA=I("ZodEmail",(t,e)=>{Xu.init(t,e),Me.init(t,e)}),jv=I("ZodGUID",(t,e)=>{Ju.init(t,e),Me.init(t,e)}),Na=I("ZodUUID",(t,e)=>{Yu.init(t,e),Me.init(t,e)}),FA=I("ZodURL",(t,e)=>{Qu.init(t,e),Me.init(t,e)}),HA=I("ZodEmoji",(t,e)=>{ed.init(t,e),Me.init(t,e)}),VA=I("ZodNanoID",(t,e)=>{td.init(t,e),Me.init(t,e)}),KA=I("ZodCUID",(t,e)=>{rd.init(t,e),Me.init(t,e)}),WA=I("ZodCUID2",(t,e)=>{nd.init(t,e),Me.init(t,e)}),GA=I("ZodULID",(t,e)=>{od.init(t,e),Me.init(t,e)}),JA=I("ZodXID",(t,e)=>{sd.init(t,e),Me.init(t,e)}),YA=I("ZodKSUID",(t,e)=>{id.init(t,e),Me.init(t,e)}),XA=I("ZodIPv4",(t,e)=>{ad.init(t,e),Me.init(t,e)}),QA=I("ZodIPv6",(t,e)=>{cd.init(t,e),Me.init(t,e)}),eI=I("ZodCIDRv4",(t,e)=>{ld.init(t,e),Me.init(t,e)}),tI=I("ZodCIDRv6",(t,e)=>{ud.init(t,e),Me.init(t,e)}),rI=I("ZodBase64",(t,e)=>{dd.init(t,e),Me.init(t,e)}),nI=I("ZodBase64URL",(t,e)=>{pd.init(t,e),Me.init(t,e)}),oI=I("ZodE164",(t,e)=>{hd.init(t,e),Me.init(t,e)}),sI=I("ZodJWT",(t,e)=>{fd.init(t,e),Me.init(t,e)}),Mv=I("ZodNumber",(t,e)=>{_a.init(t,e),Fe.init(t,e),t.gt=(n,o)=>t.check(Ea(n,o)),t.gte=(n,o)=>t.check(As(n,o)),t.min=(n,o)=>t.check(As(n,o)),t.lt=(n,o)=>t.check(Ta(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(Lv(n)),t.safe=n=>t.check(Lv(n)),t.positive=n=>t.check(Ea(0,n)),t.nonnegative=n=>t.check(As(0,n)),t.negative=n=>t.check(Ta(0,n)),t.nonpositive=n=>t.check(Ps(0,n)),t.multipleOf=(n,o)=>t.check(Ra(n,o)),t.step=(n,o)=>t.check(Ra(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});iI=I("ZodNumberFormat",(t,e)=>{md.init(t,e),Mv.init(t,e)});aI=I("ZodBoolean",(t,e)=>{gd.init(t,e),Fe.init(t,e)});cI=I("ZodNull",(t,e)=>{yd.init(t,e),Fe.init(t,e)});lI=I("ZodUnknown",(t,e)=>{bd.init(t,e),Fe.init(t,e)});uI=I("ZodNever",(t,e)=>{wd.init(t,e),Fe.init(t,e)});pI=I("ZodArray",(t,e)=>{vd.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(vo(r,n)),t.nonempty=r=>t.check(vo(1,r)),t.max=(r,n)=>t.check(Pa(r,n)),t.length=(r,n)=>t.check(Aa(r,n)),t.unwrap=()=>t.element});Zv=I("ZodObject",(t,e)=>{xa.init(t,e),Fe.init(t,e),be.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>St(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:qe()}),t.loose=()=>t.clone({...t._zod.def,catchall:qe()}),t.strict=()=>t.clone({...t._zod.def,catchall:dI()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>be.extend(t,r),t.merge=r=>be.merge(t,r),t.pick=r=>be.pick(t,r),t.omit=r=>be.omit(t,r),t.partial=(...r)=>be.partial(Hv,t,r[0]),t.required=(...r)=>be.required(Vv,t,r[0])});Bv=I("ZodUnion",(t,e)=>{ka.init(t,e),Fe.init(t,e),t.options=e.options});hI=I("ZodDiscriminatedUnion",(t,e)=>{Bv.init(t,e),_d.init(t,e)});fI=I("ZodIntersection",(t,e)=>{xd.init(t,e),Fe.init(t,e)});mI=I("ZodRecord",(t,e)=>{kd.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Lp=I("ZodEnum",(t,e)=>{$d.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 Lp({...e,checks:[],...be.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 Lp({...e,checks:[],...be.normalizeParams(o),entries:s})}});gI=I("ZodLiteral",(t,e)=>{Sd.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]}})});yI=I("ZodTransform",(t,e)=>{Td.init(t,e),Fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(be.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(be.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Hv=I("ZodOptional",(t,e)=>{Ed.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});bI=I("ZodNullable",(t,e)=>{Rd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});wI=I("ZodDefault",(t,e)=>{Pd.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});_I=I("ZodPrefault",(t,e)=>{Ad.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});Vv=I("ZodNonOptional",(t,e)=>{Id.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});$I=I("ZodCatch",(t,e)=>{Od.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});TI=I("ZodPipe",(t,e)=>{Cd.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});EI=I("ZodReadonly",(t,e)=>{Nd.init(t,e),Fe.init(t,e)});Kv=I("ZodCustom",(t,e)=>{zd.init(t,e),Fe.init(t,e)})});var Gv=O(()=>{});var Jv=O(()=>{});var Yv=O(()=>{gt();Np();Rp();zp();jp();Gv();gt();av();$a();Cp();Jv();Ot(iv())});var Xv=O(()=>{Yv()});var Qv=O(()=>{Xv()});function g_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function y_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Zp,e_,Xr,La,Xe,t_,r_,nF,NI,zI,Bp,Nt,Ns,n_,st,Zt,Bt,it,Da,o_,Fp,s_,i_,Hp,zs,ee,Vp,a_,c_,oF,Ua,jI,Ma,LI,js,ko,l_,DI,UI,MI,qI,ZI,BI,Kp,FI,HI,Wp,qa,VI,KI,Za,WI,Ls,Ds,GI,Us,$o,JI,Ms,Ba,Fa,Ha,sF,Va,Ka,Wa,u_,d_,p_,Gp,h_,qs,So,f_,YI,Ga,XI,Ja,QI,Jp,eO,Ya,tO,rO,nO,oO,sO,iO,aO,cO,lO,uO,Xa,dO,pO,Qa,Yp,Xp,Qp,hO,fO,mO,eh,gO,yO,bO,wO,vO,m_,ec,_O,tc,iF,xO,To,kO,aF,Zs,$O,th,SO,TO,EO,RO,PO,AO,IO,ja,OO,CO,NO,Bs,rh,zO,jO,LO,DO,UO,MO,qO,ZO,BO,FO,HO,VO,KO,WO,GO,JO,YO,XO,Eo,QO,eC,tC,rc,rC,nC,oC,nh,sC,cF,lF,uF,dF,pF,hF,G,qp,Ro=O(()=>{Qv();Zp="2025-11-25",e_=[Zp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Xr="io.modelcontextprotocol/related-task",La="2.0",Xe=Wv(t=>t!==null&&(typeof t=="object"||typeof t=="function")),t_=je([A(),Re().int()]),r_=A(),nF=yt({ttl:Re().optional(),pollInterval:Re().optional()}),NI=H({ttl:Re().optional()}),zI=H({taskId:A()}),Bp=yt({progressToken:t_.optional(),[Xr]:zI.optional()}),Nt=H({_meta:Bp.optional()}),Ns=Nt.extend({task:NI.optional()}),n_=t=>Ns.safeParse(t).success,st=H({method:A(),params:Nt.loose().optional()}),Zt=H({_meta:Bp.optional()}),Bt=H({method:A(),params:Zt.loose().optional()}),it=yt({_meta:Bp.optional()}),Da=je([A(),Re().int()]),o_=H({jsonrpc:J(La),id:Da,...st.shape}).strict(),Fp=t=>o_.safeParse(t).success,s_=H({jsonrpc:J(La),...Bt.shape}).strict(),i_=t=>s_.safeParse(t).success,Hp=H({jsonrpc:J(La),id:Da,result:it}).strict(),zs=t=>Hp.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"})(ee||(ee={}));Vp=H({jsonrpc:J(La),id:Da.optional(),error:H({code:Re().int(),message:A(),data:qe().optional()})}).strict(),a_=t=>Vp.safeParse(t).success,c_=je([o_,s_,Hp,Vp]),oF=je([Hp,Vp]),Ua=it.strict(),jI=Zt.extend({requestId:Da.optional(),reason:A().optional()}),Ma=Bt.extend({method:J("notifications/cancelled"),params:jI}),LI=H({src:A(),mimeType:A().optional(),sizes:we(A()).optional(),theme:St(["light","dark"]).optional()}),js=H({icons:we(LI).optional()}),ko=H({name:A(),title:A().optional()}),l_=ko.extend({...ko.shape,...js.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),DI=za(H({applyDefaults:rt().optional()}),ze(A(),qe())),UI=Mp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,za(H({form:DI.optional(),url:Xe.optional()}),ze(A(),qe()).optional())),MI=yt({list:Xe.optional(),cancel:Xe.optional(),requests:yt({sampling:yt({createMessage:Xe.optional()}).optional(),elicitation:yt({create:Xe.optional()}).optional()}).optional()}),qI=yt({list:Xe.optional(),cancel:Xe.optional(),requests:yt({tools:yt({call:Xe.optional()}).optional()}).optional()}),ZI=H({experimental:ze(A(),Xe).optional(),sampling:H({context:Xe.optional(),tools:Xe.optional()}).optional(),elicitation:UI.optional(),roots:H({listChanged:rt().optional()}).optional(),tasks:MI.optional(),extensions:ze(A(),Xe).optional()}),BI=Nt.extend({protocolVersion:A(),capabilities:ZI,clientInfo:l_}),Kp=st.extend({method:J("initialize"),params:BI}),FI=H({experimental:ze(A(),Xe).optional(),logging:Xe.optional(),completions:Xe.optional(),prompts:H({listChanged:rt().optional()}).optional(),resources:H({subscribe:rt().optional(),listChanged:rt().optional()}).optional(),tools:H({listChanged:rt().optional()}).optional(),tasks:qI.optional(),extensions:ze(A(),Xe).optional()}),HI=it.extend({protocolVersion:A(),capabilities:FI,serverInfo:l_,instructions:A().optional()}),Wp=Bt.extend({method:J("notifications/initialized"),params:Zt.optional()}),qa=st.extend({method:J("ping"),params:Nt.optional()}),VI=H({progress:Re(),total:Ze(Re()),message:Ze(A())}),KI=H({...Zt.shape,...VI.shape,progressToken:t_}),Za=Bt.extend({method:J("notifications/progress"),params:KI}),WI=Nt.extend({cursor:r_.optional()}),Ls=st.extend({params:WI.optional()}),Ds=it.extend({nextCursor:r_.optional()}),GI=St(["working","input_required","completed","failed","cancelled"]),Us=H({taskId:A(),status:GI,ttl:je([Re(),qv()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Ze(Re()),statusMessage:Ze(A())}),$o=it.extend({task:Us}),JI=Zt.merge(Us),Ms=Bt.extend({method:J("notifications/tasks/status"),params:JI}),Ba=st.extend({method:J("tasks/get"),params:Nt.extend({taskId:A()})}),Fa=it.merge(Us),Ha=st.extend({method:J("tasks/result"),params:Nt.extend({taskId:A()})}),sF=it.loose(),Va=Ls.extend({method:J("tasks/list")}),Ka=Ds.extend({tasks:we(Us)}),Wa=st.extend({method:J("tasks/cancel"),params:Nt.extend({taskId:A()})}),u_=it.merge(Us),d_=H({uri:A(),mimeType:Ze(A()),_meta:ze(A(),qe()).optional()}),p_=d_.extend({text:A()}),Gp=A().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),h_=d_.extend({blob:Gp}),qs=St(["user","assistant"]),So=H({audience:we(qs).optional(),priority:Re().min(0).max(1).optional(),lastModified:Os.datetime({offset:!0}).optional()}),f_=H({...ko.shape,...js.shape,uri:A(),description:Ze(A()),mimeType:Ze(A()),size:Ze(Re()),annotations:So.optional(),_meta:Ze(yt({}))}),YI=H({...ko.shape,...js.shape,uriTemplate:A(),description:Ze(A()),mimeType:Ze(A()),annotations:So.optional(),_meta:Ze(yt({}))}),Ga=Ls.extend({method:J("resources/list")}),XI=Ds.extend({resources:we(f_)}),Ja=Ls.extend({method:J("resources/templates/list")}),QI=Ds.extend({resourceTemplates:we(YI)}),Jp=Nt.extend({uri:A()}),eO=Jp,Ya=st.extend({method:J("resources/read"),params:eO}),tO=it.extend({contents:we(je([p_,h_]))}),rO=Bt.extend({method:J("notifications/resources/list_changed"),params:Zt.optional()}),nO=Jp,oO=st.extend({method:J("resources/subscribe"),params:nO}),sO=Jp,iO=st.extend({method:J("resources/unsubscribe"),params:sO}),aO=Zt.extend({uri:A()}),cO=Bt.extend({method:J("notifications/resources/updated"),params:aO}),lO=H({name:A(),description:Ze(A()),required:Ze(rt())}),uO=H({...ko.shape,...js.shape,description:Ze(A()),arguments:Ze(we(lO)),_meta:Ze(yt({}))}),Xa=Ls.extend({method:J("prompts/list")}),dO=Ds.extend({prompts:we(uO)}),pO=Nt.extend({name:A(),arguments:ze(A(),A()).optional()}),Qa=st.extend({method:J("prompts/get"),params:pO}),Yp=H({type:J("text"),text:A(),annotations:So.optional(),_meta:ze(A(),qe()).optional()}),Xp=H({type:J("image"),data:Gp,mimeType:A(),annotations:So.optional(),_meta:ze(A(),qe()).optional()}),Qp=H({type:J("audio"),data:Gp,mimeType:A(),annotations:So.optional(),_meta:ze(A(),qe()).optional()}),hO=H({type:J("tool_use"),name:A(),id:A(),input:ze(A(),qe()),_meta:ze(A(),qe()).optional()}),fO=H({type:J("resource"),resource:je([p_,h_]),annotations:So.optional(),_meta:ze(A(),qe()).optional()}),mO=f_.extend({type:J("resource_link")}),eh=je([Yp,Xp,Qp,mO,fO]),gO=H({role:qs,content:eh}),yO=it.extend({description:A().optional(),messages:we(gO)}),bO=Bt.extend({method:J("notifications/prompts/list_changed"),params:Zt.optional()}),wO=H({title:A().optional(),readOnlyHint:rt().optional(),destructiveHint:rt().optional(),idempotentHint:rt().optional(),openWorldHint:rt().optional()}),vO=H({taskSupport:St(["required","optional","forbidden"]).optional()}),m_=H({...ko.shape,...js.shape,description:A().optional(),inputSchema:H({type:J("object"),properties:ze(A(),Xe).optional(),required:we(A()).optional()}).catchall(qe()),outputSchema:H({type:J("object"),properties:ze(A(),Xe).optional(),required:we(A()).optional()}).catchall(qe()).optional(),annotations:wO.optional(),execution:vO.optional(),_meta:ze(A(),qe()).optional()}),ec=Ls.extend({method:J("tools/list")}),_O=Ds.extend({tools:we(m_)}),tc=it.extend({content:we(eh).default([]),structuredContent:ze(A(),qe()).optional(),isError:rt().optional()}),iF=tc.or(it.extend({toolResult:qe()})),xO=Ns.extend({name:A(),arguments:ze(A(),qe()).optional()}),To=st.extend({method:J("tools/call"),params:xO}),kO=Bt.extend({method:J("notifications/tools/list_changed"),params:Zt.optional()}),aF=H({autoRefresh:rt().default(!0),debounceMs:Re().int().nonnegative().default(300)}),Zs=St(["debug","info","notice","warning","error","critical","alert","emergency"]),$O=Nt.extend({level:Zs}),th=st.extend({method:J("logging/setLevel"),params:$O}),SO=Zt.extend({level:Zs,logger:A().optional(),data:qe()}),TO=Bt.extend({method:J("notifications/message"),params:SO}),EO=H({name:A().optional()}),RO=H({hints:we(EO).optional(),costPriority:Re().min(0).max(1).optional(),speedPriority:Re().min(0).max(1).optional(),intelligencePriority:Re().min(0).max(1).optional()}),PO=H({mode:St(["auto","required","none"]).optional()}),AO=H({type:J("tool_result"),toolUseId:A().describe("The unique identifier for the corresponding tool call."),content:we(eh).default([]),structuredContent:H({}).loose().optional(),isError:rt().optional(),_meta:ze(A(),qe()).optional()}),IO=Up("type",[Yp,Xp,Qp]),ja=Up("type",[Yp,Xp,Qp,hO,AO]),OO=H({role:qs,content:je([ja,we(ja)]),_meta:ze(A(),qe()).optional()}),CO=Ns.extend({messages:we(OO),modelPreferences:RO.optional(),systemPrompt:A().optional(),includeContext:St(["none","thisServer","allServers"]).optional(),temperature:Re().optional(),maxTokens:Re().int(),stopSequences:we(A()).optional(),metadata:Xe.optional(),tools:we(m_).optional(),toolChoice:PO.optional()}),NO=st.extend({method:J("sampling/createMessage"),params:CO}),Bs=it.extend({model:A(),stopReason:Ze(St(["endTurn","stopSequence","maxTokens"]).or(A())),role:qs,content:IO}),rh=it.extend({model:A(),stopReason:Ze(St(["endTurn","stopSequence","maxTokens","toolUse"]).or(A())),role:qs,content:je([ja,we(ja)])}),zO=H({type:J("boolean"),title:A().optional(),description:A().optional(),default:rt().optional()}),jO=H({type:J("string"),title:A().optional(),description:A().optional(),minLength:Re().optional(),maxLength:Re().optional(),format:St(["email","uri","date","date-time"]).optional(),default:A().optional()}),LO=H({type:St(["number","integer"]),title:A().optional(),description:A().optional(),minimum:Re().optional(),maximum:Re().optional(),default:Re().optional()}),DO=H({type:J("string"),title:A().optional(),description:A().optional(),enum:we(A()),default:A().optional()}),UO=H({type:J("string"),title:A().optional(),description:A().optional(),oneOf:we(H({const:A(),title:A()})),default:A().optional()}),MO=H({type:J("string"),title:A().optional(),description:A().optional(),enum:we(A()),enumNames:we(A()).optional(),default:A().optional()}),qO=je([DO,UO]),ZO=H({type:J("array"),title:A().optional(),description:A().optional(),minItems:Re().optional(),maxItems:Re().optional(),items:H({type:J("string"),enum:we(A())}),default:we(A()).optional()}),BO=H({type:J("array"),title:A().optional(),description:A().optional(),minItems:Re().optional(),maxItems:Re().optional(),items:H({anyOf:we(H({const:A(),title:A()}))}),default:we(A()).optional()}),FO=je([ZO,BO]),HO=je([MO,qO,FO]),VO=je([HO,zO,jO,LO]),KO=Ns.extend({mode:J("form").optional(),message:A(),requestedSchema:H({type:J("object"),properties:ze(A(),VO),required:we(A()).optional()})}),WO=Ns.extend({mode:J("url"),message:A(),elicitationId:A(),url:A().url()}),GO=je([KO,WO]),JO=st.extend({method:J("elicitation/create"),params:GO}),YO=Zt.extend({elicitationId:A()}),XO=Bt.extend({method:J("notifications/elicitation/complete"),params:YO}),Eo=it.extend({action:St(["accept","decline","cancel"]),content:Mp(t=>t===null?void 0:t,ze(A(),je([A(),Re(),rt(),we(A())])).optional())}),QO=H({type:J("ref/resource"),uri:A()}),eC=H({type:J("ref/prompt"),name:A()}),tC=Nt.extend({ref:je([eC,QO]),argument:H({name:A(),value:A()}),context:H({arguments:ze(A(),A()).optional()}).optional()}),rc=st.extend({method:J("completion/complete"),params:tC});rC=it.extend({completion:yt({values:we(A()).max(100),total:Ze(Re().int()),hasMore:Ze(rt())})}),nC=H({uri:A().startsWith("file://"),name:A().optional(),_meta:ze(A(),qe()).optional()}),oC=st.extend({method:J("roots/list"),params:Nt.optional()}),nh=it.extend({roots:we(nC)}),sC=Bt.extend({method:J("notifications/roots/list_changed"),params:Zt.optional()}),cF=je([qa,Kp,rc,th,Qa,Xa,Ga,Ja,Ya,oO,iO,To,ec,Ba,Ha,Va,Wa]),lF=je([Ma,Za,Wp,sC,Ms]),uF=je([Ua,Bs,rh,Eo,nh,Fa,Ka,$o]),dF=je([qa,NO,JO,oC,Ba,Ha,Va,Wa]),pF=je([Ma,Za,TO,cO,rO,kO,bO,Ms,XO]),hF=je([Ua,HI,rC,yO,dO,XI,QI,tO,tc,_O,Fa,Ka,$o]),G=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===ee.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new qp(o.elicitations,r)}return new t(e,r,n)}},qp=class extends G{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(ee.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Qr(t){return t==="completed"||t==="failed"||t==="cancelled"}var b_=O(()=>{});var v_,w_,__,nc=O(()=>{v_=Symbol("Let zodToJsonSchema decide on which parser to use"),w_={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"},__=t=>typeof t=="string"?{...w_,name:t}:{...w_,...t}});var x_,oh=O(()=>{nc();x_=t=>{let e=__(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 sh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ve(t,e,r,n,o){t[e]=r,sh(t,e,n,o)}var en=O(()=>{});var oc,sc=O(()=>{oc=(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 Be(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?oc(e,t.currentPath):e.join("/")}}var Ft=O(()=>{sc()});function k_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==U.ZodAny&&(r.items=ie(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ve(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ve(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ve(r,"minItems",t.exactLength.value,t.exactLength.message,e),ve(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var ih=O(()=>{bs();en();Ge()});function $_(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?ve(r,"minimum",n.value,n.message,e):ve(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ve(r,"maximum",n.value,n.message,e):ve(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",n.value,n.message,e));break;case"multipleOf":ve(r,"multipleOf",n.value,n.message,e);break}return r}var ah=O(()=>{en()});function S_(){return{type:"boolean"}}var ch=O(()=>{});function ic(t,e){return ie(t.type._def,e)}var ac=O(()=>{Ge()});var T_,lh=O(()=>{Ge();T_=(t,e)=>ie(t.innerType._def,e)});function uh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>uh(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 iC(t,e)}}var iC,dh=O(()=>{en();iC=(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":ve(r,"minimum",n.value,n.message,e);break;case"max":ve(r,"maximum",n.value,n.message,e);break}return r}});function E_(t,e){return{...ie(t.innerType._def,e),default:t.defaultValue()}}var ph=O(()=>{Ge()});function R_(t,e){return e.effectStrategy==="input"?ie(t.schema._def,e):Be(e)}var hh=O(()=>{Ge();Ft()});function P_(t){return{type:"string",enum:Array.from(t.values)}}var fh=O(()=>{});function A_(t,e){let r=[ie(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ie(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(aC(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 aC,mh=O(()=>{Ge();aC=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function I_(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 gh=O(()=>{});function cc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ve(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ve(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":tr(r,"email",n.message,e);break;case"format:idn-email":tr(r,"idn-email",n.message,e);break;case"pattern:zod":bt(r,er.email,n.message,e);break}break;case"url":tr(r,"uri",n.message,e);break;case"uuid":tr(r,"uuid",n.message,e);break;case"regex":bt(r,n.regex,n.message,e);break;case"cuid":bt(r,er.cuid,n.message,e);break;case"cuid2":bt(r,er.cuid2,n.message,e);break;case"startsWith":bt(r,RegExp(`^${bh(n.value,e)}`),n.message,e);break;case"endsWith":bt(r,RegExp(`${bh(n.value,e)}$`),n.message,e);break;case"datetime":tr(r,"date-time",n.message,e);break;case"date":tr(r,"date",n.message,e);break;case"time":tr(r,"time",n.message,e);break;case"duration":tr(r,"duration",n.message,e);break;case"length":ve(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ve(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{bt(r,RegExp(bh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&tr(r,"ipv4",n.message,e),n.version!=="v4"&&tr(r,"ipv6",n.message,e);break}case"base64url":bt(r,er.base64url,n.message,e);break;case"jwt":bt(r,er.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&bt(r,er.ipv4Cidr,n.message,e),n.version!=="v4"&&bt(r,er.ipv6Cidr,n.message,e);break}case"emoji":bt(r,er.emoji(),n.message,e);break;case"ulid":{bt(r,er.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{tr(r,"binary",n.message,e);break}case"contentEncoding:base64":{ve(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{bt(r,er.base64,n.message,e);break}}break}case"nanoid":bt(r,er.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function bh(t,e){return e.patternStrategy==="escape"?lC(t):t}function lC(t){let e="";for(let r=0;r<t.length;r++)cC.has(t[r])||(e+="\\"),e+=t[r];return e}function tr(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}}})):ve(t,"format",e,r,n)}function bt(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:O_(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ve(t,"pattern",O_(e,n),r,n)}function O_(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
|
|
1814
1908
|
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
1815
1909
|
]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
|
|
1816
1910
|
`:`[${n[c]}\r
|
|
1817
|
-
]`;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 gh,tr,iC,cc=N(()=>{Xr();tr={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:()=>(gh===void 0&&(gh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gh),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-_]*$/};iC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function lc(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===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:se(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Be(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:se(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=ac(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=sc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var uc=N(()=>{ws();Je();cc();ic();Bt()});function O_(t,e){if(e.mapStrategy==="record")return lc(t,e);let r=se(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Be(e),n=se(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Be(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var bh=N(()=>{Je();uc();Bt()});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 wh=N(()=>{});function N_(t){return t.target==="openAi"?void 0:{not:Be({...t,currentPath:[...t.currentPath,"not"]})}}var vh=N(()=>{Bt()});function z_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var _h=N(()=>{});function L_(t,e){if(e.target==="openApi3")return j_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Hs&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Hs[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 j_(t,e)}var Hs,j_,dc=N(()=>{Je();Hs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};j_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>se(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 D_(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:Hs[t.innerType._def.typeName],nullable:!0}:{type:[Hs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=se(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=se(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var xh=N(()=>{Je();dc()});function U_(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",oh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ve(r,"minimum",n.value,n.message,e):ve(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ve(r,"maximum",n.value,n.message,e):ve(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",n.value,n.message,e));break;case"multipleOf":ve(r,"multipleOf",n.value,n.message,e);break}return r}var kh=N(()=>{Xr()});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=lC(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=se(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=cC(t,e);return i!==void 0&&(n.additionalProperties=i),n}function cC(t,e){if(t.catchall._def.typeName!=="ZodNever")return se(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 lC(t){try{return t.isOptional()}catch{return!0}}var $h=N(()=>{Je()});var q_,Sh=N(()=>{Je();Bt();q_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return se(t.innerType._def,e);let r=se(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Be(e)},r]}:Be(e)}});var Z_,Th=N(()=>{Je();Z_=(t,e)=>{if(e.pipeStrategy==="input")return se(t.in._def,e);if(e.pipeStrategy==="output")return se(t.out._def,e);let r=se(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=se(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 se(t.type._def,e)}var Eh=N(()=>{Je()});function F_(t,e){let n={type:"array",uniqueItems:!0,items:se(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ve(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ve(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Rh=N(()=>{Xr();Je()});function H_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>se(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:se(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>se(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Ph=N(()=>{Je()});function V_(t){return{not:Be(t)}}var Ah=N(()=>{Bt()});function K_(t){return Be(t)}var Ih=N(()=>{Bt()});var G_,Oh=N(()=>{Je();G_=(t,e)=>se(t.innerType._def,e)});var W_,Ch=N(()=>{ws();Bt();sh();ih();ah();ic();ch();uh();dh();ph();hh();fh();mh();bh();wh();vh();_h();xh();kh();$h();Sh();Th();Eh();uc();Rh();cc();Ph();Ah();dc();Ih();Oh();W_=(t,e,r)=>{switch(e){case D.ZodString:return ac(t,r);case D.ZodNumber:return U_(t,r);case D.ZodObject:return M_(t,r);case D.ZodBigInt:return k_(t,r);case D.ZodBoolean:return $_();case D.ZodDate:return lh(t,r);case D.ZodUndefined:return V_(r);case D.ZodNull:return z_(r);case D.ZodArray:return x_(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return L_(t,r);case D.ZodIntersection:return P_(t,r);case D.ZodTuple:return H_(t,r);case D.ZodRecord:return lc(t,r);case D.ZodLiteral:return A_(t,r);case D.ZodEnum:return R_(t);case D.ZodNativeEnum:return C_(t);case D.ZodNullable:return D_(t,r);case D.ZodOptional:return q_(t,r);case D.ZodMap:return O_(t,r);case D.ZodSet:return F_(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return B_(t,r);case D.ZodNaN:case D.ZodNever:return N_(r);case D.ZodEffects:return E_(t,r);case D.ZodAny:return Be(r);case D.ZodUnknown:return K_(r);case D.ZodDefault:return T_(t,r);case D.ZodBranded:return sc(t,r);case D.ZodReadonly:return G_(t,r);case D.ZodCatch:return S_(t,r);case D.ZodPipeline:return Z_(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}}});function se(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==w_)return a}if(n&&!r){let a=uC(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=W_(t,t.typeName,e),i=typeof s=="function"?se(s(),e):s;if(i&&dC(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var uC,dC,Je=N(()=>{rc();Ch();oc();Bt();uC=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:nc(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`),Be(e)):e.$refStrategy==="seen"?Be(e):void 0}},dC=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var J_=N(()=>{});var Nh,zh=N(()=>{Je();nh();Bt();Nh=(t,e)=>{let r=__(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:se(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Be(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=se(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Be(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 Y_=N(()=>{rc();nh();Xr();oc();Je();J_();Bt();sh();ih();ah();ic();ch();uh();dh();ph();hh();fh();mh();bh();wh();vh();_h();xh();kh();$h();Sh();Th();Eh();Oh();uc();Rh();cc();Ph();Ah();dc();Ih();Ch();zh();zh()});function pC(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function jh(t,e){return fr(t)?kp(t,{target:pC(e?.target),io:e?.pipeStrategy??"input"}):Nh(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Lh(t){let r=Jr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ko(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Dh(t,e){let r=Wr(t,e);if(!r.success)throw r.error;return r.data}var Uh=N(()=>{Tp();Os();Y_()});function Q_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function X_(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];Q_(i)&&Q_(s)?r[o]={...i,...s}:r[o]=s}return r}var hC,pc,ex=N(()=>{Os();Po();y_();Uh();hC=6e4,pc=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(Ua,r=>{this._oncancel(r)}),this.setNotificationHandler(qa,r=>{this._onprogress(r)}),this.setRequestHandler(Ma,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Za,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new G(X.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Fa,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 p=c,w=new G(p.error.code,p.error.message,p.error.data);u(w)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} 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 G(X.InvalidParams,`Task not found: ${s}`);if(!Qr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Qr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Yr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ha,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 G(X.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ka,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new G(X.InvalidParams,`Task not found: ${r.params.taskId}`);if(Qr(o.status))throw new G(X.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 G(X.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof G?o:new G(X.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),G.fromError(X.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),js(s)||i_(s)?this._onresponse(s):Bp(s)?this._onrequest(s,i):s_(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=G.fromError(X.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?.[Yr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:X.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));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 p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,w)=>{if(i.signal.aborted)throw new G(X.ConnectionClosed,"Request was cancelled");let m={...w,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let h=m.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,p,m)},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 p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:X.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).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),js(e))n(e);else{let i=new G(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(js(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),js(e))o(e);else{let i=G.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 G?i:new G(X.InternalError,String(i))}}return}let s;try{let i=await this.request(e,So,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new G(X.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Qr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new G(X.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new G(X.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 G?i:new G(X.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 p=P=>{u(P)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(P){p(P);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Yr]:c}});let h=P=>{this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(P)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`)));let z=P instanceof G?P:new G(X.RequestTimeout,String(P));u(z)};this._responseHandlers.set(w,P=>{if(!n?.signal?.aborted){if(P instanceof Error)return u(P);try{let z=Wr(r,P.result);z.success?l(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let b=n?.timeout??hC,k=()=>h(G.fromError(X.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(w,b,n?.maxTotalTimeout,k,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let P=z=>{let V=this._responseHandlers.get(w);V?V(z):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,P),this._enqueueTaskMessage(E,{type:"request",message:m,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(w),u(z)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>{this._cleanupTimeout(w),u(P)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ba,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},Va,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},l_,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||{},[Yr]: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||{},[Yr]: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||{},[Yr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Lh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Dh(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=Lh(e);this._notificationHandlers.set(n,o=>{let s=Dh(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"&&Bp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new G(X.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 G(X.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new G(X.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 G(X.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=qs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Qr(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 G(X.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Qr(a.status))throw new G(X.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=qs.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Qr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Gs=Z(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.regexpCode=Te.getEsmExportName=Te.getProperty=Te.safeStringify=Te.stringify=Te.strConcat=Te.addCodeArg=Te.str=Te._=Te.nil=Te._Code=Te.Name=Te.IDENTIFIER=Te._CodeOrName=void 0;var Vs=class{};Te._CodeOrName=Vs;Te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Dn=class extends Vs{constructor(e){if(super(),!Te.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}}};Te.Name=Dn;var Ft=class extends Vs{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 Dn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Te._Code=Ft;Te.nil=new Ft("");function tx(t,...e){let r=[t[0]],n=0;for(;n<e.length;)qh(r,e[n]),r.push(t[++n]);return new Ft(r)}Te._=tx;var Mh=new Ft("+");function rx(t,...e){let r=[Ks(t[0])],n=0;for(;n<e.length;)r.push(Mh),qh(r,e[n]),r.push(Mh,Ks(t[++n]));return fC(r),new Ft(r)}Te.str=rx;function qh(t,e){e instanceof Ft?t.push(...e._items):e instanceof Dn?t.push(e):t.push(yC(e))}Te.addCodeArg=qh;function fC(t){let e=1;for(;e<t.length-1;){if(t[e]===Mh){let r=mC(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function mC(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Dn||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 Dn))return`"${t}${e.slice(1)}`}function gC(t,e){return e.emptyStr()?t:t.emptyStr()?e:rx`${t}${e}`}Te.strConcat=gC;function yC(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ks(Array.isArray(t)?t.join(","):t)}function bC(t){return new Ft(Ks(t))}Te.stringify=bC;function Ks(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Te.safeStringify=Ks;function wC(t){return typeof t=="string"&&Te.IDENTIFIER.test(t)?new Ft(`.${t}`):tx`[${t}]`}Te.getProperty=wC;function vC(t){if(typeof t=="string"&&Te.IDENTIFIER.test(t))return new Ft(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Te.getEsmExportName=vC;function _C(t){return new Ft(t.toString())}Te.regexpCode=_C});var Fh=Z(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var Tt=Gs(),Zh=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},hc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(hc||(Et.UsedValueState=hc={}));Et.varKinds={const:new Tt.Name("const"),let:new Tt.Name("let"),var:new Tt.Name("var")};var fc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Tt.Name?e:this.name(e)}name(e){return new Tt.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}}};Et.Scope=fc;var mc=class extends Tt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Tt._)`.${new Tt.Name(r)}[${n}]`}};Et.ValueScopeName=mc;var xC=(0,Tt._)`\n`,Bh=class extends fc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?xC:Tt.nil}}get(){return this._scope}name(e){return new mc(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,Tt._)`${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=Tt.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,hc.Started);let u=r(l);if(u){let p=this.opts.es5?Et.varKinds.var:Et.varKinds.const;s=(0,Tt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Tt._)`${s}${u}${this.opts._n}`;else throw new Zh(l);c.set(l,hc.Completed)})}return s}};Et.ValueScope=Bh});var he=Z(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.or=fe.and=fe.not=fe.CodeGen=fe.operators=fe.varKinds=fe.ValueScopeName=fe.ValueScope=fe.Scope=fe.Name=fe.regexpCode=fe.stringify=fe.getProperty=fe.nil=fe.strConcat=fe.str=fe._=void 0;var _e=Gs(),nr=Fh(),en=Gs();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return en._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return en.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return en.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return en.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return en.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return en.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return en.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return en.Name}});var wc=Fh();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return wc.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return wc.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return wc.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return wc.varKinds}});fe.operators={GT:new _e._Code(">"),GTE:new _e._Code(">="),LT:new _e._Code("<"),LTE:new _e._Code("<="),EQ:new _e._Code("==="),NEQ:new _e._Code("!=="),NOT:new _e._Code("!"),OR:new _e._Code("||"),AND:new _e._Code("&&"),ADD:new _e._Code("+")};var Ir=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Hh=class extends Ir{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?nr.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=Io(this.rhs,e,r)),this}get names(){return this.rhs instanceof _e._CodeOrName?this.rhs.names:{}}},gc=class extends Ir{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 _e.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Io(this.rhs,e,r),this}get names(){let e=this.lhs instanceof _e.Name?{}:{...this.lhs.names};return bc(e,this.rhs)}},Vh=class extends gc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Kh=class extends Ir{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Gh=class extends Ir{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Wh=class extends Ir{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Jh=class extends Ir{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=Io(this.code,e,r),this}get names(){return this.code instanceof _e._CodeOrName?this.code.names:{}}},Ws=class extends Ir{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)||(kC(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>qn(e,r.names),{})}},Or=class extends Ws{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Yh=class extends Ws{},Ao=class extends Or{};Ao.kind="else";var Un=class t extends Or{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 Ao(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(nx(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=Io(this.condition,e,r),this}get names(){let e=super.names;return bc(e,this.condition),this.else&&qn(e,this.else.names),e}};Un.kind="if";var Mn=class extends Or{};Mn.kind="for";var Qh=class extends Mn{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=Io(this.iteration,e,r),this}get names(){return qn(super.names,this.iteration.names)}},Xh=class extends Mn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?nr.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=bc(super.names,this.from);return bc(e,this.to)}},yc=class extends Mn{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=Io(this.iterable,e,r),this}get names(){return qn(super.names,this.iterable.names)}},Js=class extends Or{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)}};Js.kind="func";var Ys=class extends Ws{render(e){return"return "+super.render(e)}};Ys.kind="return";var ef=class extends Or{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&&qn(e,this.catch.names),this.finally&&qn(e,this.finally.names),e}},Qs=class extends Or{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Qs.kind="catch";var Xs=class extends Or{render(e){return"finally"+super.render(e)}};Xs.kind="finally";var tf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
1818
|
-
`:""},this._extScope=e,this._scope=new nr.Scope({parent:e}),this._nodes=[new Yh]}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 Hh(e,s,n)),s}const(e,r,n){return this._def(nr.varKinds.const,e,r,n)}let(e,r,n){return this._def(nr.varKinds.let,e,r,n)}var(e,r,n){return this._def(nr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new gc(e,r,n))}add(e,r){return this._leafNode(new Vh(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==_e.nil&&this._leafNode(new Jh(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,_e.addCodeArg)(r,o));return r.push("}"),new _e._Code(r)}if(e,r,n){if(this._blockNode(new Un(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 Un(e))}else(){return this._elseNode(new Ao)}endIf(){return this._endBlockNode(Un,Ao)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Qh(e),r)}forRange(e,r,n,o,s=this.opts.es5?nr.varKinds.var:nr.varKinds.let){let i=this._scope.toName(e);return this._for(new Xh(s,i,r,n),()=>o(i))}forOf(e,r,n,o=nr.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof _e.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,_e._)`${i}.length`,a=>{this.var(s,(0,_e._)`${i}[${a}]`),n(s)})}return this._for(new yc("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?nr.varKinds.var:nr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,_e._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new yc("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Mn)}label(e){return this._leafNode(new Kh(e))}break(e){return this._leafNode(new Gh(e))}return(e){let r=new Ys;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ys)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ef;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Qs(s),r(s)}return n&&(this._currNode=o.finally=new Xs,this.code(n)),this._endBlockNode(Qs,Xs)}throw(e){return this._leafNode(new Wh(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=_e.nil,n,o){return this._blockNode(new Js(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Js)}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 Un))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}};fe.CodeGen=tf;function qn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function bc(t,e){return e instanceof _e._CodeOrName?qn(t,e.names):t}function Io(t,e,r){if(t instanceof _e.Name)return n(t);if(!o(t))return t;return new _e._Code(t._items.reduce((s,i)=>(i instanceof _e.Name&&(i=n(i)),i instanceof _e._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 _e._Code&&s._items.some(i=>i instanceof _e.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function kC(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function nx(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,_e._)`!${rf(t)}`}fe.not=nx;var $C=ox(fe.operators.AND);function SC(...t){return t.reduce($C)}fe.and=SC;var TC=ox(fe.operators.OR);function EC(...t){return t.reduce(TC)}fe.or=EC;function ox(t){return(e,r)=>e===_e.nil?r:r===_e.nil?e:(0,_e._)`${rf(e)} ${t} ${rf(r)}`}function rf(t){return t instanceof _e.Name?t:(0,_e._)`(${t})`}});var $e=Z(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.checkStrictMode=me.getErrorPath=me.Type=me.useFunc=me.setEvaluated=me.evaluatedPropsToName=me.mergeEvaluated=me.eachItem=me.unescapeJsonPointer=me.escapeJsonPointer=me.escapeFragment=me.unescapeFragment=me.schemaRefOrVal=me.schemaHasRulesButRef=me.schemaHasRules=me.checkUnknownRules=me.alwaysValidSchema=me.toHash=void 0;var Oe=he(),RC=Gs();function PC(t){let e={};for(let r of t)e[r]=!0;return e}me.toHash=PC;function AC(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ax(t,e),!cx(e,t.self.RULES.all))}me.alwaysValidSchema=AC;function ax(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]||dx(t,`unknown keyword: "${s}"`)}me.checkUnknownRules=ax;function cx(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}me.schemaHasRules=cx;function IC(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}me.schemaHasRulesButRef=IC;function OC({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Oe._)`${r}`}return(0,Oe._)`${t}${e}${(0,Oe.getProperty)(n)}`}me.schemaRefOrVal=OC;function CC(t){return lx(decodeURIComponent(t))}me.unescapeFragment=CC;function NC(t){return encodeURIComponent(of(t))}me.escapeFragment=NC;function of(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}me.escapeJsonPointer=of;function lx(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}me.unescapeJsonPointer=lx;function zC(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}me.eachItem=zC;function sx({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Oe.Name?(s instanceof Oe.Name?t(o,s,i):e(o,s,i),i):s instanceof Oe.Name?(e(o,i,s),s):r(s,i);return a===Oe.Name&&!(c instanceof Oe.Name)?n(o,c):c}}me.mergeEvaluated={props:sx({mergeNames:(t,e,r)=>t.if((0,Oe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Oe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Oe._)`${r} || {}`).code((0,Oe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Oe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Oe._)`${r} || {}`),sf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:ux}),items:sx({mergeNames:(t,e,r)=>t.if((0,Oe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Oe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Oe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Oe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function ux(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Oe._)`{}`);return e!==void 0&&sf(t,r,e),r}me.evaluatedPropsToName=ux;function sf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Oe._)`${e}${(0,Oe.getProperty)(n)}`,!0))}me.setEvaluated=sf;var ix={};function jC(t,e){return t.scopeValue("func",{ref:e,code:ix[e.code]||(ix[e.code]=new RC._Code(e.code))})}me.useFunc=jC;var nf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(nf||(me.Type=nf={}));function LC(t,e,r){if(t instanceof Oe.Name){let n=e===nf.Num;return r?n?(0,Oe._)`"[" + ${t} + "]"`:(0,Oe._)`"['" + ${t} + "']"`:n?(0,Oe._)`"/" + ${t}`:(0,Oe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Oe.getProperty)(t).toString():"/"+of(t)}me.getErrorPath=LC;function dx(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}me.checkStrictMode=dx});var Cr=Z(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var ut=he(),DC={data:new ut.Name("data"),valCxt:new ut.Name("valCxt"),instancePath:new ut.Name("instancePath"),parentData:new ut.Name("parentData"),parentDataProperty:new ut.Name("parentDataProperty"),rootData:new ut.Name("rootData"),dynamicAnchors:new ut.Name("dynamicAnchors"),vErrors:new ut.Name("vErrors"),errors:new ut.Name("errors"),this:new ut.Name("this"),self:new ut.Name("self"),scope:new ut.Name("scope"),json:new ut.Name("json"),jsonPos:new ut.Name("jsonPos"),jsonLen:new ut.Name("jsonLen"),jsonPart:new ut.Name("jsonPart")};af.default=DC});var ei=Z(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.extendErrors=dt.resetErrorsCount=dt.reportExtraError=dt.reportError=dt.keyword$DataError=dt.keywordError=void 0;var Se=he(),vc=$e(),bt=Cr();dt.keywordError={message:({keyword:t})=>(0,Se.str)`must pass "${t}" keyword validation`};dt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Se.str)`"${t}" keyword must be ${e} ($data)`:(0,Se.str)`"${t}" keyword is invalid ($data)`};function UC(t,e=dt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=fx(t,e,r);n??(i||a)?px(s,c):hx(o,(0,Se._)`[${c}]`)}dt.reportError=UC;function MC(t,e=dt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=fx(t,e,r);px(o,a),s||i||hx(n,bt.default.vErrors)}dt.reportExtraError=MC;function qC(t,e){t.assign(bt.default.errors,e),t.if((0,Se._)`${bt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Se._)`${bt.default.vErrors}.length`,e),()=>t.assign(bt.default.vErrors,null)))}dt.resetErrorsCount=qC;function ZC({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,bt.default.errors,a=>{t.const(i,(0,Se._)`${bt.default.vErrors}[${a}]`),t.if((0,Se._)`${i}.instancePath === undefined`,()=>t.assign((0,Se._)`${i}.instancePath`,(0,Se.strConcat)(bt.default.instancePath,s.errorPath))),t.assign((0,Se._)`${i}.schemaPath`,(0,Se.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Se._)`${i}.schema`,r),t.assign((0,Se._)`${i}.data`,n))})}dt.extendErrors=ZC;function px(t,e){let r=t.const("err",e);t.if((0,Se._)`${bt.default.vErrors} === null`,()=>t.assign(bt.default.vErrors,(0,Se._)`[${r}]`),(0,Se._)`${bt.default.vErrors}.push(${r})`),t.code((0,Se._)`${bt.default.errors}++`)}function hx(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Se._)`new ${t.ValidationError}(${e})`):(r.assign((0,Se._)`${n}.errors`,e),r.return(!1))}var Zn={keyword:new Se.Name("keyword"),schemaPath:new Se.Name("schemaPath"),params:new Se.Name("params"),propertyName:new Se.Name("propertyName"),message:new Se.Name("message"),schema:new Se.Name("schema"),parentSchema:new Se.Name("parentSchema")};function fx(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Se._)`{}`:BC(t,e,r)}function BC(t,e,r={}){let{gen:n,it:o}=t,s=[FC(o,r),HC(t,r)];return VC(t,e,s),n.object(...s)}function FC({errorPath:t},{instancePath:e}){let r=e?(0,Se.str)`${t}${(0,vc.getErrorPath)(e,vc.Type.Str)}`:t;return[bt.default.instancePath,(0,Se.strConcat)(bt.default.instancePath,r)]}function HC({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Se.str)`${e}/${t}`;return r&&(o=(0,Se.str)`${o}${(0,vc.getErrorPath)(r,vc.Type.Str)}`),[Zn.schemaPath,o]}function VC(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:p}=a;n.push([Zn.keyword,o],[Zn.params,typeof e=="function"?e(t):e||(0,Se._)`{}`]),c.messages&&n.push([Zn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Zn.schema,i],[Zn.parentSchema,(0,Se._)`${u}${p}`],[bt.default.data,s]),l&&n.push([Zn.propertyName,l])}});var gx=Z(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.boolOrEmptySchema=Oo.topBoolOrEmptySchema=void 0;var KC=ei(),GC=he(),WC=Cr(),JC={message:"boolean schema is false"};function YC(t){let{gen:e,schema:r,validateName:n}=t;r===!1?mx(t,!1):typeof r=="object"&&r.$async===!0?e.return(WC.default.data):(e.assign((0,GC._)`${n}.errors`,null),e.return(!0))}Oo.topBoolOrEmptySchema=YC;function QC(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),mx(t)):r.var(e,!0)}Oo.boolOrEmptySchema=QC;function mx(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,KC.reportError)(o,JC,void 0,e)}});var cf=Z(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.getRules=Co.isJSONType=void 0;var XC=["string","number","integer","boolean","null","object","array"],eN=new Set(XC);function tN(t){return typeof t=="string"&&eN.has(t)}Co.isJSONType=tN;function rN(){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:{}}}Co.getRules=rN});var lf=Z(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.shouldUseRule=tn.shouldUseGroup=tn.schemaHasRulesForType=void 0;function nN({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&yx(t,n)}tn.schemaHasRulesForType=nN;function yx(t,e){return e.rules.some(r=>bx(t,r))}tn.shouldUseGroup=yx;function bx(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))}tn.shouldUseRule=bx});var ti=Z(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.reportTypeError=pt.checkDataTypes=pt.checkDataType=pt.coerceAndCheckDataType=pt.getJSONTypes=pt.getSchemaTypes=pt.DataType=void 0;var oN=cf(),sN=lf(),iN=ei(),ue=he(),wx=$e(),No;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(No||(pt.DataType=No={}));function aN(t){let e=vx(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}pt.getSchemaTypes=aN;function vx(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(oN.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}pt.getJSONTypes=vx;function cN(t,e){let{gen:r,data:n,opts:o}=t,s=lN(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,sN.schemaHasRulesForType)(t,e[0]));if(i){let a=df(e,n,o.strictNumbers,No.Wrong);r.if(a,()=>{s.length?uN(t,e,s):pf(t)})}return i}pt.coerceAndCheckDataType=cN;var _x=new Set(["string","number","integer","boolean","null"]);function lN(t,e){return e?t.filter(r=>_x.has(r)||e==="array"&&r==="array"):[]}function uN(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,ue._)`typeof ${o}`),a=n.let("coerced",(0,ue._)`undefined`);s.coerceTypes==="array"&&n.if((0,ue._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,ue._)`${o}[0]`).assign(i,(0,ue._)`typeof ${o}`).if(df(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ue._)`${a} !== undefined`);for(let l of r)(_x.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),pf(t),n.endIf(),n.if((0,ue._)`${a} !== undefined`,()=>{n.assign(o,a),dN(t,a)});function c(l){switch(l){case"string":n.elseIf((0,ue._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ue._)`"" + ${o}`).elseIf((0,ue._)`${o} === null`).assign(a,(0,ue._)`""`);return;case"number":n.elseIf((0,ue._)`${i} == "boolean" || ${o} === null
|
|
1911
|
+
]`;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 yh,er,cC,lc=O(()=>{en();er={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:()=>(yh===void 0&&(yh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),yh),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-_]*$/};cC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function uc(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===U.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Be(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===U.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=cc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===U.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===U.ZodBranded&&t.keyType._def.type._def.typeName===U.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ic(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var dc=O(()=>{bs();Ge();lc();ac();Ft()});function C_(t,e){if(e.mapStrategy==="record")return uc(t,e);let r=ie(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Be(e),n=ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Be(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var wh=O(()=>{Ge();dc();Ft()});function N_(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 vh=O(()=>{});function z_(t){return t.target==="openAi"?void 0:{not:Be({...t,currentPath:[...t.currentPath,"not"]})}}var _h=O(()=>{Ft()});function j_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var xh=O(()=>{});function D_(t,e){if(e.target==="openApi3")return L_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Fs&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Fs[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 L_(t,e)}var Fs,L_,pc=O(()=>{Ge();Fs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};L_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ie(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 U_(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:Fs[t.innerType._def.typeName],nullable:!0}:{type:[Fs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ie(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ie(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var kh=O(()=>{Ge();pc()});function M_(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",sh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ve(r,"minimum",n.value,n.message,e):ve(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ve(r,"maximum",n.value,n.message,e):ve(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",n.value,n.message,e));break;case"multipleOf":ve(r,"multipleOf",n.value,n.message,e);break}return r}var $h=O(()=>{en()});function q_(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=dC(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ie(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=uC(t,e);return i!==void 0&&(n.additionalProperties=i),n}function uC(t,e){if(t.catchall._def.typeName!=="ZodNever")return ie(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 dC(t){try{return t.isOptional()}catch{return!0}}var Sh=O(()=>{Ge()});var Z_,Th=O(()=>{Ge();Ft();Z_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ie(t.innerType._def,e);let r=ie(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Be(e)},r]}:Be(e)}});var B_,Eh=O(()=>{Ge();B_=(t,e)=>{if(e.pipeStrategy==="input")return ie(t.in._def,e);if(e.pipeStrategy==="output")return ie(t.out._def,e);let r=ie(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ie(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function F_(t,e){return ie(t.type._def,e)}var Rh=O(()=>{Ge()});function H_(t,e){let n={type:"array",uniqueItems:!0,items:ie(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ve(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ve(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Ph=O(()=>{en();Ge()});function V_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ie(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ie(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ie(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Ah=O(()=>{Ge()});function K_(t){return{not:Be(t)}}var Ih=O(()=>{Ft()});function W_(t){return Be(t)}var Oh=O(()=>{Ft()});var G_,Ch=O(()=>{Ge();G_=(t,e)=>ie(t.innerType._def,e)});var J_,Nh=O(()=>{bs();Ft();ih();ah();ch();ac();lh();dh();ph();hh();fh();mh();gh();wh();vh();_h();xh();kh();$h();Sh();Th();Eh();Rh();dc();Ph();lc();Ah();Ih();pc();Oh();Ch();J_=(t,e,r)=>{switch(e){case U.ZodString:return cc(t,r);case U.ZodNumber:return M_(t,r);case U.ZodObject:return q_(t,r);case U.ZodBigInt:return $_(t,r);case U.ZodBoolean:return S_();case U.ZodDate:return uh(t,r);case U.ZodUndefined:return K_(r);case U.ZodNull:return j_(r);case U.ZodArray:return k_(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return D_(t,r);case U.ZodIntersection:return A_(t,r);case U.ZodTuple:return V_(t,r);case U.ZodRecord:return uc(t,r);case U.ZodLiteral:return I_(t,r);case U.ZodEnum:return P_(t);case U.ZodNativeEnum:return N_(t);case U.ZodNullable:return U_(t,r);case U.ZodOptional:return Z_(t,r);case U.ZodMap:return C_(t,r);case U.ZodSet:return H_(t,r);case U.ZodLazy:return()=>t.getter()._def;case U.ZodPromise:return F_(t,r);case U.ZodNaN:case U.ZodNever:return z_(r);case U.ZodEffects:return R_(t,r);case U.ZodAny:return Be(r);case U.ZodUnknown:return W_(r);case U.ZodDefault:return E_(t,r);case U.ZodBranded:return ic(t,r);case U.ZodReadonly:return G_(t,r);case U.ZodCatch:return T_(t,r);case U.ZodPipeline:return B_(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(n=>{})(e)}}});function ie(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=pC(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=J_(t,t.typeName,e),i=typeof s=="function"?ie(s(),e):s;if(i&&hC(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var pC,hC,Ge=O(()=>{nc();Nh();sc();Ft();pC=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:oc(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`),Be(e)):e.$refStrategy==="seen"?Be(e):void 0}},hC=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var Y_=O(()=>{});var zh,jh=O(()=>{Ge();oh();Ft();zh=(t,e)=>{let r=x_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ie(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Be(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ie(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Be(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 X_=O(()=>{nc();oh();en();sc();Ge();Y_();Ft();ih();ah();ch();ac();lh();dh();ph();hh();fh();mh();gh();wh();vh();_h();xh();kh();$h();Sh();Th();Eh();Rh();Ch();dc();Ph();lc();Ah();Ih();pc();Oh();Nh();jh();jh()});function fC(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Lh(t,e){return hr(t)?$p(t,{target:fC(e?.target),io:e?.pipeStrategy??"input"}):zh(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Dh(t){let r=Yr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=xo(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Uh(t,e){let r=Jr(t,e);if(!r.success)throw r.error;return r.data}var Mh=O(()=>{Ep();Is();X_()});function Q_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ex(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];Q_(i)&&Q_(s)?r[o]={...i,...s}:r[o]=s}return r}var mC,hc,tx=O(()=>{Is();Ro();b_();Mh();mC=6e4,hc=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(Ma,r=>{this._oncancel(r)}),this.setNotificationHandler(Za,r=>{this._onprogress(r)}),this.setRequestHandler(qa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ba,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new G(ee.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ha,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 p=c,w=new G(p.error.code,p.error.message,p.error.data);u(w)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} 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 G(ee.InvalidParams,`Task not found: ${s}`);if(!Qr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Qr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Xr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Va,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 G(ee.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 G(ee.InvalidParams,`Task not found: ${r.params.taskId}`);if(Qr(o.status))throw new G(ee.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 G(ee.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof G?o:new G(ee.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),G.fromError(ee.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),zs(s)||a_(s)?this._onresponse(s):Fp(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=G.fromError(ee.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?.[Xr]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:ee.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=n_(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 p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,w)=>{if(i.signal.aborted)throw new G(ee.ConnectionClosed,"Request was cancelled");let m={...w,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let h=m.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,p,m)},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 p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:ee.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).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),zs(e))n(e);else{let i=new G(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(zs(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),zs(e))o(e);else{let i=G.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 G?i:new G(ee.InternalError,String(i))}}return}let s;try{let i=await this.request(e,$o,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new G(ee.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Qr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new G(ee.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new G(ee.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 G?i:new G(ee.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 p=P=>{u(P)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(P){p(P);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Xr]:c}});let h=P=>{this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(P)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`)));let z=P instanceof G?P:new G(ee.RequestTimeout,String(P));u(z)};this._responseHandlers.set(w,P=>{if(!n?.signal?.aborted){if(P instanceof Error)return u(P);try{let z=Jr(r,P.result);z.success?l(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let b=n?.timeout??mC,$=()=>h(G.fromError(ee.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(w,b,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let P=z=>{let V=this._responseHandlers.get(w);V?V(z):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,P),this._enqueueTaskMessage(E,{type:"request",message:m,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(w),u(z)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>{this._cleanupTimeout(w),u(P)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Fa,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},Ka,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},u_,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||{},[Xr]: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||{},[Xr]: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||{},[Xr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Dh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Uh(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=Dh(e);this._notificationHandlers.set(n,o=>{let s=Uh(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"&&Fp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new G(ee.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 G(ee.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new G(ee.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 G(ee.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=Ms.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Qr(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 G(ee.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Qr(a.status))throw new G(ee.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=Ms.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Qr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Ks=Z(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.regexpCode=Te.getEsmExportName=Te.getProperty=Te.safeStringify=Te.stringify=Te.strConcat=Te.addCodeArg=Te.str=Te._=Te.nil=Te._Code=Te.Name=Te.IDENTIFIER=Te._CodeOrName=void 0;var Hs=class{};Te._CodeOrName=Hs;Te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ln=class extends Hs{constructor(e){if(super(),!Te.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}}};Te.Name=Ln;var Ht=class extends Hs{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 Ln&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Te._Code=Ht;Te.nil=new Ht("");function rx(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Zh(r,e[n]),r.push(t[++n]);return new Ht(r)}Te._=rx;var qh=new Ht("+");function nx(t,...e){let r=[Vs(t[0])],n=0;for(;n<e.length;)r.push(qh),Zh(r,e[n]),r.push(qh,Vs(t[++n]));return gC(r),new Ht(r)}Te.str=nx;function Zh(t,e){e instanceof Ht?t.push(...e._items):e instanceof Ln?t.push(e):t.push(wC(e))}Te.addCodeArg=Zh;function gC(t){let e=1;for(;e<t.length-1;){if(t[e]===qh){let r=yC(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function yC(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ln||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 Ln))return`"${t}${e.slice(1)}`}function bC(t,e){return e.emptyStr()?t:t.emptyStr()?e:nx`${t}${e}`}Te.strConcat=bC;function wC(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Vs(Array.isArray(t)?t.join(","):t)}function vC(t){return new Ht(Vs(t))}Te.stringify=vC;function Vs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Te.safeStringify=Vs;function _C(t){return typeof t=="string"&&Te.IDENTIFIER.test(t)?new Ht(`.${t}`):rx`[${t}]`}Te.getProperty=_C;function xC(t){if(typeof t=="string"&&Te.IDENTIFIER.test(t))return new Ht(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Te.getEsmExportName=xC;function kC(t){return new Ht(t.toString())}Te.regexpCode=kC});var Hh=Z(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var Tt=Ks(),Bh=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},fc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(fc||(Et.UsedValueState=fc={}));Et.varKinds={const:new Tt.Name("const"),let:new Tt.Name("let"),var:new Tt.Name("var")};var mc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Tt.Name?e:this.name(e)}name(e){return new Tt.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}}};Et.Scope=mc;var gc=class extends Tt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Tt._)`.${new Tt.Name(r)}[${n}]`}};Et.ValueScopeName=gc;var $C=(0,Tt._)`\n`,Fh=class extends mc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?$C:Tt.nil}}get(){return this._scope}name(e){return new gc(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,Tt._)`${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=Tt.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,fc.Started);let u=r(l);if(u){let p=this.opts.es5?Et.varKinds.var:Et.varKinds.const;s=(0,Tt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Tt._)`${s}${u}${this.opts._n}`;else throw new Bh(l);c.set(l,fc.Completed)})}return s}};Et.ValueScope=Fh});var he=Z(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.or=fe.and=fe.not=fe.CodeGen=fe.operators=fe.varKinds=fe.ValueScopeName=fe.ValueScope=fe.Scope=fe.Name=fe.regexpCode=fe.stringify=fe.getProperty=fe.nil=fe.strConcat=fe.str=fe._=void 0;var _e=Ks(),rr=Hh(),tn=Ks();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return tn._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return tn.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return tn.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return tn.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return tn.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return tn.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return tn.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return tn.Name}});var vc=Hh();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return vc.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return vc.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return vc.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return vc.varKinds}});fe.operators={GT:new _e._Code(">"),GTE:new _e._Code(">="),LT:new _e._Code("<"),LTE:new _e._Code("<="),EQ:new _e._Code("==="),NEQ:new _e._Code("!=="),NOT:new _e._Code("!"),OR:new _e._Code("||"),AND:new _e._Code("&&"),ADD:new _e._Code("+")};var Ar=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Vh=class extends Ar{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?rr.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=Ao(this.rhs,e,r)),this}get names(){return this.rhs instanceof _e._CodeOrName?this.rhs.names:{}}},yc=class extends Ar{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 _e.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ao(this.rhs,e,r),this}get names(){let e=this.lhs instanceof _e.Name?{}:{...this.lhs.names};return wc(e,this.rhs)}},Kh=class extends yc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wh=class extends Ar{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Gh=class extends Ar{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Jh=class extends Ar{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Yh=class extends Ar{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=Ao(this.code,e,r),this}get names(){return this.code instanceof _e._CodeOrName?this.code.names:{}}},Ws=class extends Ar{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)||(SC(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Mn(e,r.names),{})}},Ir=class extends Ws{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Xh=class extends Ws{},Po=class extends Ir{};Po.kind="else";var Dn=class t extends Ir{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 Po(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(ox(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=Ao(this.condition,e,r),this}get names(){let e=super.names;return wc(e,this.condition),this.else&&Mn(e,this.else.names),e}};Dn.kind="if";var Un=class extends Ir{};Un.kind="for";var Qh=class extends Un{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=Ao(this.iteration,e,r),this}get names(){return Mn(super.names,this.iteration.names)}},ef=class extends Un{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?rr.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=wc(super.names,this.from);return wc(e,this.to)}},bc=class extends Un{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=Ao(this.iterable,e,r),this}get names(){return Mn(super.names,this.iterable.names)}},Gs=class extends Ir{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)}};Gs.kind="func";var Js=class extends Ws{render(e){return"return "+super.render(e)}};Js.kind="return";var tf=class extends Ir{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&&Mn(e,this.catch.names),this.finally&&Mn(e,this.finally.names),e}},Ys=class extends Ir{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ys.kind="catch";var Xs=class extends Ir{render(e){return"finally"+super.render(e)}};Xs.kind="finally";var rf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
1912
|
+
`:""},this._extScope=e,this._scope=new rr.Scope({parent:e}),this._nodes=[new Xh]}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 Vh(e,s,n)),s}const(e,r,n){return this._def(rr.varKinds.const,e,r,n)}let(e,r,n){return this._def(rr.varKinds.let,e,r,n)}var(e,r,n){return this._def(rr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new yc(e,r,n))}add(e,r){return this._leafNode(new Kh(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==_e.nil&&this._leafNode(new Yh(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,_e.addCodeArg)(r,o));return r.push("}"),new _e._Code(r)}if(e,r,n){if(this._blockNode(new Dn(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 Dn(e))}else(){return this._elseNode(new Po)}endIf(){return this._endBlockNode(Dn,Po)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Qh(e),r)}forRange(e,r,n,o,s=this.opts.es5?rr.varKinds.var:rr.varKinds.let){let i=this._scope.toName(e);return this._for(new ef(s,i,r,n),()=>o(i))}forOf(e,r,n,o=rr.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof _e.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,_e._)`${i}.length`,a=>{this.var(s,(0,_e._)`${i}[${a}]`),n(s)})}return this._for(new bc("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?rr.varKinds.var:rr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,_e._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new bc("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Un)}label(e){return this._leafNode(new Wh(e))}break(e){return this._leafNode(new Gh(e))}return(e){let r=new Js;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Js)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new tf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Ys(s),r(s)}return n&&(this._currNode=o.finally=new Xs,this.code(n)),this._endBlockNode(Ys,Xs)}throw(e){return this._leafNode(new Jh(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=_e.nil,n,o){return this._blockNode(new Gs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Gs)}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 Dn))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}};fe.CodeGen=rf;function Mn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function wc(t,e){return e instanceof _e._CodeOrName?Mn(t,e.names):t}function Ao(t,e,r){if(t instanceof _e.Name)return n(t);if(!o(t))return t;return new _e._Code(t._items.reduce((s,i)=>(i instanceof _e.Name&&(i=n(i)),i instanceof _e._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 _e._Code&&s._items.some(i=>i instanceof _e.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function SC(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function ox(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,_e._)`!${nf(t)}`}fe.not=ox;var TC=sx(fe.operators.AND);function EC(...t){return t.reduce(TC)}fe.and=EC;var RC=sx(fe.operators.OR);function PC(...t){return t.reduce(RC)}fe.or=PC;function sx(t){return(e,r)=>e===_e.nil?r:r===_e.nil?e:(0,_e._)`${nf(e)} ${t} ${nf(r)}`}function nf(t){return t instanceof _e.Name?t:(0,_e._)`(${t})`}});var $e=Z(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.checkStrictMode=me.getErrorPath=me.Type=me.useFunc=me.setEvaluated=me.evaluatedPropsToName=me.mergeEvaluated=me.eachItem=me.unescapeJsonPointer=me.escapeJsonPointer=me.escapeFragment=me.unescapeFragment=me.schemaRefOrVal=me.schemaHasRulesButRef=me.schemaHasRules=me.checkUnknownRules=me.alwaysValidSchema=me.toHash=void 0;var Oe=he(),AC=Ks();function IC(t){let e={};for(let r of t)e[r]=!0;return e}me.toHash=IC;function OC(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(cx(t,e),!lx(e,t.self.RULES.all))}me.alwaysValidSchema=OC;function cx(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]||px(t,`unknown keyword: "${s}"`)}me.checkUnknownRules=cx;function lx(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}me.schemaHasRules=lx;function CC(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}me.schemaHasRulesButRef=CC;function NC({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Oe._)`${r}`}return(0,Oe._)`${t}${e}${(0,Oe.getProperty)(n)}`}me.schemaRefOrVal=NC;function zC(t){return ux(decodeURIComponent(t))}me.unescapeFragment=zC;function jC(t){return encodeURIComponent(sf(t))}me.escapeFragment=jC;function sf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}me.escapeJsonPointer=sf;function ux(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}me.unescapeJsonPointer=ux;function LC(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}me.eachItem=LC;function ix({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Oe.Name?(s instanceof Oe.Name?t(o,s,i):e(o,s,i),i):s instanceof Oe.Name?(e(o,i,s),s):r(s,i);return a===Oe.Name&&!(c instanceof Oe.Name)?n(o,c):c}}me.mergeEvaluated={props:ix({mergeNames:(t,e,r)=>t.if((0,Oe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Oe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Oe._)`${r} || {}`).code((0,Oe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Oe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Oe._)`${r} || {}`),af(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:dx}),items:ix({mergeNames:(t,e,r)=>t.if((0,Oe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Oe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Oe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Oe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function dx(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Oe._)`{}`);return e!==void 0&&af(t,r,e),r}me.evaluatedPropsToName=dx;function af(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Oe._)`${e}${(0,Oe.getProperty)(n)}`,!0))}me.setEvaluated=af;var ax={};function DC(t,e){return t.scopeValue("func",{ref:e,code:ax[e.code]||(ax[e.code]=new AC._Code(e.code))})}me.useFunc=DC;var of;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(of||(me.Type=of={}));function UC(t,e,r){if(t instanceof Oe.Name){let n=e===of.Num;return r?n?(0,Oe._)`"[" + ${t} + "]"`:(0,Oe._)`"['" + ${t} + "']"`:n?(0,Oe._)`"/" + ${t}`:(0,Oe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Oe.getProperty)(t).toString():"/"+sf(t)}me.getErrorPath=UC;function px(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}me.checkStrictMode=px});var Or=Z(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var ut=he(),MC={data:new ut.Name("data"),valCxt:new ut.Name("valCxt"),instancePath:new ut.Name("instancePath"),parentData:new ut.Name("parentData"),parentDataProperty:new ut.Name("parentDataProperty"),rootData:new ut.Name("rootData"),dynamicAnchors:new ut.Name("dynamicAnchors"),vErrors:new ut.Name("vErrors"),errors:new ut.Name("errors"),this:new ut.Name("this"),self:new ut.Name("self"),scope:new ut.Name("scope"),json:new ut.Name("json"),jsonPos:new ut.Name("jsonPos"),jsonLen:new ut.Name("jsonLen"),jsonPart:new ut.Name("jsonPart")};cf.default=MC});var Qs=Z(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.extendErrors=dt.resetErrorsCount=dt.reportExtraError=dt.reportError=dt.keyword$DataError=dt.keywordError=void 0;var Se=he(),_c=$e(),wt=Or();dt.keywordError={message:({keyword:t})=>(0,Se.str)`must pass "${t}" keyword validation`};dt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Se.str)`"${t}" keyword must be ${e} ($data)`:(0,Se.str)`"${t}" keyword is invalid ($data)`};function qC(t,e=dt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=mx(t,e,r);n??(i||a)?hx(s,c):fx(o,(0,Se._)`[${c}]`)}dt.reportError=qC;function ZC(t,e=dt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=mx(t,e,r);hx(o,a),s||i||fx(n,wt.default.vErrors)}dt.reportExtraError=ZC;function BC(t,e){t.assign(wt.default.errors,e),t.if((0,Se._)`${wt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Se._)`${wt.default.vErrors}.length`,e),()=>t.assign(wt.default.vErrors,null)))}dt.resetErrorsCount=BC;function FC({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,wt.default.errors,a=>{t.const(i,(0,Se._)`${wt.default.vErrors}[${a}]`),t.if((0,Se._)`${i}.instancePath === undefined`,()=>t.assign((0,Se._)`${i}.instancePath`,(0,Se.strConcat)(wt.default.instancePath,s.errorPath))),t.assign((0,Se._)`${i}.schemaPath`,(0,Se.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Se._)`${i}.schema`,r),t.assign((0,Se._)`${i}.data`,n))})}dt.extendErrors=FC;function hx(t,e){let r=t.const("err",e);t.if((0,Se._)`${wt.default.vErrors} === null`,()=>t.assign(wt.default.vErrors,(0,Se._)`[${r}]`),(0,Se._)`${wt.default.vErrors}.push(${r})`),t.code((0,Se._)`${wt.default.errors}++`)}function fx(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Se._)`new ${t.ValidationError}(${e})`):(r.assign((0,Se._)`${n}.errors`,e),r.return(!1))}var qn={keyword:new Se.Name("keyword"),schemaPath:new Se.Name("schemaPath"),params:new Se.Name("params"),propertyName:new Se.Name("propertyName"),message:new Se.Name("message"),schema:new Se.Name("schema"),parentSchema:new Se.Name("parentSchema")};function mx(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Se._)`{}`:HC(t,e,r)}function HC(t,e,r={}){let{gen:n,it:o}=t,s=[VC(o,r),KC(t,r)];return WC(t,e,s),n.object(...s)}function VC({errorPath:t},{instancePath:e}){let r=e?(0,Se.str)`${t}${(0,_c.getErrorPath)(e,_c.Type.Str)}`:t;return[wt.default.instancePath,(0,Se.strConcat)(wt.default.instancePath,r)]}function KC({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Se.str)`${e}/${t}`;return r&&(o=(0,Se.str)`${o}${(0,_c.getErrorPath)(r,_c.Type.Str)}`),[qn.schemaPath,o]}function WC(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:p}=a;n.push([qn.keyword,o],[qn.params,typeof e=="function"?e(t):e||(0,Se._)`{}`]),c.messages&&n.push([qn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([qn.schema,i],[qn.parentSchema,(0,Se._)`${u}${p}`],[wt.default.data,s]),l&&n.push([qn.propertyName,l])}});var yx=Z(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.boolOrEmptySchema=Io.topBoolOrEmptySchema=void 0;var GC=Qs(),JC=he(),YC=Or(),XC={message:"boolean schema is false"};function QC(t){let{gen:e,schema:r,validateName:n}=t;r===!1?gx(t,!1):typeof r=="object"&&r.$async===!0?e.return(YC.default.data):(e.assign((0,JC._)`${n}.errors`,null),e.return(!0))}Io.topBoolOrEmptySchema=QC;function eN(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),gx(t)):r.var(e,!0)}Io.boolOrEmptySchema=eN;function gx(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,GC.reportError)(o,XC,void 0,e)}});var lf=Z(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.getRules=Oo.isJSONType=void 0;var tN=["string","number","integer","boolean","null","object","array"],rN=new Set(tN);function nN(t){return typeof t=="string"&&rN.has(t)}Oo.isJSONType=nN;function oN(){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:{}}}Oo.getRules=oN});var uf=Z(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.shouldUseRule=rn.shouldUseGroup=rn.schemaHasRulesForType=void 0;function sN({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&bx(t,n)}rn.schemaHasRulesForType=sN;function bx(t,e){return e.rules.some(r=>wx(t,r))}rn.shouldUseGroup=bx;function wx(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))}rn.shouldUseRule=wx});var ei=Z(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.reportTypeError=pt.checkDataTypes=pt.checkDataType=pt.coerceAndCheckDataType=pt.getJSONTypes=pt.getSchemaTypes=pt.DataType=void 0;var iN=lf(),aN=uf(),cN=Qs(),ue=he(),vx=$e(),Co;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Co||(pt.DataType=Co={}));function lN(t){let e=_x(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}pt.getSchemaTypes=lN;function _x(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(iN.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}pt.getJSONTypes=_x;function uN(t,e){let{gen:r,data:n,opts:o}=t,s=dN(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,aN.schemaHasRulesForType)(t,e[0]));if(i){let a=pf(e,n,o.strictNumbers,Co.Wrong);r.if(a,()=>{s.length?pN(t,e,s):hf(t)})}return i}pt.coerceAndCheckDataType=uN;var xx=new Set(["string","number","integer","boolean","null"]);function dN(t,e){return e?t.filter(r=>xx.has(r)||e==="array"&&r==="array"):[]}function pN(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,ue._)`typeof ${o}`),a=n.let("coerced",(0,ue._)`undefined`);s.coerceTypes==="array"&&n.if((0,ue._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,ue._)`${o}[0]`).assign(i,(0,ue._)`typeof ${o}`).if(pf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ue._)`${a} !== undefined`);for(let l of r)(xx.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),hf(t),n.endIf(),n.if((0,ue._)`${a} !== undefined`,()=>{n.assign(o,a),hN(t,a)});function c(l){switch(l){case"string":n.elseIf((0,ue._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ue._)`"" + ${o}`).elseIf((0,ue._)`${o} === null`).assign(a,(0,ue._)`""`);return;case"number":n.elseIf((0,ue._)`${i} == "boolean" || ${o} === null
|
|
1819
1913
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ue._)`+${o}`);return;case"integer":n.elseIf((0,ue._)`${i} === "boolean" || ${o} === null
|
|
1820
1914
|
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ue._)`+${o}`);return;case"boolean":n.elseIf((0,ue._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ue._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ue._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ue._)`${i} === "string" || ${i} === "number"
|
|
1821
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,ue._)`[${o}]`)}}}function dN({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ue._)`${e} !== undefined`,()=>t.assign((0,ue._)`${e}[${r}]`,n))}function uf(t,e,r,n=No.Correct){let o=n===No.Correct?ue.operators.EQ:ue.operators.NEQ,s;switch(t){case"null":return(0,ue._)`${e} ${o} null`;case"array":s=(0,ue._)`Array.isArray(${e})`;break;case"object":s=(0,ue._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ue._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ue._)`typeof ${e} ${o} ${t}`}return n===No.Correct?s:(0,ue.not)(s);function i(a=ue.nil){return(0,ue.and)((0,ue._)`typeof ${e} == "number"`,a,r?(0,ue._)`isFinite(${e})`:ue.nil)}}pt.checkDataType=uf;function df(t,e,r,n){if(t.length===1)return uf(t[0],e,r,n);let o,s=(0,wx.toHash)(t);if(s.array&&s.object){let i=(0,ue._)`typeof ${e} != "object"`;o=s.null?i:(0,ue._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ue.nil;s.number&&delete s.integer;for(let i in s)o=(0,ue.and)(o,uf(i,e,r,n));return o}pt.checkDataTypes=df;var pN={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ue._)`{type: ${t}}`:(0,ue._)`{type: ${e}}`};function pf(t){let e=hN(t);(0,iN.reportError)(e,pN)}pt.reportTypeError=pf;function hN(t){let{gen:e,data:r,schema:n}=t,o=(0,wx.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var kx=Z(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.assignDefaults=void 0;var zo=he(),fN=$e();function mN(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)xx(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>xx(t,s,o.default))}_c.assignDefaults=mN;function xx(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,zo._)`${s}${(0,zo.getProperty)(e)}`;if(o){(0,fN.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,zo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,zo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,zo._)`${a} = ${(0,zo.stringify)(r)}`)}});var Ht=Z(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.validateUnion=Ae.validateArray=Ae.usePattern=Ae.callValidateCode=Ae.schemaProperties=Ae.allSchemaProperties=Ae.noPropertyInData=Ae.propertyInData=Ae.isOwnProperty=Ae.hasPropFunc=Ae.reportMissingProp=Ae.checkMissingProp=Ae.checkReportMissingProp=void 0;var Le=he(),hf=$e(),rn=Cr(),gN=$e();function yN(t,e){let{gen:r,data:n,it:o}=t;r.if(mf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Le._)`${e}`},!0),t.error()})}Ae.checkReportMissingProp=yN;function bN({gen:t,data:e,it:{opts:r}},n,o){return(0,Le.or)(...n.map(s=>(0,Le.and)(mf(t,e,s,r.ownProperties),(0,Le._)`${o} = ${s}`)))}Ae.checkMissingProp=bN;function wN(t,e){t.setParams({missingProperty:e},!0),t.error()}Ae.reportMissingProp=wN;function $x(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Le._)`Object.prototype.hasOwnProperty`})}Ae.hasPropFunc=$x;function ff(t,e,r){return(0,Le._)`${$x(t)}.call(${e}, ${r})`}Ae.isOwnProperty=ff;function vN(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} !== undefined`;return n?(0,Le._)`${o} && ${ff(t,e,r)}`:o}Ae.propertyInData=vN;function mf(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} === undefined`;return n?(0,Le.or)(o,(0,Le.not)(ff(t,e,r))):o}Ae.noPropertyInData=mf;function Sx(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ae.allSchemaProperties=Sx;function _N(t,e){return Sx(e).filter(r=>!(0,hf.alwaysValidSchema)(t,e[r]))}Ae.schemaProperties=_N;function xN({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Le._)`${t}, ${e}, ${n}${o}`:e,p=[[rn.default.instancePath,(0,Le.strConcat)(rn.default.instancePath,s)],[rn.default.parentData,i.parentData],[rn.default.parentDataProperty,i.parentDataProperty],[rn.default.rootData,rn.default.rootData]];i.opts.dynamicRef&&p.push([rn.default.dynamicAnchors,rn.default.dynamicAnchors]);let w=(0,Le._)`${u}, ${r.object(...p)}`;return c!==Le.nil?(0,Le._)`${a}.call(${c}, ${w})`:(0,Le._)`${a}(${w})`}Ae.callValidateCode=xN;var kN=(0,Le._)`new RegExp`;function $N({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,Le._)`${o.code==="new RegExp"?kN:(0,gN.useFunc)(t,o)}(${r}, ${n})`})}Ae.usePattern=$N;function SN(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,Le._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:hf.Type.Num},s),e.if((0,Le.not)(s),a)})}}Ae.validateArray=SN;function TN(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,hf.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,Le._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Le.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ae.validateUnion=TN});var Rx=Z(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.validateKeywordUsage=mr.validSchemaType=mr.funcKeywordCode=mr.macroKeywordCode=void 0;var wt=he(),Bn=Cr(),EN=Ht(),RN=ei();function PN(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Ex(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:wt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}mr.macroKeywordCode=PN;function AN(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;ON(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Ex(n,o,l),p=n.let("valid");t.block$data(p,w),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function w(){if(e.errors===!1)b(),e.modifying&&Tx(t),k(()=>t.error());else{let E=e.async?m():h();e.modifying&&Tx(t),k(()=>IN(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>b((0,wt._)`await `),P=>n.assign(p,!1).if((0,wt._)`${P} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,wt._)`${P}.errors`),()=>n.throw(P))),E}function h(){let E=(0,wt._)`${u}.errors`;return n.assign(E,null),b(wt.nil),E}function b(E=e.async?(0,wt._)`await `:wt.nil){let P=c.opts.passContext?Bn.default.this:Bn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,wt._)`${E}${(0,EN.callValidateCode)(t,u,P,z)}`,e.modifying)}function k(E){var P;n.if((0,wt.not)((P=e.valid)!==null&&P!==void 0?P:p),E)}}mr.funcKeywordCode=AN;function Tx(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,wt._)`${n.parentData}[${n.parentDataProperty}]`))}function IN(t,e){let{gen:r}=t;r.if((0,wt._)`Array.isArray(${e})`,()=>{r.assign(Bn.default.vErrors,(0,wt._)`${Bn.default.vErrors} === null ? ${e} : ${Bn.default.vErrors}.concat(${e})`).assign(Bn.default.errors,(0,wt._)`${Bn.default.vErrors}.length`),(0,RN.extendErrors)(t)},()=>t.error())}function ON({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ex(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,wt.stringify)(r)})}function CN(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")}mr.validSchemaType=CN;function NN({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)}}mr.validateKeywordUsage=NN});var Ax=Z(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.extendSubschemaMode=nn.extendSubschemaData=nn.getSubschema=void 0;var gr=he(),Px=$e();function zN(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,gr._)`${t.schemaPath}${(0,gr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,gr._)`${t.schemaPath}${(0,gr.getProperty)(e)}${(0,gr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Px.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')}nn.getSubschema=zN;function jN(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:p}=e,w=a.let("data",(0,gr._)`${e.data}${(0,gr.getProperty)(r)}`,!0);c(w),t.errorPath=(0,gr.str)`${l}${(0,Px.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,gr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof gr.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]}}nn.extendSubschemaData=jN;function LN(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}nn.extendSubschemaMode=LN});var gf=Z((EH,Ix)=>{"use strict";Ix.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 Cx=Z((RH,Ox)=>{"use strict";var on=Ox.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(){};xc(e,n,o,t,"",t)};on.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};on.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};on.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};on.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 xc(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 p=n[u];if(Array.isArray(p)){if(u in on.arrayKeywords)for(var w=0;w<p.length;w++)xc(t,e,r,p[w],o+"/"+u+"/"+w,s,o,u,n,w)}else if(u in on.propsKeywords){if(p&&typeof p=="object")for(var m in p)xc(t,e,r,p[m],o+"/"+u+"/"+DN(m),s,o,u,n,m)}else(u in on.keywords||t.allKeys&&!(u in on.skipKeywords))&&xc(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function DN(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ri=Z(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.getSchemaRefs=Rt.resolveUrl=Rt.normalizeId=Rt._getFullPath=Rt.getFullPath=Rt.inlineRef=void 0;var UN=$e(),MN=gf(),qN=Cx(),ZN=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function BN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!yf(t):e?Nx(t)<=e:!1}Rt.inlineRef=BN;var FN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function yf(t){for(let e in t){if(FN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(yf)||typeof r=="object"&&yf(r))return!0}return!1}function Nx(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!ZN.has(r)&&(typeof t[r]=="object"&&(0,UN.eachItem)(t[r],n=>e+=Nx(n)),e===1/0))return 1/0}return e}function zx(t,e="",r){r!==!1&&(e=jo(e));let n=t.parse(e);return jx(t,n)}Rt.getFullPath=zx;function jx(t,e){return t.serialize(e).split("#")[0]+"#"}Rt._getFullPath=jx;var HN=/#\/?$/;function jo(t){return t?t.replace(HN,""):""}Rt.normalizeId=jo;function VN(t,e,r){return r=jo(r),t.resolve(e,r)}Rt.resolveUrl=VN;var KN=/^[a-z_][-a-z0-9._]*$/i;function GN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=jo(t[r]||e),s={"":o},i=zx(n,o,!1),a={},c=new Set;return qN(t,{allKeys:!0},(p,w,m,h)=>{if(h===void 0)return;let b=i+w,k=s[h];typeof p[r]=="string"&&(k=E.call(this,p[r])),P.call(this,p.$anchor),P.call(this,p.$dynamicAnchor),s[w]=k;function E(z){let V=this.opts.uriResolver.resolve;if(z=jo(k?V(k,z):z),c.has(z))throw u(z);c.add(z);let Q=this.refs[z];return typeof Q=="string"&&(Q=this.refs[Q]),typeof Q=="object"?l(p,Q.schema,z):z!==jo(b)&&(z[0]==="#"?(l(p,a[z],z),a[z]=p):this.refs[z]=b),z}function P(z){if(typeof z=="string"){if(!KN.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function l(p,w,m){if(w!==void 0&&!MN(p,w))throw u(m)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Rt.getSchemaRefs=GN});var si=Z(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.getData=sn.KeywordCxt=sn.validateFunctionCode=void 0;var qx=gx(),Lx=ti(),wf=lf(),kc=ti(),WN=kx(),oi=Rx(),bf=Ax(),J=he(),ce=Cr(),JN=ri(),Nr=$e(),ni=ei();function YN(t){if(Fx(t)&&(Hx(t),Bx(t))){ez(t);return}Zx(t,()=>(0,qx.topBoolOrEmptySchema)(t))}sn.validateFunctionCode=YN;function Zx({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,J._)`${ce.default.data}, ${ce.default.valCxt}`,n.$async,()=>{t.code((0,J._)`"use strict"; ${Dx(r,o)}`),XN(t,o),t.code(s)}):t.func(e,(0,J._)`${ce.default.data}, ${QN(o)}`,n.$async,()=>t.code(Dx(r,o)).code(s))}function QN(t){return(0,J._)`{${ce.default.instancePath}="", ${ce.default.parentData}, ${ce.default.parentDataProperty}, ${ce.default.rootData}=${ce.default.data}${t.dynamicRef?(0,J._)`, ${ce.default.dynamicAnchors}={}`:J.nil}}={}`}function XN(t,e){t.if(ce.default.valCxt,()=>{t.var(ce.default.instancePath,(0,J._)`${ce.default.valCxt}.${ce.default.instancePath}`),t.var(ce.default.parentData,(0,J._)`${ce.default.valCxt}.${ce.default.parentData}`),t.var(ce.default.parentDataProperty,(0,J._)`${ce.default.valCxt}.${ce.default.parentDataProperty}`),t.var(ce.default.rootData,(0,J._)`${ce.default.valCxt}.${ce.default.rootData}`),e.dynamicRef&&t.var(ce.default.dynamicAnchors,(0,J._)`${ce.default.valCxt}.${ce.default.dynamicAnchors}`)},()=>{t.var(ce.default.instancePath,(0,J._)`""`),t.var(ce.default.parentData,(0,J._)`undefined`),t.var(ce.default.parentDataProperty,(0,J._)`undefined`),t.var(ce.default.rootData,ce.default.data),e.dynamicRef&&t.var(ce.default.dynamicAnchors,(0,J._)`{}`)})}function ez(t){let{schema:e,opts:r,gen:n}=t;Zx(t,()=>{r.$comment&&e.$comment&&Kx(t),sz(t),n.let(ce.default.vErrors,null),n.let(ce.default.errors,0),r.unevaluated&&tz(t),Vx(t),cz(t)})}function tz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,J._)`${r}.evaluated`),e.if((0,J._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,J._)`${t.evaluated}.props`,(0,J._)`undefined`)),e.if((0,J._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,J._)`${t.evaluated}.items`,(0,J._)`undefined`))}function Dx(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,J._)`/*# sourceURL=${r} */`:J.nil}function rz(t,e){if(Fx(t)&&(Hx(t),Bx(t))){nz(t,e);return}(0,qx.boolOrEmptySchema)(t,e)}function Bx({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 Fx(t){return typeof t.schema!="boolean"}function nz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Kx(t),iz(t),az(t);let s=n.const("_errs",ce.default.errors);Vx(t,s),n.var(e,(0,J._)`${s} === ${ce.default.errors}`)}function Hx(t){(0,Nr.checkUnknownRules)(t),oz(t)}function Vx(t,e){if(t.opts.jtd)return Ux(t,[],!1,e);let r=(0,Lx.getSchemaTypes)(t.schema),n=(0,Lx.coerceAndCheckDataType)(t,r);Ux(t,r,!n,e)}function oz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Nr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function sz(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Nr.checkStrictMode)(t,"default is ignored in the schema root")}function iz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,JN.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function az(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Kx({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,J._)`${ce.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,J.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,J._)`${ce.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function cz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,J._)`${ce.default.errors} === 0`,()=>e.return(ce.default.data),()=>e.throw((0,J._)`new ${o}(${ce.default.vErrors})`)):(e.assign((0,J._)`${n}.errors`,ce.default.vErrors),s.unevaluated&&lz(t),e.return((0,J._)`${ce.default.errors} === 0`))}function lz({gen:t,evaluated:e,props:r,items:n}){r instanceof J.Name&&t.assign((0,J._)`${e}.props`,r),n instanceof J.Name&&t.assign((0,J._)`${e}.items`,n)}function Ux(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,Nr.schemaHasRulesButRef)(s,u))){o.block(()=>Wx(t,"$ref",u.all.$ref.definition));return}c.jtd||uz(t,e),o.block(()=>{for(let w of u.rules)p(w);p(u.post)});function p(w){(0,wf.shouldUseGroup)(s,w)&&(w.type?(o.if((0,kc.checkDataType)(w.type,i,c.strictNumbers)),Mx(t,w),e.length===1&&e[0]===w.type&&r&&(o.else(),(0,kc.reportTypeError)(t)),o.endIf()):Mx(t,w),a||o.if((0,J._)`${ce.default.errors} === ${n||0}`))}}function Mx(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,WN.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,wf.shouldUseRule)(n,s)&&Wx(t,s.keyword,s.definition,e.type)})}function uz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(dz(t,e),t.opts.allowUnionTypes||pz(t,e),hz(t,t.dataTypes))}function dz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Gx(t.dataTypes,r)||vf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),mz(t,e)}}function pz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&vf(t,"use allowUnionTypes to allow union type keyword")}function hz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,wf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>fz(e,i))&&vf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function fz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Gx(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function mz(t,e){let r=[];for(let n of t.dataTypes)Gx(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function vf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Nr.checkStrictMode)(t,e,t.opts.strictTypes)}var $c=class{constructor(e,r,n){if((0,oi.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,Nr.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",Jx(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,oi.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",ce.default.errors))}result(e,r,n){this.failResult((0,J.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,J.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,J._)`${r} !== undefined && (${(0,J.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?ni.reportExtraError:ni.reportError)(this,this.def.error,r)}$dataError(){(0,ni.reportError)(this,this.def.$dataError||ni.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ni.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=J.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=J.nil,r=J.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,J.or)((0,J._)`${o} === undefined`,r)),e!==J.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==J.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,J.or)(i(),a());function i(){if(n.length){if(!(r instanceof J.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,J._)`${(0,kc.checkDataTypes)(c,r,s.opts.strictNumbers,kc.DataType.Wrong)}`}return J.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,J._)`!${c}(${r})`}return J.nil}}subschema(e,r){let n=(0,bf.getSubschema)(this.it,e);(0,bf.extendSubschemaData)(n,this.it,e),(0,bf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return rz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Nr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Nr.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,J.Name)),!0}};sn.KeywordCxt=$c;function Wx(t,e,r,n){let o=new $c(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,oi.funcKeywordCode)(o,r):"macro"in r?(0,oi.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,oi.funcKeywordCode)(o,r)}var gz=/^\/(?:[^~]|~0|~1)*$/,yz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Jx(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ce.default.rootData;if(t[0]==="/"){if(!gz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ce.default.rootData}else{let l=yz.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,J._)`${s}${(0,J.getProperty)((0,Nr.unescapeJsonPointer)(l))}`,i=(0,J._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}sn.getData=Jx});var Sc=Z(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var _f=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xf.default=_f});var ii=Z(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var kf=ri(),$f=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,kf.resolveUrl)(e,r,n),this.missingSchema=(0,kf.normalizeId)((0,kf.getFullPath)(e,this.missingRef))}};Sf.default=$f});var Ec=Z(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.resolveSchema=Vt.getCompilingSchema=Vt.resolveRef=Vt.compileSchema=Vt.SchemaEnv=void 0;var or=he(),bz=Sc(),Fn=Cr(),sr=ri(),Yx=$e(),wz=si(),Lo=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,sr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Vt.SchemaEnv=Lo;function Ef(t){let e=Qx.call(this,t);if(e)return e;let r=(0,sr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new or.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:bz.default,code:(0,or._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Fn.default.data,parentData:Fn.default.parentData,parentDataProperty:Fn.default.parentDataProperty,dataNames:[Fn.default.data],dataPathArr:[or.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,or.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:or.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,or._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,wz.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Fn.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let m=new Function(`${Fn.default.self}`,`${Fn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:b}=l;m.evaluated={props:h instanceof or.Name?void 0:h,items:b instanceof or.Name?void 0:b,dynamicProps:h instanceof or.Name,dynamicItems:b instanceof or.Name},m.source&&(m.source.evaluated=(0,or.stringify)(m.evaluated))}return t.validate=m,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}Vt.compileSchema=Ef;function vz(t,e,r){var n;r=(0,sr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=kz.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 Lo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=_z.call(this,s)}Vt.resolveRef=vz;function _z(t){return(0,sr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ef.call(this,t)}function Qx(t){for(let e of this._compilations)if(xz(e,t))return e}Vt.getCompilingSchema=Qx;function xz(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function kz(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Tc.call(this,t,e)}function Tc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,sr._getFullPath)(this.opts.uriResolver,r),o=(0,sr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Tf.call(this,r,t);let s=(0,sr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Tc.call(this,t,i);return typeof a?.schema!="object"?void 0:Tf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ef.call(this,i),s===(0,sr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,sr.resolveUrl)(this.opts.uriResolver,o,l)),new Lo({schema:a,schemaId:c,root:t,baseId:o})}return Tf.call(this,r,i)}}Vt.resolveSchema=Tc;var $z=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Tf(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,Yx.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!$z.has(a)&&l&&(e=(0,sr.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Yx.schemaHasRulesButRef)(r,this.RULES)){let a=(0,sr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Tc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Lo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Xx=Z((NH,Sz)=>{Sz.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 Af=Z((zH,sk)=>{"use strict";var Tz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),tk=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),Rf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),rk=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Ez=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Pf(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 Rz=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ek(t){return t.length=0,!0}function Pz(t,e,r){if(t.length){let n=Pf(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Az(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=Pz;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=ek}else{o.push(l);continue}}return o.length&&(a===ek?r.zone=o.join(""):i?n.push(o.join("")):n.push(Pf(o))),r.address=n.join(""),r}function nk(t){if(Iz(t,":")<2)return{host:t,isIPV6:!1};let e=Az(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 Iz(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Oz(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 Cz={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Nz=/[@/?#:]/g,zz=/[@/?#]/g;function ok(t,e){let r=e?zz:Nz;return r.lastIndex=0,t.replace(r,n=>Cz[n])}function jz(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(Rf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&rk(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function Lz(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(Rf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&rk(s)?e+=s:e+="%"+o,r+=2;continue}}Ez(t[r])?e+=t[r]:e+=escape(t[r])}return e}function Dz(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(Rf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function Uz(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!tk(r)){let n=nk(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=ok(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}sk.exports={nonSimpleDomain:Rz,recomposeAuthority:Uz,reescapeHostDelimiters:ok,normalizePercentEncoding:jz,normalizePathEncoding:Lz,escapePreservingEscapes:Dz,removeDotSegments:Oz,isIPv4:tk,isUUID:Tz,normalizeIPv6:nk,stringArrayToHexStripped:Pf}});var uk=Z((jH,lk)=>{"use strict";var{isUUID:Mz}=Af(),qz=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Zz=["http","https","ws","wss","urn","urn:uuid"];function Bz(t){return Zz.indexOf(t)!==-1}function If(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 ik(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function ak(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 Fz(t){return t.secure=If(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Hz(t){if((t.port===(If(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 Vz(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(qz);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=Of(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Kz(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=Of(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 Gz(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Mz(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Wz(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var ck={scheme:"http",domainHost:!0,parse:ik,serialize:ak},Jz={scheme:"https",domainHost:ck.domainHost,parse:ik,serialize:ak},Rc={scheme:"ws",domainHost:!0,parse:Fz,serialize:Hz},Yz={scheme:"wss",domainHost:Rc.domainHost,parse:Rc.parse,serialize:Rc.serialize},Qz={scheme:"urn",parse:Vz,serialize:Kz,skipNormalize:!0},Xz={scheme:"urn:uuid",parse:Gz,serialize:Wz,skipNormalize:!0},Pc={http:ck,https:Jz,ws:Rc,wss:Yz,urn:Qz,"urn:uuid":Xz};Object.setPrototypeOf(Pc,null);function Of(t){return t&&(Pc[t]||Pc[t.toLowerCase()])||void 0}lk.exports={wsIsSecure:If,SCHEMES:Pc,isValidSchemeName:Bz,getSchemeHandler:Of}});var mk=Z((LH,Oc)=>{"use strict";var{normalizeIPv6:ej,removeDotSegments:ai,recomposeAuthority:tj,normalizePercentEncoding:rj,normalizePathEncoding:nj,escapePreservingEscapes:oj,reescapeHostDelimiters:sj,isIPv4:ij,nonSimpleDomain:aj}=Af(),{SCHEMES:cj,getSchemeHandler:pk}=uk();function lj(t,e){return typeof t=="string"?t=gj(t,e):typeof t=="object"&&(t=Ic(Hn(t,e),e)),t}function uj(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=Ac(t,n),{parsed:i,malformedAuthorityOrPort:a}=Ac(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=hk(o,i,n,!0);return n.skipEscape=!0,Hn(c,n)}function hk(t,e,r,n){let o={};return n||(t=Ic(Hn(t,r),r),e=Ic(Hn(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=ai(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=ai(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ai(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=ai(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 dj(t,e,r){let n=dk(t,r),o=dk(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Hn(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=pk(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=rj(r.path):(r.path=oj(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=tj(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=ai(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 pj=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,hj=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,fj=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function mj(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 Ac(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(hj);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(fj);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(pj);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=mj(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(ij(n.host)===!1){let w=ej(n.host);n.host=w.host.toLowerCase(),s=w.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=pk(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&aj(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=sj(unescape(n.host),s))),n.path&&(n.path=nj(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 Ic(t,e){return Ac(t,e).parsed}function gj(t,e){return fk(t,e).normalized}function fk(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Ac(t,e);return{normalized:n?t:Hn(r,e),malformedAuthorityOrPort:n}}function dk(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=fk(t,e);return n?void 0:r}if(typeof t=="object")return Hn(t,e)}var Cf={SCHEMES:cj,normalize:lj,resolve:uj,resolveComponent:hk,equal:dj,serialize:Hn,parse:Ic};Oc.exports=Cf;Oc.exports.default=Cf;Oc.exports.fastUri=Cf});var yk=Z(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var gk=mk();gk.code='require("ajv/dist/runtime/uri").default';Nf.default=gk});var Sk=Z(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.CodeGen=at.Name=at.nil=at.stringify=at.str=at._=at.KeywordCxt=void 0;var yj=si();Object.defineProperty(at,"KeywordCxt",{enumerable:!0,get:function(){return yj.KeywordCxt}});var Do=he();Object.defineProperty(at,"_",{enumerable:!0,get:function(){return Do._}});Object.defineProperty(at,"str",{enumerable:!0,get:function(){return Do.str}});Object.defineProperty(at,"stringify",{enumerable:!0,get:function(){return Do.stringify}});Object.defineProperty(at,"nil",{enumerable:!0,get:function(){return Do.nil}});Object.defineProperty(at,"Name",{enumerable:!0,get:function(){return Do.Name}});Object.defineProperty(at,"CodeGen",{enumerable:!0,get:function(){return Do.CodeGen}});var bj=Sc(),xk=ii(),wj=cf(),ci=Ec(),vj=he(),li=ri(),Cc=ti(),jf=$e(),bk=Xx(),_j=yk(),kk=(t,e)=>new RegExp(t,e);kk.code="new RegExp";var xj=["removeAdditional","useDefaults","coerceTypes"],kj=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),$j={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."},Sj={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},wk=200;function Tj(t){var e,r,n,o,s,i,a,c,l,u,p,w,m,h,b,k,E,P,z,V,Q,Ge,rt,Gt,Wt;let un=t.strict,Wo=(e=t.code)===null||e===void 0?void 0:e.optimize,zr=Wo===!0||Wo===void 0?1:Wo||0,dn=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:kk,Wn=(o=t.uriResolver)!==null&&o!==void 0?o:_j.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:un)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:un)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:un)!==null&&u!==void 0?u:"log",strictTuples:(w=(p=t.strictTuples)!==null&&p!==void 0?p:un)!==null&&w!==void 0?w:"log",strictRequired:(h=(m=t.strictRequired)!==null&&m!==void 0?m:un)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:zr,regExp:dn}:{optimize:zr,regExp:dn},loopRequired:(b=t.loopRequired)!==null&&b!==void 0?b:wk,loopEnum:(k=t.loopEnum)!==null&&k!==void 0?k:wk,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(P=t.messages)!==null&&P!==void 0?P:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(V=t.schemaId)!==null&&V!==void 0?V:"$id",addUsedSchema:(Q=t.addUsedSchema)!==null&&Q!==void 0?Q:!0,validateSchema:(Ge=t.validateSchema)!==null&&Ge!==void 0?Ge:!0,validateFormats:(rt=t.validateFormats)!==null&&rt!==void 0?rt:!0,unicodeRegExp:(Gt=t.unicodeRegExp)!==null&&Gt!==void 0?Gt:!0,int32range:(Wt=t.int32range)!==null&&Wt!==void 0?Wt:!0,uriResolver:Wn}}var ui=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,...Tj(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new vj.ValueScope({scope:{},prefixes:kj,es5:r,lines:n}),this.logger=Oj(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,wj.getRules)(),vk.call(this,$j,e,"NOT SUPPORTED"),vk.call(this,Sj,e,"DEPRECATED","warn"),this._metaOpts=Aj.call(this),e.formats&&Rj.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Pj.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ej.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=bk;n==="id"&&(o={...bk},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,p){await s.call(this,u.$schema);let w=this._addSchema(u,p);return w.validate||i.call(this,w)}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(p){if(!(p instanceof xk.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await l.call(this,u);this.refs[u]||await s.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,r)}async function l(u){let p=this._loading[u];if(p)return p;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,li.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=_k.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ci.SchemaEnv({schema:{},schemaId:n});if(r=ci.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=_k.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,li.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(Nj.call(this,n,r),!r)return(0,jf.eachItem)(n,s=>zf.call(this,s)),this;jj.call(this,r);let o={...r,type:(0,Cc.getJSONTypes)(r.type),schemaType:(0,Cc.getJSONTypes)(r.schemaType)};return(0,jf.eachItem)(n,o.type.length===0?s=>zf.call(this,s,o):s=>o.type.forEach(i=>zf.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]=$k(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,li.normalizeId)(i||n);let l=li.getSchemaRefs.call(this,e,n);return c=new ci.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):ci.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{ci.compileSchema.call(this,e)}finally{this.opts=r}}};ui.ValidationError=bj.default;ui.MissingRefError=xk.default;at.default=ui;function vk(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 _k(t){return t=(0,li.normalizeId)(t),this.schemas[t]||this.refs[t]}function Ej(){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 Rj(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Pj(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 Aj(){let t={...this.opts};for(let e of xj)delete t[e];return t}var Ij={log(){},warn(){},error(){}};function Oj(t){if(t===!1)return Ij;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 Cj=/^[a-z_$][a-z0-9_$:-]*$/i;function Nj(t,e){let{RULES:r}=this;if((0,jf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Cj.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 zf(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,Cc.getJSONTypes)(e.type),schemaType:(0,Cc.getJSONTypes)(e.schemaType)}};e.before?zj.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 zj(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 jj(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=$k(e)),t.validateSchema=this.compile(e,!0))}var Lj={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function $k(t){return{anyOf:[t,Lj]}}});var Tk=Z(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var Dj={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Lf.default=Dj});var Ak=Z(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.callRef=Vn.getValidate=void 0;var Uj=ii(),Ek=Ht(),Pt=he(),Uo=Cr(),Rk=Ec(),Nc=$e(),Mj={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 p();let u=Rk.resolveRef.call(c,l,o,r);if(u===void 0)throw new Uj.default(n.opts.uriResolver,o,r);if(u instanceof Rk.SchemaEnv)return w(u);return m(u);function p(){if(s===l)return zc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:l});return zc(t,(0,Pt._)`${h}.validate`,l,l.$async)}function w(h){let b=Pk(t,h);zc(t,b,h,h.$async)}function m(h){let b=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Pt.stringify)(h)}:{ref:h}),k=e.name("valid"),E=t.subschema({schema:h,dataTypes:[],schemaPath:Pt.nil,topSchemaRef:b,errSchemaPath:r},k);t.mergeEvaluated(E),t.ok(k)}}};function Pk(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Pt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Vn.getValidate=Pk;function zc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Uo.default.this:Pt.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,Pt._)`await ${(0,Ek.callValidateCode)(t,e,l)}`),m(e),i||o.assign(h,!0)},b=>{o.if((0,Pt._)`!(${b} instanceof ${s.ValidationError})`,()=>o.throw(b)),w(b),i||o.assign(h,!1)}),t.ok(h)}function p(){t.result((0,Ek.callValidateCode)(t,e,l),()=>m(e),()=>w(e))}function w(h){let b=(0,Pt._)`${h}.errors`;o.assign(Uo.default.vErrors,(0,Pt._)`${Uo.default.vErrors} === null ? ${b} : ${Uo.default.vErrors}.concat(${b})`),o.assign(Uo.default.errors,(0,Pt._)`${Uo.default.vErrors}.length`)}function m(h){var b;if(!s.opts.unevaluated)return;let k=(b=r?.validate)===null||b===void 0?void 0:b.evaluated;if(s.props!==!0)if(k&&!k.dynamicProps)k.props!==void 0&&(s.props=Nc.mergeEvaluated.props(o,k.props,s.props));else{let E=o.var("props",(0,Pt._)`${h}.evaluated.props`);s.props=Nc.mergeEvaluated.props(o,E,s.props,Pt.Name)}if(s.items!==!0)if(k&&!k.dynamicItems)k.items!==void 0&&(s.items=Nc.mergeEvaluated.items(o,k.items,s.items));else{let E=o.var("items",(0,Pt._)`${h}.evaluated.items`);s.items=Nc.mergeEvaluated.items(o,E,s.items,Pt.Name)}}}Vn.callRef=zc;Vn.default=Mj});var Ik=Z(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var qj=Tk(),Zj=Ak(),Bj=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",qj.default,Zj.default];Df.default=Bj});var Ok=Z(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var jc=he(),an=jc.operators,Lc={maximum:{okStr:"<=",ok:an.LTE,fail:an.GT},minimum:{okStr:">=",ok:an.GTE,fail:an.LT},exclusiveMaximum:{okStr:"<",ok:an.LT,fail:an.GTE},exclusiveMinimum:{okStr:">",ok:an.GT,fail:an.LTE}},Fj={message:({keyword:t,schemaCode:e})=>(0,jc.str)`must be ${Lc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,jc._)`{comparison: ${Lc[t].okStr}, limit: ${e}}`},Hj={keyword:Object.keys(Lc),type:"number",schemaType:"number",$data:!0,error:Fj,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,jc._)`${r} ${Lc[e].fail} ${n} || isNaN(${r})`)}};Uf.default=Hj});var Ck=Z(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var di=he(),Vj={message:({schemaCode:t})=>(0,di.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,di._)`{multipleOf: ${t}}`},Kj={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Vj,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,di._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,di._)`${i} !== parseInt(${i})`;t.fail$data((0,di._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Mf.default=Kj});var zk=Z(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});function Nk(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}qf.default=Nk;Nk.code='require("ajv/dist/runtime/ucs2length").default'});var jk=Z(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var Kn=he(),Gj=$e(),Wj=zk(),Jj={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Kn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Kn._)`{limit: ${t}}`},Yj={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Jj,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Kn.operators.GT:Kn.operators.LT,i=o.opts.unicode===!1?(0,Kn._)`${r}.length`:(0,Kn._)`${(0,Gj.useFunc)(t.gen,Wj.default)}(${r})`;t.fail$data((0,Kn._)`${i} ${s} ${n}`)}};Zf.default=Yj});var Lk=Z(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var Qj=Ht(),Xj=$e(),Mo=he(),e1={message:({schemaCode:t})=>(0,Mo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Mo._)`{pattern: ${t}}`},t1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:e1,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,Mo._)`new RegExp`:(0,Xj.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Mo._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Mo._)`!${u}`)}else{let c=(0,Qj.usePattern)(t,o);t.fail$data((0,Mo._)`!${c}.test(${r})`)}}};Bf.default=t1});var Dk=Z(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var pi=he(),r1={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,pi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,pi._)`{limit: ${t}}`},n1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:r1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?pi.operators.GT:pi.operators.LT;t.fail$data((0,pi._)`Object.keys(${r}).length ${o} ${n}`)}};Ff.default=n1});var Uk=Z(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var hi=Ht(),fi=he(),o1=$e(),s1={message:({params:{missingProperty:t}})=>(0,fi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,fi._)`{missingProperty: ${t}}`},i1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:s1,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 m=t.parentSchema.properties,{definedProperties:h}=t.it;for(let b of r)if(m?.[b]===void 0&&!h.has(b)){let k=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${b}" is not defined at "${k}" (strictRequired)`;(0,o1.checkStrictMode)(i,E,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(fi.nil,p);else for(let m of r)(0,hi.checkReportMissingProp)(t,m)}function u(){let m=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>w(m,h)),t.ok(h)}else e.if((0,hi.checkMissingProp)(t,r,m)),(0,hi.reportMissingProp)(t,m),e.else()}function p(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,hi.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function w(m,h){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(h,(0,hi.propertyInData)(e,o,m,a.ownProperties)),e.if((0,fi.not)(h),()=>{t.error(),e.break()})},fi.nil)}}};Hf.default=i1});var Mk=Z(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var mi=he(),a1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,mi.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,mi._)`{limit: ${t}}`},c1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:a1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?mi.operators.GT:mi.operators.LT;t.fail$data((0,mi._)`${r}.length ${o} ${n}`)}};Vf.default=c1});var Dc=Z(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var qk=gf();qk.code='require("ajv/dist/runtime/equal").default';Kf.default=qk});var Zk=Z(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var Gf=ti(),ct=he(),l1=$e(),u1=Dc(),d1={message:({params:{i:t,j:e}})=>(0,ct.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ct._)`{i: ${t}, j: ${e}}`},p1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:d1,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,Gf.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,ct._)`${i} === false`),t.ok(c);function u(){let h=e.let("i",(0,ct._)`${r}.length`),b=e.let("j");t.setParams({i:h,j:b}),e.assign(c,!0),e.if((0,ct._)`${h} > 1`,()=>(p()?w:m)(h,b))}function p(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function w(h,b){let k=e.name("item"),E=(0,Gf.checkDataTypes)(l,k,a.opts.strictNumbers,Gf.DataType.Wrong),P=e.const("indices",(0,ct._)`{}`);e.for((0,ct._)`;${h}--;`,()=>{e.let(k,(0,ct._)`${r}[${h}]`),e.if(E,(0,ct._)`continue`),l.length>1&&e.if((0,ct._)`typeof ${k} == "string"`,(0,ct._)`${k} += "_"`),e.if((0,ct._)`typeof ${P}[${k}] == "number"`,()=>{e.assign(b,(0,ct._)`${P}[${k}]`),t.error(),e.assign(c,!1).break()}).code((0,ct._)`${P}[${k}] = ${h}`)})}function m(h,b){let k=(0,l1.useFunc)(e,u1.default),E=e.name("outer");e.label(E).for((0,ct._)`;${h}--;`,()=>e.for((0,ct._)`${b} = ${h}; ${b}--;`,()=>e.if((0,ct._)`${k}(${r}[${h}], ${r}[${b}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};Wf.default=p1});var Bk=Z(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var Jf=he(),h1=$e(),f1=Dc(),m1={message:"must be equal to constant",params:({schemaCode:t})=>(0,Jf._)`{allowedValue: ${t}}`},g1={keyword:"const",$data:!0,error:m1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Jf._)`!${(0,h1.useFunc)(e,f1.default)}(${r}, ${o})`):t.fail((0,Jf._)`${s} !== ${r}`)}};Yf.default=g1});var Fk=Z(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var gi=he(),y1=$e(),b1=Dc(),w1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,gi._)`{allowedValues: ${t}}`},v1={keyword:"enum",schemaType:"array",$data:!0,error:w1,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,y1.useFunc)(e,b1.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);u=(0,gi.or)(...o.map((h,b)=>w(m,b)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,m=>e.if((0,gi._)`${l()}(${r}, ${m})`,()=>e.assign(u,!0).break()))}function w(m,h){let b=o[h];return typeof b=="object"&&b!==null?(0,gi._)`${l()}(${r}, ${m}[${h}])`:(0,gi._)`${r} === ${b}`}}};Qf.default=v1});var Hk=Z(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var _1=Ok(),x1=Ck(),k1=jk(),$1=Lk(),S1=Dk(),T1=Uk(),E1=Mk(),R1=Zk(),P1=Bk(),A1=Fk(),I1=[_1.default,x1.default,k1.default,$1.default,S1.default,T1.default,E1.default,R1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},P1.default,A1.default];Xf.default=I1});var tm=Z(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.validateAdditionalItems=void 0;var Gn=he(),em=$e(),O1={message:({params:{len:t}})=>(0,Gn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Gn._)`{limit: ${t}}`},C1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:O1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,em.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Vk(t,n)}};function Vk(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Gn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Gn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,em.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Gn._)`${a} <= ${e.length}`);r.if((0,Gn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:em.Type.Num},l),i.allErrors||r.if((0,Gn.not)(l),()=>r.break())})}}yi.validateAdditionalItems=Vk;yi.default=C1});var rm=Z(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.validateTuple=void 0;var Kk=he(),Uc=$e(),N1=Ht(),z1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Gk(t,"additionalItems",e);r.items=!0,!(0,Uc.alwaysValidSchema)(r,e)&&t.ok((0,N1.validateArray)(t))}};function Gk(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=Uc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Kk._)`${s}.length`);r.forEach((p,w)=>{(0,Uc.alwaysValidSchema)(a,p)||(n.if((0,Kk._)`${l} > ${w}`,()=>t.subschema({keyword:i,schemaProp:w,dataProp:w},c)),t.ok(c))});function u(p){let{opts:w,errSchemaPath:m}=a,h=r.length,b=h===p.minItems&&(h===p.maxItems||p[e]===!1);if(w.strictTuples&&!b){let k=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Uc.checkStrictMode)(a,k,w.strictTuples)}}}bi.validateTuple=Gk;bi.default=z1});var Wk=Z(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var j1=rm(),L1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,j1.validateTuple)(t,"items")};nm.default=L1});var Yk=Z(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});var Jk=he(),D1=$e(),U1=Ht(),M1=tm(),q1={message:({params:{len:t}})=>(0,Jk.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Jk._)`{limit: ${t}}`},Z1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:q1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,D1.alwaysValidSchema)(n,e)&&(o?(0,M1.validateAdditionalItems)(t,o):t.ok((0,U1.validateArray)(t)))}};om.default=Z1});var Qk=Z(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var Kt=he(),Mc=$e(),B1={message:({params:{min:t,max:e}})=>e===void 0?(0,Kt.str)`must contain at least ${t} valid item(s)`:(0,Kt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Kt._)`{minContains: ${t}}`:(0,Kt._)`{minContains: ${t}, maxContains: ${e}}`},F1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:B1,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,Kt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Mc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Mc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Mc.alwaysValidSchema)(s,r)){let b=(0,Kt._)`${u} >= ${i}`;a!==void 0&&(b=(0,Kt._)`${b} && ${u} <= ${a}`),t.pass(b);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?m(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,Kt._)`${o}.length > 0`,w)):(e.let(p,!1),w()),t.result(p,()=>t.reset());function w(){let b=e.name("_valid"),k=e.let("count",0);m(b,()=>e.if(b,()=>h(k)))}function m(b,k){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:Mc.Type.Num,compositeRule:!0},b),k()})}function h(b){e.code((0,Kt._)`${b}++`),a===void 0?e.if((0,Kt._)`${b} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,Kt._)`${b} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,Kt._)`${b} >= ${i}`,()=>e.assign(p,!0)))}}};sm.default=F1});var t$=Z(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.validateSchemaDeps=yr.validatePropertyDeps=yr.error=void 0;var im=he(),H1=$e(),wi=Ht();yr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,im.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,im._)`{property: ${t},
|
|
1915
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,ue._)`[${o}]`)}}}function hN({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ue._)`${e} !== undefined`,()=>t.assign((0,ue._)`${e}[${r}]`,n))}function df(t,e,r,n=Co.Correct){let o=n===Co.Correct?ue.operators.EQ:ue.operators.NEQ,s;switch(t){case"null":return(0,ue._)`${e} ${o} null`;case"array":s=(0,ue._)`Array.isArray(${e})`;break;case"object":s=(0,ue._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ue._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ue._)`typeof ${e} ${o} ${t}`}return n===Co.Correct?s:(0,ue.not)(s);function i(a=ue.nil){return(0,ue.and)((0,ue._)`typeof ${e} == "number"`,a,r?(0,ue._)`isFinite(${e})`:ue.nil)}}pt.checkDataType=df;function pf(t,e,r,n){if(t.length===1)return df(t[0],e,r,n);let o,s=(0,vx.toHash)(t);if(s.array&&s.object){let i=(0,ue._)`typeof ${e} != "object"`;o=s.null?i:(0,ue._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ue.nil;s.number&&delete s.integer;for(let i in s)o=(0,ue.and)(o,df(i,e,r,n));return o}pt.checkDataTypes=pf;var fN={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ue._)`{type: ${t}}`:(0,ue._)`{type: ${e}}`};function hf(t){let e=mN(t);(0,cN.reportError)(e,fN)}pt.reportTypeError=hf;function mN(t){let{gen:e,data:r,schema:n}=t,o=(0,vx.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(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.assignDefaults=void 0;var No=he(),gN=$e();function yN(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)kx(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>kx(t,s,o.default))}xc.assignDefaults=yN;function kx(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,No._)`${s}${(0,No.getProperty)(e)}`;if(o){(0,gN.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,No._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,No._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,No._)`${a} = ${(0,No.stringify)(r)}`)}});var Vt=Z(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.validateUnion=Ae.validateArray=Ae.usePattern=Ae.callValidateCode=Ae.schemaProperties=Ae.allSchemaProperties=Ae.noPropertyInData=Ae.propertyInData=Ae.isOwnProperty=Ae.hasPropFunc=Ae.reportMissingProp=Ae.checkMissingProp=Ae.checkReportMissingProp=void 0;var Le=he(),ff=$e(),nn=Or(),bN=$e();function wN(t,e){let{gen:r,data:n,it:o}=t;r.if(gf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Le._)`${e}`},!0),t.error()})}Ae.checkReportMissingProp=wN;function vN({gen:t,data:e,it:{opts:r}},n,o){return(0,Le.or)(...n.map(s=>(0,Le.and)(gf(t,e,s,r.ownProperties),(0,Le._)`${o} = ${s}`)))}Ae.checkMissingProp=vN;function _N(t,e){t.setParams({missingProperty:e},!0),t.error()}Ae.reportMissingProp=_N;function Sx(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Le._)`Object.prototype.hasOwnProperty`})}Ae.hasPropFunc=Sx;function mf(t,e,r){return(0,Le._)`${Sx(t)}.call(${e}, ${r})`}Ae.isOwnProperty=mf;function xN(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} !== undefined`;return n?(0,Le._)`${o} && ${mf(t,e,r)}`:o}Ae.propertyInData=xN;function gf(t,e,r,n){let o=(0,Le._)`${e}${(0,Le.getProperty)(r)} === undefined`;return n?(0,Le.or)(o,(0,Le.not)(mf(t,e,r))):o}Ae.noPropertyInData=gf;function Tx(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ae.allSchemaProperties=Tx;function kN(t,e){return Tx(e).filter(r=>!(0,ff.alwaysValidSchema)(t,e[r]))}Ae.schemaProperties=kN;function $N({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Le._)`${t}, ${e}, ${n}${o}`:e,p=[[nn.default.instancePath,(0,Le.strConcat)(nn.default.instancePath,s)],[nn.default.parentData,i.parentData],[nn.default.parentDataProperty,i.parentDataProperty],[nn.default.rootData,nn.default.rootData]];i.opts.dynamicRef&&p.push([nn.default.dynamicAnchors,nn.default.dynamicAnchors]);let w=(0,Le._)`${u}, ${r.object(...p)}`;return c!==Le.nil?(0,Le._)`${a}.call(${c}, ${w})`:(0,Le._)`${a}(${w})`}Ae.callValidateCode=$N;var SN=(0,Le._)`new RegExp`;function TN({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,Le._)`${o.code==="new RegExp"?SN:(0,bN.useFunc)(t,o)}(${r}, ${n})`})}Ae.usePattern=TN;function EN(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,Le._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:ff.Type.Num},s),e.if((0,Le.not)(s),a)})}}Ae.validateArray=EN;function RN(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,ff.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,Le._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Le.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ae.validateUnion=RN});var Px=Z(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.validateKeywordUsage=fr.validSchemaType=fr.funcKeywordCode=fr.macroKeywordCode=void 0;var vt=he(),Zn=Or(),PN=Vt(),AN=Qs();function IN(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Rx(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:vt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}fr.macroKeywordCode=IN;function ON(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;NN(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Rx(n,o,l),p=n.let("valid");t.block$data(p,w),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function w(){if(e.errors===!1)b(),e.modifying&&Ex(t),$(()=>t.error());else{let E=e.async?m():h();e.modifying&&Ex(t),$(()=>CN(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>b((0,vt._)`await `),P=>n.assign(p,!1).if((0,vt._)`${P} instanceof ${c.ValidationError}`,()=>n.assign(E,(0,vt._)`${P}.errors`),()=>n.throw(P))),E}function h(){let E=(0,vt._)`${u}.errors`;return n.assign(E,null),b(vt.nil),E}function b(E=e.async?(0,vt._)`await `:vt.nil){let P=c.opts.passContext?Zn.default.this:Zn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,vt._)`${E}${(0,PN.callValidateCode)(t,u,P,z)}`,e.modifying)}function $(E){var P;n.if((0,vt.not)((P=e.valid)!==null&&P!==void 0?P:p),E)}}fr.funcKeywordCode=ON;function Ex(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,vt._)`${n.parentData}[${n.parentDataProperty}]`))}function CN(t,e){let{gen:r}=t;r.if((0,vt._)`Array.isArray(${e})`,()=>{r.assign(Zn.default.vErrors,(0,vt._)`${Zn.default.vErrors} === null ? ${e} : ${Zn.default.vErrors}.concat(${e})`).assign(Zn.default.errors,(0,vt._)`${Zn.default.vErrors}.length`),(0,AN.extendErrors)(t)},()=>t.error())}function NN({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Rx(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,vt.stringify)(r)})}function zN(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")}fr.validSchemaType=zN;function jN({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)}}fr.validateKeywordUsage=jN});var Ix=Z(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.extendSubschemaMode=on.extendSubschemaData=on.getSubschema=void 0;var mr=he(),Ax=$e();function LN(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,mr._)`${t.schemaPath}${(0,mr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,mr._)`${t.schemaPath}${(0,mr.getProperty)(e)}${(0,mr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Ax.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')}on.getSubschema=LN;function DN(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:p}=e,w=a.let("data",(0,mr._)`${e.data}${(0,mr.getProperty)(r)}`,!0);c(w),t.errorPath=(0,mr.str)`${l}${(0,Ax.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,mr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof mr.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]}}on.extendSubschemaData=DN;function UN(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}on.extendSubschemaMode=UN});var yf=Z((PH,Ox)=>{"use strict";Ox.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 Nx=Z((AH,Cx)=>{"use strict";var sn=Cx.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(){};kc(e,n,o,t,"",t)};sn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};sn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};sn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};sn.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 kc(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 p=n[u];if(Array.isArray(p)){if(u in sn.arrayKeywords)for(var w=0;w<p.length;w++)kc(t,e,r,p[w],o+"/"+u+"/"+w,s,o,u,n,w)}else if(u in sn.propsKeywords){if(p&&typeof p=="object")for(var m in p)kc(t,e,r,p[m],o+"/"+u+"/"+MN(m),s,o,u,n,m)}else(u in sn.keywords||t.allKeys&&!(u in sn.skipKeywords))&&kc(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function MN(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ti=Z(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.getSchemaRefs=Rt.resolveUrl=Rt.normalizeId=Rt._getFullPath=Rt.getFullPath=Rt.inlineRef=void 0;var qN=$e(),ZN=yf(),BN=Nx(),FN=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function HN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!bf(t):e?zx(t)<=e:!1}Rt.inlineRef=HN;var VN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function bf(t){for(let e in t){if(VN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(bf)||typeof r=="object"&&bf(r))return!0}return!1}function zx(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!FN.has(r)&&(typeof t[r]=="object"&&(0,qN.eachItem)(t[r],n=>e+=zx(n)),e===1/0))return 1/0}return e}function jx(t,e="",r){r!==!1&&(e=zo(e));let n=t.parse(e);return Lx(t,n)}Rt.getFullPath=jx;function Lx(t,e){return t.serialize(e).split("#")[0]+"#"}Rt._getFullPath=Lx;var KN=/#\/?$/;function zo(t){return t?t.replace(KN,""):""}Rt.normalizeId=zo;function WN(t,e,r){return r=zo(r),t.resolve(e,r)}Rt.resolveUrl=WN;var GN=/^[a-z_][-a-z0-9._]*$/i;function JN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=zo(t[r]||e),s={"":o},i=jx(n,o,!1),a={},c=new Set;return BN(t,{allKeys:!0},(p,w,m,h)=>{if(h===void 0)return;let b=i+w,$=s[h];typeof p[r]=="string"&&($=E.call(this,p[r])),P.call(this,p.$anchor),P.call(this,p.$dynamicAnchor),s[w]=$;function E(z){let V=this.opts.uriResolver.resolve;if(z=zo($?V($,z):z),c.has(z))throw u(z);c.add(z);let Q=this.refs[z];return typeof Q=="string"&&(Q=this.refs[Q]),typeof Q=="object"?l(p,Q.schema,z):z!==zo(b)&&(z[0]==="#"?(l(p,a[z],z),a[z]=p):this.refs[z]=b),z}function P(z){if(typeof z=="string"){if(!GN.test(z))throw new Error(`invalid anchor "${z}"`);E.call(this,`#${z}`)}}}),a;function l(p,w,m){if(w!==void 0&&!ZN(p,w))throw u(m)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Rt.getSchemaRefs=JN});var oi=Z(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.getData=an.KeywordCxt=an.validateFunctionCode=void 0;var Zx=yx(),Dx=ei(),vf=uf(),$c=ei(),YN=$x(),ni=Px(),wf=Ix(),Y=he(),ce=Or(),XN=ti(),Cr=$e(),ri=Qs();function QN(t){if(Hx(t)&&(Vx(t),Fx(t))){rz(t);return}Bx(t,()=>(0,Zx.topBoolOrEmptySchema)(t))}an.validateFunctionCode=QN;function Bx({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Y._)`${ce.default.data}, ${ce.default.valCxt}`,n.$async,()=>{t.code((0,Y._)`"use strict"; ${Ux(r,o)}`),tz(t,o),t.code(s)}):t.func(e,(0,Y._)`${ce.default.data}, ${ez(o)}`,n.$async,()=>t.code(Ux(r,o)).code(s))}function ez(t){return(0,Y._)`{${ce.default.instancePath}="", ${ce.default.parentData}, ${ce.default.parentDataProperty}, ${ce.default.rootData}=${ce.default.data}${t.dynamicRef?(0,Y._)`, ${ce.default.dynamicAnchors}={}`:Y.nil}}={}`}function tz(t,e){t.if(ce.default.valCxt,()=>{t.var(ce.default.instancePath,(0,Y._)`${ce.default.valCxt}.${ce.default.instancePath}`),t.var(ce.default.parentData,(0,Y._)`${ce.default.valCxt}.${ce.default.parentData}`),t.var(ce.default.parentDataProperty,(0,Y._)`${ce.default.valCxt}.${ce.default.parentDataProperty}`),t.var(ce.default.rootData,(0,Y._)`${ce.default.valCxt}.${ce.default.rootData}`),e.dynamicRef&&t.var(ce.default.dynamicAnchors,(0,Y._)`${ce.default.valCxt}.${ce.default.dynamicAnchors}`)},()=>{t.var(ce.default.instancePath,(0,Y._)`""`),t.var(ce.default.parentData,(0,Y._)`undefined`),t.var(ce.default.parentDataProperty,(0,Y._)`undefined`),t.var(ce.default.rootData,ce.default.data),e.dynamicRef&&t.var(ce.default.dynamicAnchors,(0,Y._)`{}`)})}function rz(t){let{schema:e,opts:r,gen:n}=t;Bx(t,()=>{r.$comment&&e.$comment&&Wx(t),az(t),n.let(ce.default.vErrors,null),n.let(ce.default.errors,0),r.unevaluated&&nz(t),Kx(t),uz(t)})}function nz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Y._)`${r}.evaluated`),e.if((0,Y._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Y._)`${t.evaluated}.props`,(0,Y._)`undefined`)),e.if((0,Y._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Y._)`${t.evaluated}.items`,(0,Y._)`undefined`))}function Ux(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Y._)`/*# sourceURL=${r} */`:Y.nil}function oz(t,e){if(Hx(t)&&(Vx(t),Fx(t))){sz(t,e);return}(0,Zx.boolOrEmptySchema)(t,e)}function Fx({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 Hx(t){return typeof t.schema!="boolean"}function sz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Wx(t),cz(t),lz(t);let s=n.const("_errs",ce.default.errors);Kx(t,s),n.var(e,(0,Y._)`${s} === ${ce.default.errors}`)}function Vx(t){(0,Cr.checkUnknownRules)(t),iz(t)}function Kx(t,e){if(t.opts.jtd)return Mx(t,[],!1,e);let r=(0,Dx.getSchemaTypes)(t.schema),n=(0,Dx.coerceAndCheckDataType)(t,r);Mx(t,r,!n,e)}function iz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Cr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function az(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Cr.checkStrictMode)(t,"default is ignored in the schema root")}function cz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,XN.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function lz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Wx({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Y._)`${ce.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Y.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Y._)`${ce.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function uz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Y._)`${ce.default.errors} === 0`,()=>e.return(ce.default.data),()=>e.throw((0,Y._)`new ${o}(${ce.default.vErrors})`)):(e.assign((0,Y._)`${n}.errors`,ce.default.vErrors),s.unevaluated&&dz(t),e.return((0,Y._)`${ce.default.errors} === 0`))}function dz({gen:t,evaluated:e,props:r,items:n}){r instanceof Y.Name&&t.assign((0,Y._)`${e}.props`,r),n instanceof Y.Name&&t.assign((0,Y._)`${e}.items`,n)}function Mx(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,Cr.schemaHasRulesButRef)(s,u))){o.block(()=>Jx(t,"$ref",u.all.$ref.definition));return}c.jtd||pz(t,e),o.block(()=>{for(let w of u.rules)p(w);p(u.post)});function p(w){(0,vf.shouldUseGroup)(s,w)&&(w.type?(o.if((0,$c.checkDataType)(w.type,i,c.strictNumbers)),qx(t,w),e.length===1&&e[0]===w.type&&r&&(o.else(),(0,$c.reportTypeError)(t)),o.endIf()):qx(t,w),a||o.if((0,Y._)`${ce.default.errors} === ${n||0}`))}}function qx(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,YN.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,vf.shouldUseRule)(n,s)&&Jx(t,s.keyword,s.definition,e.type)})}function pz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(hz(t,e),t.opts.allowUnionTypes||fz(t,e),mz(t,t.dataTypes))}function hz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Gx(t.dataTypes,r)||_f(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),yz(t,e)}}function fz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&_f(t,"use allowUnionTypes to allow union type keyword")}function mz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,vf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>gz(e,i))&&_f(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function gz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Gx(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function yz(t,e){let r=[];for(let n of t.dataTypes)Gx(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function _f(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Cr.checkStrictMode)(t,e,t.opts.strictTypes)}var Sc=class{constructor(e,r,n){if((0,ni.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,Cr.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",Yx(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ni.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",ce.default.errors))}result(e,r,n){this.failResult((0,Y.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,Y.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,Y._)`${r} !== undefined && (${(0,Y.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?ri.reportExtraError:ri.reportError)(this,this.def.error,r)}$dataError(){(0,ri.reportError)(this,this.def.$dataError||ri.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ri.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=Y.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Y.nil,r=Y.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Y.or)((0,Y._)`${o} === undefined`,r)),e!==Y.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Y.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Y.or)(i(),a());function i(){if(n.length){if(!(r instanceof Y.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Y._)`${(0,$c.checkDataTypes)(c,r,s.opts.strictNumbers,$c.DataType.Wrong)}`}return Y.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Y._)`!${c}(${r})`}return Y.nil}}subschema(e,r){let n=(0,wf.getSubschema)(this.it,e);(0,wf.extendSubschemaData)(n,this.it,e),(0,wf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return oz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Cr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Cr.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,Y.Name)),!0}};an.KeywordCxt=Sc;function Jx(t,e,r,n){let o=new Sc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ni.funcKeywordCode)(o,r):"macro"in r?(0,ni.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ni.funcKeywordCode)(o,r)}var bz=/^\/(?:[^~]|~0|~1)*$/,wz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Yx(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ce.default.rootData;if(t[0]==="/"){if(!bz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ce.default.rootData}else{let l=wz.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,Y._)`${s}${(0,Y.getProperty)((0,Cr.unescapeJsonPointer)(l))}`,i=(0,Y._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}an.getData=Yx});var Tc=Z(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var xf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};kf.default=xf});var si=Z(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var $f=ti(),Sf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,$f.resolveUrl)(e,r,n),this.missingSchema=(0,$f.normalizeId)((0,$f.getFullPath)(e,this.missingRef))}};Tf.default=Sf});var Rc=Z(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.resolveSchema=Kt.getCompilingSchema=Kt.resolveRef=Kt.compileSchema=Kt.SchemaEnv=void 0;var nr=he(),vz=Tc(),Bn=Or(),or=ti(),Xx=$e(),_z=oi(),jo=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,or.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Kt.SchemaEnv=jo;function Rf(t){let e=Qx.call(this,t);if(e)return e;let r=(0,or.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new nr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:vz.default,code:(0,nr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Bn.default.data,parentData:Bn.default.parentData,parentDataProperty:Bn.default.parentDataProperty,dataNames:[Bn.default.data],dataPathArr:[nr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,nr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:nr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,nr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,_z.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Bn.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let m=new Function(`${Bn.default.self}`,`${Bn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:b}=l;m.evaluated={props:h instanceof nr.Name?void 0:h,items:b instanceof nr.Name?void 0:b,dynamicProps:h instanceof nr.Name,dynamicItems:b instanceof nr.Name},m.source&&(m.source.evaluated=(0,nr.stringify)(m.evaluated))}return t.validate=m,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}Kt.compileSchema=Rf;function xz(t,e,r){var n;r=(0,or.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Sz.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 jo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=kz.call(this,s)}Kt.resolveRef=xz;function kz(t){return(0,or.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Rf.call(this,t)}function Qx(t){for(let e of this._compilations)if($z(e,t))return e}Kt.getCompilingSchema=Qx;function $z(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Sz(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ec.call(this,t,e)}function Ec(t,e){let r=this.opts.uriResolver.parse(e),n=(0,or._getFullPath)(this.opts.uriResolver,r),o=(0,or.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Ef.call(this,r,t);let s=(0,or.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ec.call(this,t,i);return typeof a?.schema!="object"?void 0:Ef.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Rf.call(this,i),s===(0,or.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,or.resolveUrl)(this.opts.uriResolver,o,l)),new jo({schema:a,schemaId:c,root:t,baseId:o})}return Ef.call(this,r,i)}}Kt.resolveSchema=Ec;var Tz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ef(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,Xx.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!Tz.has(a)&&l&&(e=(0,or.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Xx.schemaHasRulesButRef)(r,this.RULES)){let a=(0,or.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ec.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new jo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var ek=Z((jH,Ez)=>{Ez.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 If=Z((LH,ik)=>{"use strict";var Rz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),rk=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),Pf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),nk=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Pz=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Af(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 Az=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function tk(t){return t.length=0,!0}function Iz(t,e,r){if(t.length){let n=Af(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Oz(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=Iz;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=tk}else{o.push(l);continue}}return o.length&&(a===tk?r.zone=o.join(""):i?n.push(o.join("")):n.push(Af(o))),r.address=n.join(""),r}function ok(t){if(Cz(t,":")<2)return{host:t,isIPV6:!1};let e=Oz(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 Cz(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Nz(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 zz={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},jz=/[@/?#:]/g,Lz=/[@/?#]/g;function sk(t,e){let r=e?Lz:jz;return r.lastIndex=0,t.replace(r,n=>zz[n])}function Dz(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(Pf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&nk(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function Uz(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(Pf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&nk(s)?e+=s:e+="%"+o,r+=2;continue}}Pz(t[r])?e+=t[r]:e+=escape(t[r])}return e}function Mz(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(Pf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function qz(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!rk(r)){let n=ok(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=sk(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}ik.exports={nonSimpleDomain:Az,recomposeAuthority:qz,reescapeHostDelimiters:sk,normalizePercentEncoding:Dz,normalizePathEncoding:Uz,escapePreservingEscapes:Mz,removeDotSegments:Nz,isIPv4:rk,isUUID:Rz,normalizeIPv6:ok,stringArrayToHexStripped:Af}});var dk=Z((DH,uk)=>{"use strict";var{isUUID:Zz}=If(),Bz=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Fz=["http","https","ws","wss","urn","urn:uuid"];function Hz(t){return Fz.indexOf(t)!==-1}function Of(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 ak(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function ck(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 Vz(t){return t.secure=Of(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Kz(t){if((t.port===(Of(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 Wz(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Bz);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=Cf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Gz(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=Cf(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 Jz(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Zz(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Yz(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var lk={scheme:"http",domainHost:!0,parse:ak,serialize:ck},Xz={scheme:"https",domainHost:lk.domainHost,parse:ak,serialize:ck},Pc={scheme:"ws",domainHost:!0,parse:Vz,serialize:Kz},Qz={scheme:"wss",domainHost:Pc.domainHost,parse:Pc.parse,serialize:Pc.serialize},ej={scheme:"urn",parse:Wz,serialize:Gz,skipNormalize:!0},tj={scheme:"urn:uuid",parse:Jz,serialize:Yz,skipNormalize:!0},Ac={http:lk,https:Xz,ws:Pc,wss:Qz,urn:ej,"urn:uuid":tj};Object.setPrototypeOf(Ac,null);function Cf(t){return t&&(Ac[t]||Ac[t.toLowerCase()])||void 0}uk.exports={wsIsSecure:Of,SCHEMES:Ac,isValidSchemeName:Hz,getSchemeHandler:Cf}});var gk=Z((UH,Cc)=>{"use strict";var{normalizeIPv6:rj,removeDotSegments:ii,recomposeAuthority:nj,normalizePercentEncoding:oj,normalizePathEncoding:sj,escapePreservingEscapes:ij,reescapeHostDelimiters:aj,isIPv4:cj,nonSimpleDomain:lj}=If(),{SCHEMES:uj,getSchemeHandler:hk}=dk();function dj(t,e){return typeof t=="string"?t=bj(t,e):typeof t=="object"&&(t=Oc(Fn(t,e),e)),t}function pj(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=Ic(t,n),{parsed:i,malformedAuthorityOrPort:a}=Ic(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=fk(o,i,n,!0);return n.skipEscape=!0,Fn(c,n)}function fk(t,e,r,n){let o={};return n||(t=Oc(Fn(t,r),r),e=Oc(Fn(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=ii(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=ii(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ii(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=ii(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 hj(t,e,r){let n=pk(t,r),o=pk(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Fn(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=hk(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=oj(r.path):(r.path=ij(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=nj(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=ii(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 fj=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,mj=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,gj=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function yj(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 Ic(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(mj);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(gj);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(fj);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=yj(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(cj(n.host)===!1){let w=rj(n.host);n.host=w.host.toLowerCase(),s=w.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=hk(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&lj(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=aj(unescape(n.host),s))),n.path&&(n.path=sj(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 Oc(t,e){return Ic(t,e).parsed}function bj(t,e){return mk(t,e).normalized}function mk(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Ic(t,e);return{normalized:n?t:Fn(r,e),malformedAuthorityOrPort:n}}function pk(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=mk(t,e);return n?void 0:r}if(typeof t=="object")return Fn(t,e)}var Nf={SCHEMES:uj,normalize:dj,resolve:pj,resolveComponent:fk,equal:hj,serialize:Fn,parse:Oc};Cc.exports=Nf;Cc.exports.default=Nf;Cc.exports.fastUri=Nf});var bk=Z(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var yk=gk();yk.code='require("ajv/dist/runtime/uri").default';zf.default=yk});var Tk=Z(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.CodeGen=at.Name=at.nil=at.stringify=at.str=at._=at.KeywordCxt=void 0;var wj=oi();Object.defineProperty(at,"KeywordCxt",{enumerable:!0,get:function(){return wj.KeywordCxt}});var Lo=he();Object.defineProperty(at,"_",{enumerable:!0,get:function(){return Lo._}});Object.defineProperty(at,"str",{enumerable:!0,get:function(){return Lo.str}});Object.defineProperty(at,"stringify",{enumerable:!0,get:function(){return Lo.stringify}});Object.defineProperty(at,"nil",{enumerable:!0,get:function(){return Lo.nil}});Object.defineProperty(at,"Name",{enumerable:!0,get:function(){return Lo.Name}});Object.defineProperty(at,"CodeGen",{enumerable:!0,get:function(){return Lo.CodeGen}});var vj=Tc(),kk=si(),_j=lf(),ai=Rc(),xj=he(),ci=ti(),Nc=ei(),Lf=$e(),wk=ek(),kj=bk(),$k=(t,e)=>new RegExp(t,e);$k.code="new RegExp";var $j=["removeAdditional","useDefaults","coerceTypes"],Sj=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Tj={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."},Ej={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},vk=200;function Rj(t){var e,r,n,o,s,i,a,c,l,u,p,w,m,h,b,$,E,P,z,V,Q,Je,Qe,Nr,zr;let It=t.strict,Wo=(e=t.code)===null||e===void 0?void 0:e.optimize,xi=Wo===!0||Wo===void 0?1:Wo||0,jr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:$k,Wn=(o=t.uriResolver)!==null&&o!==void 0?o:kj.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:It)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:It)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:It)!==null&&u!==void 0?u:"log",strictTuples:(w=(p=t.strictTuples)!==null&&p!==void 0?p:It)!==null&&w!==void 0?w:"log",strictRequired:(h=(m=t.strictRequired)!==null&&m!==void 0?m:It)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:xi,regExp:jr}:{optimize:xi,regExp:jr},loopRequired:(b=t.loopRequired)!==null&&b!==void 0?b:vk,loopEnum:($=t.loopEnum)!==null&&$!==void 0?$:vk,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(P=t.messages)!==null&&P!==void 0?P:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(V=t.schemaId)!==null&&V!==void 0?V:"$id",addUsedSchema:(Q=t.addUsedSchema)!==null&&Q!==void 0?Q:!0,validateSchema:(Je=t.validateSchema)!==null&&Je!==void 0?Je:!0,validateFormats:(Qe=t.validateFormats)!==null&&Qe!==void 0?Qe:!0,unicodeRegExp:(Nr=t.unicodeRegExp)!==null&&Nr!==void 0?Nr:!0,int32range:(zr=t.int32range)!==null&&zr!==void 0?zr:!0,uriResolver:Wn}}var li=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,...Rj(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new xj.ValueScope({scope:{},prefixes:Sj,es5:r,lines:n}),this.logger=Nj(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,_j.getRules)(),_k.call(this,Tj,e,"NOT SUPPORTED"),_k.call(this,Ej,e,"DEPRECATED","warn"),this._metaOpts=Oj.call(this),e.formats&&Aj.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Ij.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Pj.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=wk;n==="id"&&(o={...wk},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,p){await s.call(this,u.$schema);let w=this._addSchema(u,p);return w.validate||i.call(this,w)}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(p){if(!(p instanceof kk.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await l.call(this,u);this.refs[u]||await s.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,r)}async function l(u){let p=this._loading[u];if(p)return p;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,ci.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=xk.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ai.SchemaEnv({schema:{},schemaId:n});if(r=ai.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=xk.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,ci.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(jj.call(this,n,r),!r)return(0,Lf.eachItem)(n,s=>jf.call(this,s)),this;Dj.call(this,r);let o={...r,type:(0,Nc.getJSONTypes)(r.type),schemaType:(0,Nc.getJSONTypes)(r.schemaType)};return(0,Lf.eachItem)(n,o.type.length===0?s=>jf.call(this,s,o):s=>o.type.forEach(i=>jf.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]=Sk(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,ci.normalizeId)(i||n);let l=ci.getSchemaRefs.call(this,e,n);return c=new ai.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):ai.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{ai.compileSchema.call(this,e)}finally{this.opts=r}}};li.ValidationError=vj.default;li.MissingRefError=kk.default;at.default=li;function _k(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 xk(t){return t=(0,ci.normalizeId)(t),this.schemas[t]||this.refs[t]}function Pj(){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 Aj(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Ij(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 Oj(){let t={...this.opts};for(let e of $j)delete t[e];return t}var Cj={log(){},warn(){},error(){}};function Nj(t){if(t===!1)return Cj;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 zj=/^[a-z_$][a-z0-9_$:-]*$/i;function jj(t,e){let{RULES:r}=this;if((0,Lf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!zj.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 jf(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,Nc.getJSONTypes)(e.type),schemaType:(0,Nc.getJSONTypes)(e.schemaType)}};e.before?Lj.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 Lj(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 Dj(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Sk(e)),t.validateSchema=this.compile(e,!0))}var Uj={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Sk(t){return{anyOf:[t,Uj]}}});var Ek=Z(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var Mj={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Df.default=Mj});var Ik=Z(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.callRef=Hn.getValidate=void 0;var qj=si(),Rk=Vt(),Pt=he(),Do=Or(),Pk=Rc(),zc=$e(),Zj={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 p();let u=Pk.resolveRef.call(c,l,o,r);if(u===void 0)throw new qj.default(n.opts.uriResolver,o,r);if(u instanceof Pk.SchemaEnv)return w(u);return m(u);function p(){if(s===l)return jc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:l});return jc(t,(0,Pt._)`${h}.validate`,l,l.$async)}function w(h){let b=Ak(t,h);jc(t,b,h,h.$async)}function m(h){let b=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Pt.stringify)(h)}:{ref:h}),$=e.name("valid"),E=t.subschema({schema:h,dataTypes:[],schemaPath:Pt.nil,topSchemaRef:b,errSchemaPath:r},$);t.mergeEvaluated(E),t.ok($)}}};function Ak(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Pt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Hn.getValidate=Ak;function jc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Do.default.this:Pt.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,Pt._)`await ${(0,Rk.callValidateCode)(t,e,l)}`),m(e),i||o.assign(h,!0)},b=>{o.if((0,Pt._)`!(${b} instanceof ${s.ValidationError})`,()=>o.throw(b)),w(b),i||o.assign(h,!1)}),t.ok(h)}function p(){t.result((0,Rk.callValidateCode)(t,e,l),()=>m(e),()=>w(e))}function w(h){let b=(0,Pt._)`${h}.errors`;o.assign(Do.default.vErrors,(0,Pt._)`${Do.default.vErrors} === null ? ${b} : ${Do.default.vErrors}.concat(${b})`),o.assign(Do.default.errors,(0,Pt._)`${Do.default.vErrors}.length`)}function m(h){var b;if(!s.opts.unevaluated)return;let $=(b=r?.validate)===null||b===void 0?void 0:b.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=zc.mergeEvaluated.props(o,$.props,s.props));else{let E=o.var("props",(0,Pt._)`${h}.evaluated.props`);s.props=zc.mergeEvaluated.props(o,E,s.props,Pt.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=zc.mergeEvaluated.items(o,$.items,s.items));else{let E=o.var("items",(0,Pt._)`${h}.evaluated.items`);s.items=zc.mergeEvaluated.items(o,E,s.items,Pt.Name)}}}Hn.callRef=jc;Hn.default=Zj});var Ok=Z(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var Bj=Ek(),Fj=Ik(),Hj=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Bj.default,Fj.default];Uf.default=Hj});var Ck=Z(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Lc=he(),cn=Lc.operators,Dc={maximum:{okStr:"<=",ok:cn.LTE,fail:cn.GT},minimum:{okStr:">=",ok:cn.GTE,fail:cn.LT},exclusiveMaximum:{okStr:"<",ok:cn.LT,fail:cn.GTE},exclusiveMinimum:{okStr:">",ok:cn.GT,fail:cn.LTE}},Vj={message:({keyword:t,schemaCode:e})=>(0,Lc.str)`must be ${Dc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Lc._)`{comparison: ${Dc[t].okStr}, limit: ${e}}`},Kj={keyword:Object.keys(Dc),type:"number",schemaType:"number",$data:!0,error:Vj,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Lc._)`${r} ${Dc[e].fail} ${n} || isNaN(${r})`)}};Mf.default=Kj});var Nk=Z(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var ui=he(),Wj={message:({schemaCode:t})=>(0,ui.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ui._)`{multipleOf: ${t}}`},Gj={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Wj,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ui._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ui._)`${i} !== parseInt(${i})`;t.fail$data((0,ui._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};qf.default=Gj});var jk=Z(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});function zk(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}Zf.default=zk;zk.code='require("ajv/dist/runtime/ucs2length").default'});var Lk=Z(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var Vn=he(),Jj=$e(),Yj=jk(),Xj={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Vn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Vn._)`{limit: ${t}}`},Qj={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Xj,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Vn.operators.GT:Vn.operators.LT,i=o.opts.unicode===!1?(0,Vn._)`${r}.length`:(0,Vn._)`${(0,Jj.useFunc)(t.gen,Yj.default)}(${r})`;t.fail$data((0,Vn._)`${i} ${s} ${n}`)}};Bf.default=Qj});var Dk=Z(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var e1=Vt(),t1=$e(),Uo=he(),r1={message:({schemaCode:t})=>(0,Uo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Uo._)`{pattern: ${t}}`},n1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:r1,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,Uo._)`new RegExp`:(0,t1.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Uo._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Uo._)`!${u}`)}else{let c=(0,e1.usePattern)(t,o);t.fail$data((0,Uo._)`!${c}.test(${r})`)}}};Ff.default=n1});var Uk=Z(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var di=he(),o1={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,di.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,di._)`{limit: ${t}}`},s1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:o1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?di.operators.GT:di.operators.LT;t.fail$data((0,di._)`Object.keys(${r}).length ${o} ${n}`)}};Hf.default=s1});var Mk=Z(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var pi=Vt(),hi=he(),i1=$e(),a1={message:({params:{missingProperty:t}})=>(0,hi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,hi._)`{missingProperty: ${t}}`},c1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:a1,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 m=t.parentSchema.properties,{definedProperties:h}=t.it;for(let b of r)if(m?.[b]===void 0&&!h.has(b)){let $=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${b}" is not defined at "${$}" (strictRequired)`;(0,i1.checkStrictMode)(i,E,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(hi.nil,p);else for(let m of r)(0,pi.checkReportMissingProp)(t,m)}function u(){let m=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>w(m,h)),t.ok(h)}else e.if((0,pi.checkMissingProp)(t,r,m)),(0,pi.reportMissingProp)(t,m),e.else()}function p(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,pi.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function w(m,h){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(h,(0,pi.propertyInData)(e,o,m,a.ownProperties)),e.if((0,hi.not)(h),()=>{t.error(),e.break()})},hi.nil)}}};Vf.default=c1});var qk=Z(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var fi=he(),l1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,fi.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,fi._)`{limit: ${t}}`},u1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:l1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?fi.operators.GT:fi.operators.LT;t.fail$data((0,fi._)`${r}.length ${o} ${n}`)}};Kf.default=u1});var Uc=Z(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var Zk=yf();Zk.code='require("ajv/dist/runtime/equal").default';Wf.default=Zk});var Bk=Z(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var Gf=ei(),ct=he(),d1=$e(),p1=Uc(),h1={message:({params:{i:t,j:e}})=>(0,ct.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ct._)`{i: ${t}, j: ${e}}`},f1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:h1,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,Gf.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,ct._)`${i} === false`),t.ok(c);function u(){let h=e.let("i",(0,ct._)`${r}.length`),b=e.let("j");t.setParams({i:h,j:b}),e.assign(c,!0),e.if((0,ct._)`${h} > 1`,()=>(p()?w:m)(h,b))}function p(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function w(h,b){let $=e.name("item"),E=(0,Gf.checkDataTypes)(l,$,a.opts.strictNumbers,Gf.DataType.Wrong),P=e.const("indices",(0,ct._)`{}`);e.for((0,ct._)`;${h}--;`,()=>{e.let($,(0,ct._)`${r}[${h}]`),e.if(E,(0,ct._)`continue`),l.length>1&&e.if((0,ct._)`typeof ${$} == "string"`,(0,ct._)`${$} += "_"`),e.if((0,ct._)`typeof ${P}[${$}] == "number"`,()=>{e.assign(b,(0,ct._)`${P}[${$}]`),t.error(),e.assign(c,!1).break()}).code((0,ct._)`${P}[${$}] = ${h}`)})}function m(h,b){let $=(0,d1.useFunc)(e,p1.default),E=e.name("outer");e.label(E).for((0,ct._)`;${h}--;`,()=>e.for((0,ct._)`${b} = ${h}; ${b}--;`,()=>e.if((0,ct._)`${$}(${r}[${h}], ${r}[${b}])`,()=>{t.error(),e.assign(c,!1).break(E)})))}}};Jf.default=f1});var Fk=Z(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var Yf=he(),m1=$e(),g1=Uc(),y1={message:"must be equal to constant",params:({schemaCode:t})=>(0,Yf._)`{allowedValue: ${t}}`},b1={keyword:"const",$data:!0,error:y1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Yf._)`!${(0,m1.useFunc)(e,g1.default)}(${r}, ${o})`):t.fail((0,Yf._)`${s} !== ${r}`)}};Xf.default=b1});var Hk=Z(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var mi=he(),w1=$e(),v1=Uc(),_1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,mi._)`{allowedValues: ${t}}`},x1={keyword:"enum",schemaType:"array",$data:!0,error:_1,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,w1.useFunc)(e,v1.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);u=(0,mi.or)(...o.map((h,b)=>w(m,b)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,m=>e.if((0,mi._)`${l()}(${r}, ${m})`,()=>e.assign(u,!0).break()))}function w(m,h){let b=o[h];return typeof b=="object"&&b!==null?(0,mi._)`${l()}(${r}, ${m}[${h}])`:(0,mi._)`${r} === ${b}`}}};Qf.default=x1});var Vk=Z(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var k1=Ck(),$1=Nk(),S1=Lk(),T1=Dk(),E1=Uk(),R1=Mk(),P1=qk(),A1=Bk(),I1=Fk(),O1=Hk(),C1=[k1.default,$1.default,S1.default,T1.default,E1.default,R1.default,P1.default,A1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},I1.default,O1.default];em.default=C1});var rm=Z(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.validateAdditionalItems=void 0;var Kn=he(),tm=$e(),N1={message:({params:{len:t}})=>(0,Kn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Kn._)`{limit: ${t}}`},z1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:N1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,tm.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Kk(t,n)}};function Kk(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Kn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Kn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,tm.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Kn._)`${a} <= ${e.length}`);r.if((0,Kn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:tm.Type.Num},l),i.allErrors||r.if((0,Kn.not)(l),()=>r.break())})}}gi.validateAdditionalItems=Kk;gi.default=z1});var nm=Z(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.validateTuple=void 0;var Wk=he(),Mc=$e(),j1=Vt(),L1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Gk(t,"additionalItems",e);r.items=!0,!(0,Mc.alwaysValidSchema)(r,e)&&t.ok((0,j1.validateArray)(t))}};function Gk(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=Mc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Wk._)`${s}.length`);r.forEach((p,w)=>{(0,Mc.alwaysValidSchema)(a,p)||(n.if((0,Wk._)`${l} > ${w}`,()=>t.subschema({keyword:i,schemaProp:w,dataProp:w},c)),t.ok(c))});function u(p){let{opts:w,errSchemaPath:m}=a,h=r.length,b=h===p.minItems&&(h===p.maxItems||p[e]===!1);if(w.strictTuples&&!b){let $=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Mc.checkStrictMode)(a,$,w.strictTuples)}}}yi.validateTuple=Gk;yi.default=L1});var Jk=Z(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});var D1=nm(),U1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,D1.validateTuple)(t,"items")};om.default=U1});var Xk=Z(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var Yk=he(),M1=$e(),q1=Vt(),Z1=rm(),B1={message:({params:{len:t}})=>(0,Yk.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Yk._)`{limit: ${t}}`},F1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:B1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,M1.alwaysValidSchema)(n,e)&&(o?(0,Z1.validateAdditionalItems)(t,o):t.ok((0,q1.validateArray)(t)))}};sm.default=F1});var Qk=Z(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var Wt=he(),qc=$e(),H1={message:({params:{min:t,max:e}})=>e===void 0?(0,Wt.str)`must contain at least ${t} valid item(s)`:(0,Wt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Wt._)`{minContains: ${t}}`:(0,Wt._)`{minContains: ${t}, maxContains: ${e}}`},V1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:H1,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,Wt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,qc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,qc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,qc.alwaysValidSchema)(s,r)){let b=(0,Wt._)`${u} >= ${i}`;a!==void 0&&(b=(0,Wt._)`${b} && ${u} <= ${a}`),t.pass(b);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?m(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,Wt._)`${o}.length > 0`,w)):(e.let(p,!1),w()),t.result(p,()=>t.reset());function w(){let b=e.name("_valid"),$=e.let("count",0);m(b,()=>e.if(b,()=>h($)))}function m(b,$){e.forRange("i",0,u,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:qc.Type.Num,compositeRule:!0},b),$()})}function h(b){e.code((0,Wt._)`${b}++`),a===void 0?e.if((0,Wt._)`${b} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,Wt._)`${b} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,Wt._)`${b} >= ${i}`,()=>e.assign(p,!0)))}}};im.default=V1});var r$=Z(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.validateSchemaDeps=gr.validatePropertyDeps=gr.error=void 0;var am=he(),K1=$e(),bi=Vt();gr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,am.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,am._)`{property: ${t},
|
|
1822
1916
|
missingProperty: ${n},
|
|
1823
1917
|
depsCount: ${e},
|
|
1824
|
-
deps: ${r}}`};var V1={keyword:"dependencies",type:"object",schemaType:"object",error:yr.error,code(t){let[e,r]=K1(t);Xk(t,e),e$(t,r)}};function K1({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 Xk(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,wi.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,wi.checkReportMissingProp)(t,l)}):(r.if((0,im._)`${c} && (${(0,wi.checkMissingProp)(t,a,s)})`),(0,wi.reportMissingProp)(t,s),r.else())}}yr.validatePropertyDeps=Xk;function e$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,H1.alwaysValidSchema)(s,e[a])||(r.if((0,wi.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))}yr.validateSchemaDeps=e$;yr.default=V1});var n$=Z(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});var r$=he(),G1=$e(),W1={message:"property name must be valid",params:({params:t})=>(0,r$._)`{propertyName: ${t.propertyName}}`},J1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:W1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,G1.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,r$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};am.default=J1});var lm=Z(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var qc=Ht(),ir=he(),Y1=Cr(),Zc=$e(),Q1={message:"must NOT have additional properties",params:({params:t})=>(0,ir._)`{additionalProperty: ${t.additionalProperty}}`},X1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Q1,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,Zc.alwaysValidSchema)(i,r))return;let l=(0,qc.allSchemaProperties)(n.properties),u=(0,qc.allSchemaProperties)(n.patternProperties);p(),t.ok((0,ir._)`${s} === ${Y1.default.errors}`);function p(){e.forIn("key",o,k=>{!l.length&&!u.length?h(k):e.if(w(k),()=>h(k))})}function w(k){let E;if(l.length>8){let P=(0,Zc.schemaRefOrVal)(i,n.properties,"properties");E=(0,qc.isOwnProperty)(e,P,k)}else l.length?E=(0,ir.or)(...l.map(P=>(0,ir._)`${k} === ${P}`)):E=ir.nil;return u.length&&(E=(0,ir.or)(E,...u.map(P=>(0,ir._)`${(0,qc.usePattern)(t,P)}.test(${k})`))),(0,ir.not)(E)}function m(k){e.code((0,ir._)`delete ${o}[${k}]`)}function h(k){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(k);return}if(r===!1){t.setParams({additionalProperty:k}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Zc.alwaysValidSchema)(i,r)){let E=e.name("valid");c.removeAdditional==="failing"?(b(k,E,!1),e.if((0,ir.not)(E),()=>{t.reset(),m(k)})):(b(k,E),a||e.if((0,ir.not)(E),()=>e.break()))}}function b(k,E,P){let z={keyword:"additionalProperties",dataProp:k,dataPropType:Zc.Type.Str};P===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};cm.default=X1});var i$=Z(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});var eL=si(),o$=Ht(),um=$e(),s$=lm(),tL={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&&s$.default.code(new eL.KeywordCxt(s,s$.default,"additionalProperties"));let i=(0,o$.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=um.mergeEvaluated.props(e,(0,um.toHash)(i),s.props));let a=i.filter(p=>!(0,um.alwaysValidSchema)(s,r[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?u(p):(e.if((0,o$.propertyInData)(e,o,p,s.opts.ownProperties)),u(p),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&r[p].default!==void 0}function u(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};dm.default=tL});var u$=Z(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});var a$=Ht(),Bc=he(),c$=$e(),l$=$e(),rL={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,a$.allSchemaProperties)(r),c=a.filter(b=>(0,c$.alwaysValidSchema)(s,r[b]));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 Bc.Name)&&(s.props=(0,l$.evaluatedPropsToName)(e,s.props));let{props:p}=s;w();function w(){for(let b of a)l&&m(b),s.allErrors?h(b):(e.var(u,!0),h(b),e.if(u))}function m(b){for(let k in l)new RegExp(b).test(k)&&(0,c$.checkStrictMode)(s,`property ${k} matches pattern ${b} (use allowMatchingProperties)`)}function h(b){e.forIn("key",n,k=>{e.if((0,Bc._)`${(0,a$.usePattern)(t,b)}.test(${k})`,()=>{let E=c.includes(b);E||t.subschema({keyword:"patternProperties",schemaProp:b,dataProp:k,dataPropType:l$.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,Bc._)`${p}[${k}]`,!0):!E&&!s.allErrors&&e.if((0,Bc.not)(u),()=>e.break())})})}}};pm.default=rL});var d$=Z(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});var nL=$e(),oL={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,nL.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"}};hm.default=oL});var p$=Z(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});var sL=Ht(),iL={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:sL.validateUnion,error:{message:"must match a schema in anyOf"}};fm.default=iL});var h$=Z(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});var Fc=he(),aL=$e(),cL={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Fc._)`{passingSchemas: ${t.passing}}`},lL={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:cL,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,p)=>{let w;(0,aL.alwaysValidSchema)(o,u)?e.var(c,!0):w=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,Fc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Fc._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),w&&t.mergeEvaluated(w,Fc.Name)})})}}};mm.default=lL});var f$=Z(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});var uL=$e(),dL={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,uL.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};gm.default=dL});var y$=Z(ym=>{"use strict";Object.defineProperty(ym,"__esModule",{value:!0});var Hc=he(),g$=$e(),pL={message:({params:t})=>(0,Hc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Hc._)`{failingKeyword: ${t.ifClause}}`},hL={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:pL,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,g$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=m$(n,"then"),s=m$(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,Hc.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,p){return()=>{let w=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(w,i),p?e.assign(p,(0,Hc._)`${u}`):t.setParams({ifClause:u})}}}};function m$(t,e){let r=t.schema[e];return r!==void 0&&!(0,g$.alwaysValidSchema)(t,r)}ym.default=hL});var b$=Z(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});var fL=$e(),mL={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,fL.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};bm.default=mL});var w$=Z(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});var gL=tm(),yL=Wk(),bL=rm(),wL=Yk(),vL=Qk(),_L=t$(),xL=n$(),kL=lm(),$L=i$(),SL=u$(),TL=d$(),EL=p$(),RL=h$(),PL=f$(),AL=y$(),IL=b$();function OL(t=!1){let e=[TL.default,EL.default,RL.default,PL.default,AL.default,IL.default,xL.default,kL.default,_L.default,$L.default,SL.default];return t?e.push(yL.default,wL.default):e.push(gL.default,bL.default),e.push(vL.default),e}wm.default=OL});var v$=Z(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});var Ve=he(),CL={message:({schemaCode:t})=>(0,Ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ve._)`{format: ${t}}`},NL={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:CL,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;o?w():m();function w(){let h=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),b=r.const("fDef",(0,Ve._)`${h}[${i}]`),k=r.let("fType"),E=r.let("format");r.if((0,Ve._)`typeof ${b} == "object" && !(${b} instanceof RegExp)`,()=>r.assign(k,(0,Ve._)`${b}.type || "string"`).assign(E,(0,Ve._)`${b}.validate`),()=>r.assign(k,(0,Ve._)`"string"`).assign(E,b)),t.fail$data((0,Ve.or)(P(),z()));function P(){return c.strictSchema===!1?Ve.nil:(0,Ve._)`${i} && !${E}`}function z(){let V=u.$async?(0,Ve._)`(${b}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,Ve._)`${E}(${n})`,Q=(0,Ve._)`(typeof ${E} == "function" ? ${V} : ${E}.test(${n}))`;return(0,Ve._)`${E} && ${E} !== true && ${k} === ${e} && !${Q}`}}function m(){let h=p.formats[s];if(!h){P();return}if(h===!0)return;let[b,k,E]=z(h);b===e&&t.pass(V());function P(){if(c.strictSchema===!1){p.logger.warn(Q());return}throw new Error(Q());function Q(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function z(Q){let Ge=Q instanceof RegExp?(0,Ve.regexpCode)(Q):c.code.formats?(0,Ve._)`${c.code.formats}${(0,Ve.getProperty)(s)}`:void 0,rt=r.scopeValue("formats",{key:s,ref:Q,code:Ge});return typeof Q=="object"&&!(Q instanceof RegExp)?[Q.type||"string",Q.validate,(0,Ve._)`${rt}.validate`]:["string",Q,rt]}function V(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ve._)`await ${E}(${n})`}return typeof k=="function"?(0,Ve._)`${E}(${n})`:(0,Ve._)`${E}.test(${n})`}}}};vm.default=NL});var _$=Z(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});var zL=v$(),jL=[zL.default];_m.default=jL});var x$=Z(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.contentVocabulary=qo.metadataVocabulary=void 0;qo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];qo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var $$=Z(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});var LL=Ik(),DL=Hk(),UL=w$(),ML=_$(),k$=x$(),qL=[LL.default,DL.default,(0,UL.default)(),ML.default,k$.metadataVocabulary,k$.contentVocabulary];xm.default=qL});var T$=Z(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.DiscrError=void 0;var S$;(function(t){t.Tag="tag",t.Mapping="mapping"})(S$||(Vc.DiscrError=S$={}))});var R$=Z($m=>{"use strict";Object.defineProperty($m,"__esModule",{value:!0});var Zo=he(),km=T$(),E$=Ec(),ZL=ii(),BL=$e(),FL={message:({params:{discrError:t,tagName:e}})=>t===km.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Zo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},HL={keyword:"discriminator",type:"object",schemaType:"object",error:FL,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,Zo._)`${r}${(0,Zo.getProperty)(a)}`);e.if((0,Zo._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:km.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let m=w();e.if(!1);for(let h in m)e.elseIf((0,Zo._)`${l} === ${h}`),e.assign(c,p(m[h]));e.else(),t.error(!1,{discrError:km.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(m){let h=e.name("valid"),b=t.subschema({keyword:"oneOf",schemaProp:m},h);return t.mergeEvaluated(b,Zo.Name),h}function w(){var m;let h={},b=E(o),k=!0;for(let V=0;V<i.length;V++){let Q=i[V];if(Q?.$ref&&!(0,BL.schemaHasRulesButRef)(Q,s.self.RULES)){let rt=Q.$ref;if(Q=E$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,rt),Q instanceof E$.SchemaEnv&&(Q=Q.schema),Q===void 0)throw new ZL.default(s.opts.uriResolver,s.baseId,rt)}let Ge=(m=Q?.properties)===null||m===void 0?void 0:m[a];if(typeof Ge!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);k=k&&(b||E(Q)),P(Ge,V)}if(!k)throw new Error(`discriminator: "${a}" must be required`);return h;function E({required:V}){return Array.isArray(V)&&V.includes(a)}function P(V,Q){if(V.const)z(V.const,Q);else if(V.enum)for(let Ge of V.enum)z(Ge,Q);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(V,Q){if(typeof V!="string"||V in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[V]=Q}}}};$m.default=HL});var P$=Z((SV,VL)=>{VL.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 Tm=Z((De,Sm)=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.MissingRefError=De.ValidationError=De.CodeGen=De.Name=De.nil=De.stringify=De.str=De._=De.KeywordCxt=De.Ajv=void 0;var KL=Sk(),GL=$$(),WL=R$(),A$=P$(),JL=["/properties"],Kc="http://json-schema.org/draft-07/schema",Bo=class extends KL.default{_addVocabularies(){super._addVocabularies(),GL.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(WL.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(A$,JL):A$;this.addMetaSchema(e,Kc,!1),this.refs["http://json-schema.org/schema"]=Kc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Kc)?Kc:void 0)}};De.Ajv=Bo;Sm.exports=De=Bo;Sm.exports.Ajv=Bo;Object.defineProperty(De,"__esModule",{value:!0});De.default=Bo;var YL=si();Object.defineProperty(De,"KeywordCxt",{enumerable:!0,get:function(){return YL.KeywordCxt}});var Fo=he();Object.defineProperty(De,"_",{enumerable:!0,get:function(){return Fo._}});Object.defineProperty(De,"str",{enumerable:!0,get:function(){return Fo.str}});Object.defineProperty(De,"stringify",{enumerable:!0,get:function(){return Fo.stringify}});Object.defineProperty(De,"nil",{enumerable:!0,get:function(){return Fo.nil}});Object.defineProperty(De,"Name",{enumerable:!0,get:function(){return Fo.Name}});Object.defineProperty(De,"CodeGen",{enumerable:!0,get:function(){return Fo.CodeGen}});var QL=Sc();Object.defineProperty(De,"ValidationError",{enumerable:!0,get:function(){return QL.default}});var XL=ii();Object.defineProperty(De,"MissingRefError",{enumerable:!0,get:function(){return XL.default}})});var D$=Z(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.formatNames=wr.fastFormats=wr.fullFormats=void 0;function br(t,e){return{validate:t,compare:e}}wr.fullFormats={date:br(N$,Am),time:br(Rm(!0),Im),"date-time":br(I$(!0),j$),"iso-time":br(Rm(),z$),"iso-date-time":br(I$(),L$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:sD,"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:pD,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:iD,int32:{type:"number",validate:lD},int64:{type:"number",validate:uD},float:{type:"number",validate:C$},double:{type:"number",validate:C$},password:!0,binary:!0};wr.fastFormats={...wr.fullFormats,date:br(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Am),time:br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Im),"date-time":br(/^\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,j$),"iso-time":br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,z$),"iso-date-time":br(/^\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};wr.formatNames=Object.keys(wr.fullFormats);function eD(t){return t%4===0&&(t%100!==0||t%400===0)}var tD=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,rD=[0,31,28,31,30,31,30,31,31,30,31,30,31];function N$(t){let e=tD.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&&eD(r)?29:rD[n])}function Am(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Em=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Rm(t){return function(r){let n=Em.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 p=s-u*c,w=o-l*c-(p<0?1:0);return(w===23||w===-1)&&(p===59||p===-1)&&i<61}}function Im(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 z$(t,e){if(!(t&&e))return;let r=Em.exec(t),n=Em.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 Pm=/t|\s/i;function I$(t){let e=Rm(t);return function(n){let o=n.split(Pm);return o.length===2&&N$(o[0])&&e(o[1])}}function j$(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(Pm),[o,s]=e.split(Pm),i=Am(r,o);if(i!==void 0)return i||Im(n,s)}var nD=/\/|:/,oD=/^(?:[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 sD(t){return nD.test(t)&&oD.test(t)}var O$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function iD(t){return O$.lastIndex=0,O$.test(t)}var aD=-(2**31),cD=2**31-1;function lD(t){return Number.isInteger(t)&&t<=cD&&t>=aD}function uD(t){return Number.isInteger(t)}function C$(){return!0}var dD=/[^\\]\\Z/;function pD(t){if(dD.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var U$=Z(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.formatLimitDefinition=void 0;var hD=Tm(),ar=he(),cn=ar.operators,Gc={formatMaximum:{okStr:"<=",ok:cn.LTE,fail:cn.GT},formatMinimum:{okStr:">=",ok:cn.GTE,fail:cn.LT},formatExclusiveMaximum:{okStr:"<",ok:cn.LT,fail:cn.GTE},formatExclusiveMinimum:{okStr:">",ok:cn.GT,fail:cn.LTE}},fD={message:({keyword:t,schemaCode:e})=>(0,ar.str)`should be ${Gc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ar._)`{comparison: ${Gc[t].okStr}, limit: ${e}}`};Ho.formatLimitDefinition={keyword:Object.keys(Gc),type:"string",schemaType:"string",$data:!0,error:fD,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 hD.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let w=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,ar._)`${w}[${c.schemaCode}]`);t.fail$data((0,ar.or)((0,ar._)`typeof ${m} != "object"`,(0,ar._)`${m} instanceof RegExp`,(0,ar._)`typeof ${m}.compare != "function"`,p(m)))}function u(){let w=c.schema,m=a.formats[w];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${w}" does not define "compare" function`);let h=e.scopeValue("formats",{key:w,ref:m,code:i.code.formats?(0,ar._)`${i.code.formats}${(0,ar.getProperty)(w)}`:void 0});t.fail$data(p(h))}function p(w){return(0,ar._)`${w}.compare(${r}, ${n}) ${Gc[o].fail} 0`}},dependencies:["format"]};var mD=t=>(t.addKeyword(Ho.formatLimitDefinition),t);Ho.default=mD});var B$=Z((vi,Z$)=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var Vo=D$(),gD=U$(),Om=he(),M$=new Om.Name("fullFormats"),yD=new Om.Name("fastFormats"),Cm=(t,e={keywords:!0})=>{if(Array.isArray(e))return q$(t,e,Vo.fullFormats,M$),t;let[r,n]=e.mode==="fast"?[Vo.fastFormats,yD]:[Vo.fullFormats,M$],o=e.formats||Vo.formatNames;return q$(t,o,r,n),e.keywords&&(0,gD.default)(t),t};Cm.get=(t,e="full")=>{let n=(e==="fast"?Vo.fastFormats:Vo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function q$(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Om._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Z$.exports=vi=Cm;Object.defineProperty(vi,"__esModule",{value:!0});vi.default=Cm});function bD(){let t=new F$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,H$.default)(t),t}var F$,H$,Wc,V$=N(()=>{F$=al(Tm(),1),H$=al(B$(),1);Wc=class{constructor(e){this._ajv=e??bD()}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 Jc,K$=N(()=>{Po();Jc=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(w=>w.type==="tool_use").map(w=>w.id)),p=new Set(s.filter(w=>w.type==="tool_result").map(w=>w.toolUseId));if(u.size!==p.size||![...u].every(w=>p.has(w)))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},Fs,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},Ro,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 G$(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 W$(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 J$=N(()=>{});var Yc,Y$=N(()=>{ex();Po();V$();Os();K$();J$();Yc=class extends pc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Bs.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 Wc,this.setRequestHandler(Vp,n=>this._oninitialize(n)),this.setNotificationHandler(Kp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(eh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Bs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Jc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=X_(this._capabilities,e)}setRequestHandler(e,r){let o=Jr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=ko(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=Wr(Eo,c);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new G(X.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:p}=u.data,w=await Promise.resolve(r(c,l));if(p.task){let h=Wr(So,w);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new G(X.InvalidParams,`Invalid task creation result: ${b}`)}return h.data}let m=Wr(ec,w);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new G(X.InvalidParams,`Invalid tools/call result: ${h}`)}return m.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){W$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&G$(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:Xv.includes(r)?r:qp,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"},Da)}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(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))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},th,r):this.request({method:"sampling/createMessage",params:e},Fs,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},Ro,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},Ro,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new G(X.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof G?i:new G(X.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},rh,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 Nm(t){return!!t&&typeof t=="object"&&X$ in t}function eS(t){return t[X$]?.complete}var X$,Q$,tS=N(()=>{X$=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Q$||(Q$={}))});var rS=N(()=>{});function vD(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"),!wD.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 _D(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 zm(t){let e=vD(t);return _D(t,e.warnings),e.isValid}var wD,nS=N(()=>{wD=/^[A-Za-z0-9._-]{1,128}$/});var Qc,oS=N(()=>{Qc=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 aS(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function cS(t){return"_def"in t||"_zod"in t||aS(t)}function jm(t){return typeof t!="object"||t===null||cS(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(aS)}function sS(t){if(t){if(jm(t))return Ln(t);if(!cS(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function kD(t){let e=Jr(t);return e?Object.entries(e).map(([r,n])=>{let o=$v(n),s=Sv(n);return{name:r,description:o,required:!s}}):[]}function ln(t){let r=Jr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ko(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function iS(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Xc,xD,_i,lS=N(()=>{Y$();Os();Uh();Po();tS();rS();nS();oS();io();Xc=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 Yc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Qc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ln(Xa)),this.server.assertCanSetRequestHandler(ln(Eo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Xa,()=>({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=xo(r.inputSchema);return o?jh(o,{strictUnions:!0,pipeStrategy:"input"}):xD})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=xo(r.outputSchema);o&&(n.outputSchema=jh(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Eo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new G(X.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new G(X.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 G(X.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new G(X.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 G&&n.code===X.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=xo(e.inputSchema)??e.inputSchema,i=await Ia(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Oa(a);throw new G(X.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 G(X.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=xo(e.outputSchema),s=await Ia(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Oa(i);throw new G(X.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(w=>setTimeout(w,u));let p=await n.taskStore.getTask(c);if(!p)throw new G(X.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ln(tc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(tc,async e=>{switch(e.params.ref.type){case"ref/prompt":return m_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return g_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new G(X.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new G(X.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new G(X.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return _i;let s=Jr(n.argsSchema)?.[e.params.argument.name];if(!Nm(s))return _i;let i=eS(s);if(!i)return _i;let a=await i(e.params.argument.value,e.params.context);return iS(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 _i;throw new G(X.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return _i;let s=await o(e.params.argument.value,e.params.context);return iS(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ln(Ga)),this.server.assertCanSetRequestHandler(ln(Wa)),this.server.assertCanSetRequestHandler(ln(Ja)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ga,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(Wa,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ja,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new G(X.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 G(X.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ln(Ya)),this.server.assertCanSetRequestHandler(ln(Qa)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ya,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?kD(r.argsSchema):void 0}))})),this.server.setRequestHandler(Qa,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new G(X.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new G(X.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=xo(n.argsSchema),s=await Ia(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Oa(c);throw new G(X.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:Ln(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=Ln(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 xt?c._def?.innerType:c;return Nm(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){zm(e);let u={title:r,description:n,inputSchema:sS(o),outputSchema:sS(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:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&zm(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Ln(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Ln(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.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(jm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!jm(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()}},xD={type:"object",properties:{}};_i={completion:{values:[],hasMore:!1}}});function SD(t){return a_.parse(JSON.parse(t))}function uS(t){return JSON.stringify(t)+`
|
|
1825
|
-
`}var
|
|
1826
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
1918
|
+
deps: ${r}}`};var W1={keyword:"dependencies",type:"object",schemaType:"object",error:gr.error,code(t){let[e,r]=G1(t);e$(t,e),t$(t,r)}};function G1({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 e$(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,bi.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,bi.checkReportMissingProp)(t,l)}):(r.if((0,am._)`${c} && (${(0,bi.checkMissingProp)(t,a,s)})`),(0,bi.reportMissingProp)(t,s),r.else())}}gr.validatePropertyDeps=e$;function t$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,K1.alwaysValidSchema)(s,e[a])||(r.if((0,bi.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))}gr.validateSchemaDeps=t$;gr.default=W1});var o$=Z(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var n$=he(),J1=$e(),Y1={message:"property name must be valid",params:({params:t})=>(0,n$._)`{propertyName: ${t.propertyName}}`},X1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Y1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,J1.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,n$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};cm.default=X1});var um=Z(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});var Zc=Vt(),sr=he(),Q1=Or(),Bc=$e(),eL={message:"must NOT have additional properties",params:({params:t})=>(0,sr._)`{additionalProperty: ${t.additionalProperty}}`},tL={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:eL,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,Bc.alwaysValidSchema)(i,r))return;let l=(0,Zc.allSchemaProperties)(n.properties),u=(0,Zc.allSchemaProperties)(n.patternProperties);p(),t.ok((0,sr._)`${s} === ${Q1.default.errors}`);function p(){e.forIn("key",o,$=>{!l.length&&!u.length?h($):e.if(w($),()=>h($))})}function w($){let E;if(l.length>8){let P=(0,Bc.schemaRefOrVal)(i,n.properties,"properties");E=(0,Zc.isOwnProperty)(e,P,$)}else l.length?E=(0,sr.or)(...l.map(P=>(0,sr._)`${$} === ${P}`)):E=sr.nil;return u.length&&(E=(0,sr.or)(E,...u.map(P=>(0,sr._)`${(0,Zc.usePattern)(t,P)}.test(${$})`))),(0,sr.not)(E)}function m($){e.code((0,sr._)`delete ${o}[${$}]`)}function h($){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m($);return}if(r===!1){t.setParams({additionalProperty:$}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Bc.alwaysValidSchema)(i,r)){let E=e.name("valid");c.removeAdditional==="failing"?(b($,E,!1),e.if((0,sr.not)(E),()=>{t.reset(),m($)})):(b($,E),a||e.if((0,sr.not)(E),()=>e.break()))}}function b($,E,P){let z={keyword:"additionalProperties",dataProp:$,dataPropType:Bc.Type.Str};P===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,E)}}};lm.default=tL});var a$=Z(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});var rL=oi(),s$=Vt(),dm=$e(),i$=um(),nL={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&&i$.default.code(new rL.KeywordCxt(s,i$.default,"additionalProperties"));let i=(0,s$.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=dm.mergeEvaluated.props(e,(0,dm.toHash)(i),s.props));let a=i.filter(p=>!(0,dm.alwaysValidSchema)(s,r[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?u(p):(e.if((0,s$.propertyInData)(e,o,p,s.opts.ownProperties)),u(p),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&r[p].default!==void 0}function u(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};pm.default=nL});var d$=Z(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});var c$=Vt(),Fc=he(),l$=$e(),u$=$e(),oL={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,c$.allSchemaProperties)(r),c=a.filter(b=>(0,l$.alwaysValidSchema)(s,r[b]));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 Fc.Name)&&(s.props=(0,u$.evaluatedPropsToName)(e,s.props));let{props:p}=s;w();function w(){for(let b of a)l&&m(b),s.allErrors?h(b):(e.var(u,!0),h(b),e.if(u))}function m(b){for(let $ in l)new RegExp(b).test($)&&(0,l$.checkStrictMode)(s,`property ${$} matches pattern ${b} (use allowMatchingProperties)`)}function h(b){e.forIn("key",n,$=>{e.if((0,Fc._)`${(0,c$.usePattern)(t,b)}.test(${$})`,()=>{let E=c.includes(b);E||t.subschema({keyword:"patternProperties",schemaProp:b,dataProp:$,dataPropType:u$.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,Fc._)`${p}[${$}]`,!0):!E&&!s.allErrors&&e.if((0,Fc.not)(u),()=>e.break())})})}}};hm.default=oL});var p$=Z(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});var sL=$e(),iL={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,sL.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"}};fm.default=iL});var h$=Z(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});var aL=Vt(),cL={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:aL.validateUnion,error:{message:"must match a schema in anyOf"}};mm.default=cL});var f$=Z(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});var Hc=he(),lL=$e(),uL={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Hc._)`{passingSchemas: ${t.passing}}`},dL={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:uL,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,p)=>{let w;(0,lL.alwaysValidSchema)(o,u)?e.var(c,!0):w=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,Hc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Hc._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),w&&t.mergeEvaluated(w,Hc.Name)})})}}};gm.default=dL});var m$=Z(ym=>{"use strict";Object.defineProperty(ym,"__esModule",{value:!0});var pL=$e(),hL={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,pL.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};ym.default=hL});var b$=Z(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});var Vc=he(),y$=$e(),fL={message:({params:t})=>(0,Vc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Vc._)`{failingKeyword: ${t.ifClause}}`},mL={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:fL,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,y$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=g$(n,"then"),s=g$(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,Vc.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,p){return()=>{let w=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(w,i),p?e.assign(p,(0,Vc._)`${u}`):t.setParams({ifClause:u})}}}};function g$(t,e){let r=t.schema[e];return r!==void 0&&!(0,y$.alwaysValidSchema)(t,r)}bm.default=mL});var w$=Z(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});var gL=$e(),yL={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,gL.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};wm.default=yL});var v$=Z(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});var bL=rm(),wL=Jk(),vL=nm(),_L=Xk(),xL=Qk(),kL=r$(),$L=o$(),SL=um(),TL=a$(),EL=d$(),RL=p$(),PL=h$(),AL=f$(),IL=m$(),OL=b$(),CL=w$();function NL(t=!1){let e=[RL.default,PL.default,AL.default,IL.default,OL.default,CL.default,$L.default,SL.default,kL.default,TL.default,EL.default];return t?e.push(wL.default,_L.default):e.push(bL.default,vL.default),e.push(xL.default),e}vm.default=NL});var _$=Z(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});var Ve=he(),zL={message:({schemaCode:t})=>(0,Ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ve._)`{format: ${t}}`},jL={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:zL,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;o?w():m();function w(){let h=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),b=r.const("fDef",(0,Ve._)`${h}[${i}]`),$=r.let("fType"),E=r.let("format");r.if((0,Ve._)`typeof ${b} == "object" && !(${b} instanceof RegExp)`,()=>r.assign($,(0,Ve._)`${b}.type || "string"`).assign(E,(0,Ve._)`${b}.validate`),()=>r.assign($,(0,Ve._)`"string"`).assign(E,b)),t.fail$data((0,Ve.or)(P(),z()));function P(){return c.strictSchema===!1?Ve.nil:(0,Ve._)`${i} && !${E}`}function z(){let V=u.$async?(0,Ve._)`(${b}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,Ve._)`${E}(${n})`,Q=(0,Ve._)`(typeof ${E} == "function" ? ${V} : ${E}.test(${n}))`;return(0,Ve._)`${E} && ${E} !== true && ${$} === ${e} && !${Q}`}}function m(){let h=p.formats[s];if(!h){P();return}if(h===!0)return;let[b,$,E]=z(h);b===e&&t.pass(V());function P(){if(c.strictSchema===!1){p.logger.warn(Q());return}throw new Error(Q());function Q(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function z(Q){let Je=Q instanceof RegExp?(0,Ve.regexpCode)(Q):c.code.formats?(0,Ve._)`${c.code.formats}${(0,Ve.getProperty)(s)}`:void 0,Qe=r.scopeValue("formats",{key:s,ref:Q,code:Je});return typeof Q=="object"&&!(Q instanceof RegExp)?[Q.type||"string",Q.validate,(0,Ve._)`${Qe}.validate`]:["string",Q,Qe]}function V(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ve._)`await ${E}(${n})`}return typeof $=="function"?(0,Ve._)`${E}(${n})`:(0,Ve._)`${E}.test(${n})`}}}};_m.default=jL});var x$=Z(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});var LL=_$(),DL=[LL.default];xm.default=DL});var k$=Z(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.contentVocabulary=Mo.metadataVocabulary=void 0;Mo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Mo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var S$=Z(km=>{"use strict";Object.defineProperty(km,"__esModule",{value:!0});var UL=Ok(),ML=Vk(),qL=v$(),ZL=x$(),$$=k$(),BL=[UL.default,ML.default,(0,qL.default)(),ZL.default,$$.metadataVocabulary,$$.contentVocabulary];km.default=BL});var E$=Z(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.DiscrError=void 0;var T$;(function(t){t.Tag="tag",t.Mapping="mapping"})(T$||(Kc.DiscrError=T$={}))});var P$=Z(Sm=>{"use strict";Object.defineProperty(Sm,"__esModule",{value:!0});var qo=he(),$m=E$(),R$=Rc(),FL=si(),HL=$e(),VL={message:({params:{discrError:t,tagName:e}})=>t===$m.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,qo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},KL={keyword:"discriminator",type:"object",schemaType:"object",error:VL,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,qo._)`${r}${(0,qo.getProperty)(a)}`);e.if((0,qo._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:$m.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let m=w();e.if(!1);for(let h in m)e.elseIf((0,qo._)`${l} === ${h}`),e.assign(c,p(m[h]));e.else(),t.error(!1,{discrError:$m.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(m){let h=e.name("valid"),b=t.subschema({keyword:"oneOf",schemaProp:m},h);return t.mergeEvaluated(b,qo.Name),h}function w(){var m;let h={},b=E(o),$=!0;for(let V=0;V<i.length;V++){let Q=i[V];if(Q?.$ref&&!(0,HL.schemaHasRulesButRef)(Q,s.self.RULES)){let Qe=Q.$ref;if(Q=R$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Qe),Q instanceof R$.SchemaEnv&&(Q=Q.schema),Q===void 0)throw new FL.default(s.opts.uriResolver,s.baseId,Qe)}let Je=(m=Q?.properties)===null||m===void 0?void 0:m[a];if(typeof Je!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(b||E(Q)),P(Je,V)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return h;function E({required:V}){return Array.isArray(V)&&V.includes(a)}function P(V,Q){if(V.const)z(V.const,Q);else if(V.enum)for(let Je of V.enum)z(Je,Q);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(V,Q){if(typeof V!="string"||V in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[V]=Q}}}};Sm.default=KL});var A$=Z((EV,WL)=>{WL.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 Em=Z((De,Tm)=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.MissingRefError=De.ValidationError=De.CodeGen=De.Name=De.nil=De.stringify=De.str=De._=De.KeywordCxt=De.Ajv=void 0;var GL=Tk(),JL=S$(),YL=P$(),I$=A$(),XL=["/properties"],Wc="http://json-schema.org/draft-07/schema",Zo=class extends GL.default{_addVocabularies(){super._addVocabularies(),JL.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(YL.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(I$,XL):I$;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)}};De.Ajv=Zo;Tm.exports=De=Zo;Tm.exports.Ajv=Zo;Object.defineProperty(De,"__esModule",{value:!0});De.default=Zo;var QL=oi();Object.defineProperty(De,"KeywordCxt",{enumerable:!0,get:function(){return QL.KeywordCxt}});var Bo=he();Object.defineProperty(De,"_",{enumerable:!0,get:function(){return Bo._}});Object.defineProperty(De,"str",{enumerable:!0,get:function(){return Bo.str}});Object.defineProperty(De,"stringify",{enumerable:!0,get:function(){return Bo.stringify}});Object.defineProperty(De,"nil",{enumerable:!0,get:function(){return Bo.nil}});Object.defineProperty(De,"Name",{enumerable:!0,get:function(){return Bo.Name}});Object.defineProperty(De,"CodeGen",{enumerable:!0,get:function(){return Bo.CodeGen}});var eD=Tc();Object.defineProperty(De,"ValidationError",{enumerable:!0,get:function(){return eD.default}});var tD=si();Object.defineProperty(De,"MissingRefError",{enumerable:!0,get:function(){return tD.default}})});var U$=Z(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.formatNames=br.fastFormats=br.fullFormats=void 0;function yr(t,e){return{validate:t,compare:e}}br.fullFormats={date:yr(z$,Im),time:yr(Pm(!0),Om),"date-time":yr(O$(!0),L$),"iso-time":yr(Pm(),j$),"iso-date-time":yr(O$(),D$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:aD,"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:fD,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:cD,int32:{type:"number",validate:dD},int64:{type:"number",validate:pD},float:{type:"number",validate:N$},double:{type:"number",validate:N$},password:!0,binary:!0};br.fastFormats={...br.fullFormats,date:yr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Im),time:yr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Om),"date-time":yr(/^\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,L$),"iso-time":yr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,j$),"iso-date-time":yr(/^\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,D$),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};br.formatNames=Object.keys(br.fullFormats);function rD(t){return t%4===0&&(t%100!==0||t%400===0)}var nD=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,oD=[0,31,28,31,30,31,30,31,31,30,31,30,31];function z$(t){let e=nD.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&&rD(r)?29:oD[n])}function Im(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Rm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Pm(t){return function(r){let n=Rm.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 p=s-u*c,w=o-l*c-(p<0?1:0);return(w===23||w===-1)&&(p===59||p===-1)&&i<61}}function Om(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 j$(t,e){if(!(t&&e))return;let r=Rm.exec(t),n=Rm.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 Am=/t|\s/i;function O$(t){let e=Pm(t);return function(n){let o=n.split(Am);return o.length===2&&z$(o[0])&&e(o[1])}}function L$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function D$(t,e){if(!(t&&e))return;let[r,n]=t.split(Am),[o,s]=e.split(Am),i=Im(r,o);if(i!==void 0)return i||Om(n,s)}var sD=/\/|:/,iD=/^(?:[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 aD(t){return sD.test(t)&&iD.test(t)}var C$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function cD(t){return C$.lastIndex=0,C$.test(t)}var lD=-(2**31),uD=2**31-1;function dD(t){return Number.isInteger(t)&&t<=uD&&t>=lD}function pD(t){return Number.isInteger(t)}function N$(){return!0}var hD=/[^\\]\\Z/;function fD(t){if(hD.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var M$=Z(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.formatLimitDefinition=void 0;var mD=Em(),ir=he(),ln=ir.operators,Gc={formatMaximum:{okStr:"<=",ok:ln.LTE,fail:ln.GT},formatMinimum:{okStr:">=",ok:ln.GTE,fail:ln.LT},formatExclusiveMaximum:{okStr:"<",ok:ln.LT,fail:ln.GTE},formatExclusiveMinimum:{okStr:">",ok:ln.GT,fail:ln.LTE}},gD={message:({keyword:t,schemaCode:e})=>(0,ir.str)`should be ${Gc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ir._)`{comparison: ${Gc[t].okStr}, limit: ${e}}`};Fo.formatLimitDefinition={keyword:Object.keys(Gc),type:"string",schemaType:"string",$data:!0,error:gD,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 mD.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let w=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,ir._)`${w}[${c.schemaCode}]`);t.fail$data((0,ir.or)((0,ir._)`typeof ${m} != "object"`,(0,ir._)`${m} instanceof RegExp`,(0,ir._)`typeof ${m}.compare != "function"`,p(m)))}function u(){let w=c.schema,m=a.formats[w];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${w}" does not define "compare" function`);let h=e.scopeValue("formats",{key:w,ref:m,code:i.code.formats?(0,ir._)`${i.code.formats}${(0,ir.getProperty)(w)}`:void 0});t.fail$data(p(h))}function p(w){return(0,ir._)`${w}.compare(${r}, ${n}) ${Gc[o].fail} 0`}},dependencies:["format"]};var yD=t=>(t.addKeyword(Fo.formatLimitDefinition),t);Fo.default=yD});var F$=Z((wi,B$)=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});var Ho=U$(),bD=M$(),Cm=he(),q$=new Cm.Name("fullFormats"),wD=new Cm.Name("fastFormats"),Nm=(t,e={keywords:!0})=>{if(Array.isArray(e))return Z$(t,e,Ho.fullFormats,q$),t;let[r,n]=e.mode==="fast"?[Ho.fastFormats,wD]:[Ho.fullFormats,q$],o=e.formats||Ho.formatNames;return Z$(t,o,r,n),e.keywords&&(0,bD.default)(t),t};Nm.get=(t,e="full")=>{let n=(e==="fast"?Ho.fastFormats:Ho.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Z$(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Cm._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}B$.exports=wi=Nm;Object.defineProperty(wi,"__esModule",{value:!0});wi.default=Nm});function vD(){let t=new H$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,V$.default)(t),t}var H$,V$,Jc,K$=O(()=>{H$=cl(Em(),1),V$=cl(F$(),1);Jc=class{constructor(e){this._ajv=e??vD()}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 Yc,W$=O(()=>{Ro();Yc=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(w=>w.type==="tool_use").map(w=>w.id)),p=new Set(s.filter(w=>w.type==="tool_result").map(w=>w.toolUseId));if(u.size!==p.size||![...u].every(w=>p.has(w)))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},Bs,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},Eo,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 G$(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 J$(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 Y$=O(()=>{});var Xc,X$=O(()=>{tx();Ro();K$();Is();W$();Y$();Xc=class extends hc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Zs.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 Jc,this.setRequestHandler(Kp,n=>this._oninitialize(n)),this.setNotificationHandler(Wp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(th,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Zs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Yc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ex(this._capabilities,e)}setRequestHandler(e,r){let o=Yr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=xo(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=Jr(To,c);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new G(ee.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:p}=u.data,w=await Promise.resolve(r(c,l));if(p.task){let h=Jr($o,w);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new G(ee.InvalidParams,`Invalid task creation result: ${b}`)}return h.data}let m=Jr(tc,w);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new G(ee.InvalidParams,`Invalid tools/call result: ${h}`)}return m.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){J$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&G$(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:e_.includes(r)?r:Zp,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(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))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},rh,r):this.request({method:"sampling/createMessage",params:e},Bs,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},Eo,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},Eo,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new G(ee.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof G?i:new G(ee.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},nh,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 zm(t){return!!t&&typeof t=="object"&&eS in t}function tS(t){return t[eS]?.complete}var eS,Q$,rS=O(()=>{eS=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Q$||(Q$={}))});var nS=O(()=>{});function xD(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"),!_D.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 kD(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 jm(t){let e=xD(t);return kD(t,e.warnings),e.isValid}var _D,oS=O(()=>{_D=/^[A-Za-z0-9._-]{1,128}$/});var Qc,sS=O(()=>{Qc=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 cS(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function lS(t){return"_def"in t||"_zod"in t||cS(t)}function Lm(t){return typeof t!="object"||t===null||lS(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(cS)}function iS(t){if(t){if(Lm(t))return jn(t);if(!lS(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function SD(t){let e=Yr(t);return e?Object.entries(e).map(([r,n])=>{let o=Sv(n),s=Tv(n);return{name:r,description:o,required:!s}}):[]}function un(t){let r=Yr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=xo(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function aS(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var el,$D,vi,uS=O(()=>{X$();Is();Mh();Ro();rS();nS();oS();sS();so();el=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 Xc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Qc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(un(ec)),this.server.assertCanSetRequestHandler(un(To)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ec,()=>({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=_o(r.inputSchema);return o?Lh(o,{strictUnions:!0,pipeStrategy:"input"}):$D})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=_o(r.outputSchema);o&&(n.outputSchema=Lh(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(To,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new G(ee.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new G(ee.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 G(ee.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new G(ee.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 G&&n.code===ee.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=_o(e.inputSchema)??e.inputSchema,i=await Oa(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ca(a);throw new G(ee.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 G(ee.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=_o(e.outputSchema),s=await Oa(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ca(i);throw new G(ee.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(w=>setTimeout(w,u));let p=await n.taskStore.getTask(c);if(!p)throw new G(ee.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(un(rc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(rc,async e=>{switch(e.params.ref.type){case"ref/prompt":return g_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return y_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new G(ee.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new G(ee.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new G(ee.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return vi;let s=Yr(n.argsSchema)?.[e.params.argument.name];if(!zm(s))return vi;let i=tS(s);if(!i)return vi;let a=await i(e.params.argument.value,e.params.context);return aS(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 vi;throw new G(ee.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return vi;let s=await o(e.params.argument.value,e.params.context);return aS(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(un(Ga)),this.server.assertCanSetRequestHandler(un(Ja)),this.server.assertCanSetRequestHandler(un(Ya)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ga,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(Ja,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ya,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new G(ee.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 G(ee.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(un(Xa)),this.server.assertCanSetRequestHandler(un(Qa)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Xa,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?SD(r.argsSchema):void 0}))})),this.server.setRequestHandler(Qa,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new G(ee.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new G(ee.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=_o(n.argsSchema),s=await Oa(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Ca(c);throw new G(ee.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:jn(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=jn(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 xt?c._def?.innerType:c;return zm(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){jm(e);let u={title:r,description:n,inputSchema:iS(o),outputSchema:iS(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:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&jm(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=jn(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=jn(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.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(Lm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Lm(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()}},$D={type:"object",properties:{}};vi={completion:{values:[],hasMore:!1}}});function ED(t){return c_.parse(JSON.parse(t))}function dS(t){return JSON.stringify(t)+`
|
|
1919
|
+
`}var TD,tl,pS=O(()=>{Ro();TD=10*1024*1024,tl=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??TD}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(`
|
|
1920
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),ED(r)}clear(){this._buffer=void 0}}});import hS from"node:process";var rl,fS=O(()=>{pS();rl=class{constructor(e=hS.stdin,r=hS.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 tl({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=dS(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var mS,gS=O(()=>{mS=[]});var SS={};Jo(SS,{AUTHORING_MCP_SERVER_NAME:()=>_S,AUTHORING_MCP_SERVER_VERSION:()=>xS,AUTHORING_RESOURCES:()=>ID,AUTHORING_TOOLS:()=>AD,AUTHORING_TOOLS_PUBLIC:()=>$S,buildAuthoringMcpServer:()=>kS,runAuthoringMcpServer:()=>OD});import{promises as RD}from"node:fs";import{resolve as yS}from"node:path";function vS(){return wS??=import("../mcp/grounding.js").then(e=>e,()=>null),wS}function Ke(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function PD(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 kS(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let m=await Yt(t.baseUrl);if(!m)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:m.baseUrl,token:m.token}}let r=t.grounding??{},n=await vS(),o=null;if(n)try{let m=await e();o={surface:"mcp-authoring",baseUrl:m.baseUrl,token:m.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(m=>({id:m.id,record_type:m.record_type,intent:m.intent}))}catch{c=[]}}let l=o?await PD(o,r):null,u=new el({name:_S,version:xS},n?{instructions:n.renderAuthoringInstructions({baseUrl:o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(m=>m.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let m=o;for(let h of a)u.registerPrompt(h.id,{title:h.name,description:h.description},async()=>{let b=await n.getMcpPromptSkill(m,h.id,r);if(!b)throw new Error(`unknown prompt: ${h.id}`);return{description:b.description,messages:[{role:"user",content:{type:"text",text:(b.prompts??[]).join(`
|
|
1827
1921
|
|
|
1828
|
-
`)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),b=await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog fetch failed: ${b.status}`);return Ke(await b.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:j.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:j.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:m,source:h})=>{let{baseUrl:b,token:k}=await e(),E=h?`?source=${encodeURIComponent(h)}`:"",P=await fetch(`${b}/v1/catalog/records/${encodeURIComponent(m)}${E}`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown record type "${m}" \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`record anatomy fetch failed: ${P.status}`);return Ke(await P.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:j.array(j.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:j.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:m,source:h})=>{let{baseUrl:b,token:k}=await e(),E=new URLSearchParams({types:m.join(",")});h&&E.set("source",h);let P=await fetch(`${b}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(P.status===404)throw new Error(`none of those record types resolved: ${m.join(", ")} \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`common columns fetch failed: ${P.status}`);return Ke(await P.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:m,token:h}=await e(),b=await fetch(`${m}/v1/catalog/census`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog census failed: ${b.status}`);return Ke(await b.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:j.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:j.enum(yS).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:j.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:m,kind:h,limit:b})=>{let{baseUrl:k,token:E}=await e(),P=new URLSearchParams({q:m});h&&P.set("kind",h),b!==void 0&&P.set("limit",String(b));let z=await fetch(`${k}/v1/catalog/objects?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return Ke(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:j.enum(yS),externalId:j.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:m,externalId:h})=>{let{baseUrl:b,token:k}=await e(),E=await fetch(`${b}/v1/catalog/objects/${encodeURIComponent(m)}/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${m}:${h} \u2014 find it with search_catalog.`);if(!E.ok)throw new Error(`catalog object fetch failed: ${E.status}`);return Ke(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:j.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:j.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:m,limit:h})=>{let{baseUrl:b,token:k}=await e(),E=new URLSearchParams({q:m});h!==void 0&&E.set("limit",String(h));let P=await fetch(`${b}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!P.ok)throw new Error(`kb search failed: ${P.status}`);return Ke(await P.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:j.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:m})=>{let{baseUrl:h,token:b}=await e(),k=await fetch(`${h}/v1/kb/document/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!k.ok&&k.status!==404)throw new Error(`kb document fetch failed: ${k.status}`);return Ke(await k.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:j.boolean().optional()}},async({recordsOnly:m})=>{let{baseUrl:h,token:b}=await e();return{content:[{type:"text",text:await Rn({baseUrl:h,token:b,recordsOnly:m})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:j.string(),event:j.string().optional(),template:j.enum(["require-field","enforce-format","blank"]).optional(),field:j.string().optional(),regex:j.string().optional(),source:j.string().optional(),id:j.string().optional()}},async m=>{let h=Fr("hook",{recordType:m.recordType,event:m.event,template:m.template,field:m.field,regex:m.regex,source:m.source,id:m.id});return Ke({path:h.relativePath,content:h.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:j.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:j.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:j.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:j.string().optional().describe("Target record type (defaults to the trigger record type)."),event:j.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:j.string().optional()}},async m=>{let h=Fr("conduit",{recordType:m.recordType,source:m.source,to:m.to,toRecordType:m.toRecordType,event:m.event,id:m.id});return Ke({path:h.relativePath,content:h.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:j.string().describe("The extension TS source."),samplesDir:j.string().optional().describe('Samples directory (default "samples").')}},async({source:m,samplesDir:h})=>{let b=gS(process.cwd(),h??"samples"),k=await cs(b),E=await Hi(m,k.map(z=>z.fixture)),P=E.filter(z=>!z.pass).length;return Ke({total:E.length,passed:E.length-P,results:E})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:j.string(),recordType:j.string(),event:j.string(),source:j.string().describe('Adapter id or "standalone".'),sourceCode:j.string().describe("The verbatim extension TS."),extensionKind:j.string().optional()}},async m=>{let{baseUrl:h,token:b}=await e(),E=await new Y({baseUrl:h,token:b}).deploy({id:m.id,recordType:m.recordType,event:m.event,source:m.source,sourceCode:m.sourceCode,extensionKind:m.extensionKind});return Ke(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:j.string(),limit:j.number().int().positive().optional()}},async({id:m,limit:h})=>{let{baseUrl:b,token:k}=await e(),E=new Y({baseUrl:b,token:k});return Ke({id:m,logs:await E.logs(m,h)})}),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:m,token:h}=await e(),b=new Y({baseUrl:m,token:h});return Ke(await b.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:j.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:j.string().optional().describe("Display name (defaults to the slug)."),description:j.string().optional().describe("Short description.")}},async({slug:m,name:h,description:b})=>{let{baseUrl:k,token:E}=await e(),P=new Y({baseUrl:k,token:E});return Ke(await P.appsCreate({slug:m,name:h,description:b}))}),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:j.string().describe("App slug or id.")}},async({app:m})=>{let{baseUrl:h,token:b}=await e(),k=new Y({baseUrl:h,token:b});return Ke(await k.appsPull(m))}),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:j.string().describe("App slug or id."),files:j.record(j.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:j.string().optional().describe("Short note stored with the revision.")}},async({app:m,files:h,note:b})=>{let{baseUrl:k,token:E}=await e(),P=new Y({baseUrl:k,token:E});return Ke(await P.appsPush(m,h,{note:b}))});let p=j.object({name:j.string().describe("Field name (lowercase identifier)."),type:j.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:j.boolean().optional()}),w=j.object({slug:j.string().describe("Table slug; the physical table is cr_<slug>."),displayName:j.string().optional(),fields:j.array(p).describe("At least one field."),rowLevelOwner:j.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:m,token:h}=await e(),b=new Y({baseUrl:m,token:h});return Ke(await b.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:j.array(w),claimedBy:j.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:h})=>{let{baseUrl:b,token:k}=await e(),E=new Y({baseUrl:b,token:k});return Ke(await E.tablesPlan({tables:m,claimedBy:h}))}),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:j.array(w),claimedBy:j.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:h})=>{let{baseUrl:b,token:k}=await e(),E=new Y({baseUrl:b,token:k});return Ke(await E.tablesApply({tables:m,claimedBy:h}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async m=>{let{baseUrl:h,token:b}=await e(),E=await(await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}})).text();return{contents:[{uri:m.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async m=>{let{baseUrl:h,token:b}=await e(),k=await Rn({baseUrl:h,token:b});return{contents:[{uri:m.href,mimeType:"text/plain",text:k}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async m=>{let h=gS(process.cwd(),"samples"),b=[];try{b=(await TD.readdir(h)).filter(E=>E.endsWith(".json"))}catch{b=[]}let k=await cs(h);return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({files:b,samples:k.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 m=>{let h=await wS(),b=[];if(h){let{baseUrl:k,token:E}=await e();b=await h.listRecipesForSurface({surface:"mcp-authoring",baseUrl:k,token:E},r)}return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({recipes:b})}]}}),u}async function AD(t={}){let e=await xS(t),r=new tl;await e.connect(r)}var yS,bS,vS,_S,kS,RD,PD,SS=N(()=>{lS();hS();io();Ul();ss();Tr();Gl();Ji();mS();yS=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];vS="turbobase-authoring",_S="0.1.0";kS=["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"],RD=[...kS,...fS],PD=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as Zm}from"node:child_process";import{promises as ye}from"node:fs";import{homedir as ID}from"node:os";import{basename as ES,dirname as Ko,join as At,relative as nl,resolve as xe,sep as qm}from"node:path";var ag=al(ig(),1),{program:eU,createCommand:tU,createArgument:rU,createOption:nU,CommanderError:oU,InvalidArgumentError:sU,InvalidOptionArgumentError:iU,Command:cg,Argument:aU,Option:cU,Help:lU}=ag.default;Ul();ss();Tr();Gl();Vl();import{promises as Hg}from"node:fs";function Bg(t,e){return e===t?"same-type-merge":"different-type-mint"}var Vg=4;function Wl(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=co(t,"id"),r=co(t,"on"),n=co(t,"source"),o=co(t,"recordType"),s=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=co(s,"source"),a=co(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]):Vg}}function co(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function C0(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 Kg(t,e,r="fixture"){let n=e.name??r,o=[],s;try{s=Wl(t)}catch(c){return{fixtureName:n,conduit:z0(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=C0(e),a=Object.entries(e.atlasLinks??{}).map(([c,l])=>({key:c,resolved:l}));try{let c=await Fi(t),u=!!(await as(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 p=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${p} 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 w=await as(c,i,{member:"transform",timeoutMs:200}),m=w.effects.logs,h=w.effects.result;if(!h||typeof h!="object")throw new Error(`conduit ${s.id} transform returned no result (expected { patch, createdFrom? })`);let b=h,k=Bg(s.fromRecordType,s.toRecordType),{wouldWriteBindings:E,masterAction:P}=N0(s,k,e);return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,transformResult:b,applyBranch:k,wouldWriteBindings:E,masterAction:P,logs:m}}catch(c){return{fixtureName:n,conduit:s,guards:o,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}}function N0(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 z0(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Vg}}async function Gg(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 Wg(t){let e=await Hg.readFile(t,"utf8");return JSON.parse(e)}function Jg(t){return Hg.readFile(t,"utf8")}function Yg(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(`
|
|
1829
|
-
`);if(n.push(""),n.push("transform \u2192 patch:"),n.push(
|
|
1830
|
-
`)}function
|
|
1922
|
+
`)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),b=await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog fetch failed: ${b.status}`);return Ke(await b.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:L.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:L.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:m,source:h})=>{let{baseUrl:b,token:$}=await e(),E=h?`?source=${encodeURIComponent(h)}`:"",P=await fetch(`${b}/v1/catalog/records/${encodeURIComponent(m)}${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown record type "${m}" \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`record anatomy fetch failed: ${P.status}`);return Ke(await P.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:L.array(L.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:L.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:m,source:h})=>{let{baseUrl:b,token:$}=await e(),E=new URLSearchParams({types:m.join(",")});h&&E.set("source",h);let P=await fetch(`${b}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`none of those record types resolved: ${m.join(", ")} \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`common columns fetch failed: ${P.status}`);return Ke(await P.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:m,token:h}=await e(),b=await fetch(`${m}/v1/catalog/census`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog census failed: ${b.status}`);return Ke(await b.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:L.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:L.enum(bS).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:L.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:m,kind:h,limit:b})=>{let{baseUrl:$,token:E}=await e(),P=new URLSearchParams({q:m});h&&P.set("kind",h),b!==void 0&&P.set("limit",String(b));let z=await fetch(`${$}/v1/catalog/objects?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return Ke(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:L.enum(bS),externalId:L.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:m,externalId:h})=>{let{baseUrl:b,token:$}=await e(),E=await fetch(`${b}/v1/catalog/objects/${encodeURIComponent(m)}/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${m}:${h} \u2014 find it with search_catalog.`);if(!E.ok)throw new Error(`catalog object fetch failed: ${E.status}`);return Ke(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:L.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:L.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:m,limit:h})=>{let{baseUrl:b,token:$}=await e(),E=new URLSearchParams({q:m});h!==void 0&&E.set("limit",String(h));let P=await fetch(`${b}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!P.ok)throw new Error(`kb search failed: ${P.status}`);return Ke(await P.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:L.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:m})=>{let{baseUrl:h,token:b}=await e(),$=await fetch(`${h}/v1/kb/document/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return Ke(await $.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:L.boolean().optional()}},async({recordsOnly:m})=>{let{baseUrl:h,token:b}=await e();return{content:[{type:"text",text:await En({baseUrl:h,token:b,recordsOnly:m})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:L.string(),event:L.string().optional(),template:L.enum(["require-field","enforce-format","blank"]).optional(),field:L.string().optional(),regex:L.string().optional(),source:L.string().optional(),id:L.string().optional()}},async m=>{let h=Hr("hook",{recordType:m.recordType,event:m.event,template:m.template,field:m.field,regex:m.regex,source:m.source,id:m.id});return Ke({path:h.relativePath,content:h.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:L.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:L.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:L.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:L.string().optional().describe("Target record type (defaults to the trigger record type)."),event:L.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:L.string().optional()}},async m=>{let h=Hr("conduit",{recordType:m.recordType,source:m.source,to:m.to,toRecordType:m.toRecordType,event:m.event,id:m.id});return Ke({path:h.relativePath,content:h.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:L.string().describe("The extension TS source."),samplesDir:L.string().optional().describe('Samples directory (default "samples").')}},async({source:m,samplesDir:h})=>{let b=yS(process.cwd(),h??"samples"),$=await as(b),E=await Vi(m,$.map(z=>z.fixture)),P=E.filter(z=>!z.pass).length;return Ke({total:E.length,passed:E.length-P,results:E})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:L.string(),recordType:L.string(),event:L.string(),source:L.string().describe('Adapter id or "standalone".'),sourceCode:L.string().describe("The verbatim extension TS."),extensionKind:L.string().optional()}},async m=>{let{baseUrl:h,token:b}=await e(),E=await new X({baseUrl:h,token:b}).deploy({id:m.id,recordType:m.recordType,event:m.event,source:m.source,sourceCode:m.sourceCode,extensionKind:m.extensionKind});return Ke(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:L.string(),limit:L.number().int().positive().optional()}},async({id:m,limit:h})=>{let{baseUrl:b,token:$}=await e(),E=new X({baseUrl:b,token:$});return Ke({id:m,logs:await E.logs(m,h)})}),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:m,token:h}=await e(),b=new X({baseUrl:m,token:h});return Ke(await b.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:L.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:L.string().optional().describe("Display name (defaults to the slug)."),description:L.string().optional().describe("Short description.")}},async({slug:m,name:h,description:b})=>{let{baseUrl:$,token:E}=await e(),P=new X({baseUrl:$,token:E});return Ke(await P.appsCreate({slug:m,name:h,description:b}))}),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:L.string().describe("App slug or id.")}},async({app:m})=>{let{baseUrl:h,token:b}=await e(),$=new X({baseUrl:h,token:b});return Ke(await $.appsPull(m))}),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:L.string().describe("App slug or id."),files:L.record(L.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:L.string().optional().describe("Short note stored with the revision.")}},async({app:m,files:h,note:b})=>{let{baseUrl:$,token:E}=await e(),P=new X({baseUrl:$,token:E});return Ke(await P.appsPush(m,h,{note:b}))});let p=L.object({name:L.string().describe("Field name (lowercase identifier)."),type:L.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:L.boolean().optional()}),w=L.object({slug:L.string().describe("Table slug; the physical table is cr_<slug>."),displayName:L.string().optional(),fields:L.array(p).describe("At least one field."),rowLevelOwner:L.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:m,token:h}=await e(),b=new X({baseUrl:m,token:h});return Ke(await b.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:L.array(w),claimedBy:L.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:h})=>{let{baseUrl:b,token:$}=await e(),E=new X({baseUrl:b,token:$});return Ke(await E.tablesPlan({tables:m,claimedBy:h}))}),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:L.array(w),claimedBy:L.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:h})=>{let{baseUrl:b,token:$}=await e(),E=new X({baseUrl:b,token:$});return Ke(await E.tablesApply({tables:m,claimedBy:h}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async m=>{let{baseUrl:h,token:b}=await e(),E=await(await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}})).text();return{contents:[{uri:m.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async m=>{let{baseUrl:h,token:b}=await e(),$=await En({baseUrl:h,token:b});return{contents:[{uri:m.href,mimeType:"text/plain",text:$}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async m=>{let h=yS(process.cwd(),"samples"),b=[];try{b=(await RD.readdir(h)).filter(E=>E.endsWith(".json"))}catch{b=[]}let $=await as(h);return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({files:b,samples:$.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 m=>{let h=await vS(),b=[];if(h){let{baseUrl:$,token:E}=await e();b=await h.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:E},r)}return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({recipes:b})}]}}),u}async function OD(t={}){let e=await kS(t),r=new rl;await e.connect(r)}var bS,wS,_S,xS,$S,AD,ID,TS=O(()=>{uS();fS();so();Ml();os();Sr();Gl();Yi();gS();bS=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];_S="turbobase-authoring",xS="0.1.0";$S=["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"],AD=[...$S,...mS],ID=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as Bm}from"node:child_process";import{promises as ye}from"node:fs";import{homedir as CD}from"node:os";import{basename as RS,dirname as Vo,join as At,relative as ol,resolve as xe,sep as Zm}from"node:path";var cg=cl(ag(),1),{program:rU,createCommand:nU,createArgument:oU,createOption:sU,CommanderError:iU,InvalidArgumentError:aU,InvalidOptionArgumentError:cU,Command:lg,Argument:lU,Option:uU,Help:dU}=cg.default;Ml();os();Sr();Gl();Kl();import{promises as Vg}from"node:fs";function Fg(t,e){return e===t?"same-type-merge":"different-type-mint"}var Kg=4;function Jl(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=ao(t,"id"),r=ao(t,"on"),n=ao(t,"source"),o=ao(t,"recordType"),s=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=ao(s,"source"),a=ao(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]):Kg}}function ao(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function NE(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 Wg(t,e,r="fixture"){let n=e.name??r,o=[],s;try{s=Jl(t)}catch(c){return{fixtureName:n,conduit:jE(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=NE(e),a=Object.entries(e.atlasLinks??{}).map(([c,l])=>({key:c,resolved:l}));try{let c=await Hi(t),u=!!(await is(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 p=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${p} 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 w=await is(c,i,{member:"transform",timeoutMs:200}),m=w.effects.logs,h=w.effects.result;if(!h||typeof h!="object")throw new Error(`conduit ${s.id} transform returned no result (expected { patch, createdFrom? })`);let b=h,$=Fg(s.fromRecordType,s.toRecordType),{wouldWriteBindings:E,masterAction:P}=zE(s,$,e);return{fixtureName:n,conduit:s,guards:o,whenPassed:u,atlasResolutions:a,transformResult:b,applyBranch:$,wouldWriteBindings:E,masterAction:P,logs:m}}catch(c){return{fixtureName:n,conduit:s,guards:o,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}}function zE(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 jE(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Kg}}async function Gg(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 Jg(t){let e=await Vg.readFile(t,"utf8");return JSON.parse(e)}function Yg(t){return Vg.readFile(t,"utf8")}function Xg(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(`
|
|
1923
|
+
`);if(n.push(""),n.push("transform \u2192 patch:"),n.push(LE(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(`
|
|
1924
|
+
`)}function LE(t,e){return t.split(`
|
|
1831
1925
|
`).map(r=>e+r).join(`
|
|
1832
|
-
`)}var
|
|
1926
|
+
`)}var DE="2026-01-01",Qg="2026-01-01T00:00:00.000Z";function UE(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"?DE:r.startsWith("timestamp")?Qg: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:Qg}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function ME(t){let e={};for(let r of t.columns)e[r.name]=UE(r.pgType,r.name);return e}function qE(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:ME(t)},expect:e.expect??"pass"}}function ey(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:qE(r,e)}))}import{promises as ty}from"node:fs";import{join as ry,relative as ZE,sep as BE}from"node:path";var FE=67324752,HE=33639248,VE=101010256,KE=(()=>{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 WE(t){let e=4294967295;for(let r=0;r<t.length;r++)e=KE[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function GE(t){let e=[];async function r(n){let o=await ty.readdir(n,{withFileTypes:!0});for(let s of o){let i=ry(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(ZE(t,i).split(BE).join("/"))}}return await r(t),e.sort(),e}async function ny(t){let e=await GE(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await ty.readFile(ry(t,a)),u=WE(l),p=Buffer.alloc(30+c.length);p.writeUInt32LE(FE,0),p.writeUInt16LE(20,4),p.writeUInt16LE(0,6),p.writeUInt16LE(0,8),p.writeUInt32LE(u,14),p.writeUInt32LE(l.length,18),p.writeUInt32LE(l.length,22),p.writeUInt16LE(c.length,26),c.copy(p,30),r.push(p,l);let w=Buffer.alloc(46+c.length);w.writeUInt32LE(HE,0),w.writeUInt16LE(20,4),w.writeUInt16LE(20,6),w.writeUInt16LE(0,10),w.writeUInt32LE(u,16),w.writeUInt32LE(l.length,20),w.writeUInt32LE(l.length,24),w.writeUInt16LE(c.length,28),w.writeUInt32LE(o,42),c.copy(w,46),n.push(w),o+=p.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(VE,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 JE(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function Ki(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function YE(t){let e=oy(t,"from"),r=oy(t,"to");return{fromSource:e?Ki(e,"source"):void 0,fromRecordType:e?Ki(e,"recordType"):void 0,toSource:r?Ki(r,"source"):void 0,toRecordType:r?Ki(r,"recordType"):void 0}}function oy(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 XE(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 QE(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function e0(t){return/\bcreatedFrom\b/.test(t)}function sy(t){let e=JE(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:o,fromRecordType:s,toRecordType:i}=YE(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=XE(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&&!e0(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=QE(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 iy(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(`
|
|
1833
1927
|
`);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(`
|
|
1834
1928
|
lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
|
|
1835
|
-
`)}function
|
|
1929
|
+
`)}function ay(t){return t.cases.filter(e=>e.status==="failed").length}function ls(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function t0(t){let e=ay(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${ls(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${ls(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${ls(n.type)}"`:"";r.push(` <failure${i} message="${ls(s)}">${ls(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
|
|
1836
1930
|
`)}
|
|
1837
|
-
`}function
|
|
1838
|
-
`}function
|
|
1839
|
-
`)}function Xt(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=>
|
|
1840
|
-
`)}function
|
|
1931
|
+
`}function r0(t){let e={suite:t.name,tests:t.cases.length,failures:ay(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
|
|
1932
|
+
`}function Wi(t,e){return e==="junit"?t0(t):r0(t)}var $t={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"},We={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},co=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Dt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},cy=/\x1b\[[0-9;]*m/g;function Tr(t){return t.replace(cy,"").length}function Yl(t,e){return e<=0?1:Math.max(1,Math.ceil(Tr(t)/e))}function n0(){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 Xl=n0();function tt(){return Xl}function Ql(t){Xl=t}function ft(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Ut(t,e){return Xl?`${t}${e}${$t.reset}`:e}var g={bold:t=>Ut($t.bold,t),dim:t=>Ut($t.dim,t),red:t=>Ut($t.red,t),green:t=>Ut($t.green,t),yellow:t=>Ut($t.yellow,t),blue:t=>Ut($t.blue,t),magenta:t=>Ut($t.magenta,t),cyan:t=>Ut($t.cyan,t),grey:t=>Ut($t.grey,t)};var He={success:t=>`${g.green("\u2713")} ${t}`,error:t=>`${g.red("\u2716")} ${t}`,warn:t=>`${g.yellow("\u26A0")} ${t}`,info:t=>`${g.dim("\xB7")} ${t}`,step:t=>`${g.cyan("\u25B8")} ${t}`},Zr={add:t=>g.green(`+ ${t}`),change:t=>g.yellow(`~ ${t}`),destroy:t=>g.red(`- ${t}`)},o0=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),s0=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),i0=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function lo(t){let e=t.toLowerCase();return o0.has(e)?g.green(t):s0.has(e)?g.red(t):i0.has(e)?g.yellow(t):t}function Br(t,e=[]){let r=Math.max(Tr(t),...e.map(Tr),0),n=r+2,o=g.cyan(Dt.v),s=a=>` ${a}${" ".repeat(r-Tr(a))} `,i=[g.cyan(`${Dt.tl}${Dt.h.repeat(n)}${Dt.tr}`),`${o}${g.bold(s(t))}${o}`];if(e.length){i.push(`${g.cyan(Dt.ml)}${g.dim(Dt.h.repeat(n))}${g.cyan(Dt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(g.cyan(`${Dt.bl}${Dt.h.repeat(n)}${Dt.br}`)),i.join(`
|
|
1933
|
+
`)}function Xt(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=>Tr(u[l]??"")));let a=l=>{let u=l.map((p,w)=>{let m=p??"";return w===l.length-1?m:m+" ".repeat(Math.max(0,i[w]-Tr(m)))});return r+u.join(n)},c=[];e.head&&(c.push(a(e.head.map(l=>g.bold(l)))),c.push(a(e.head.map((l,u)=>g.dim("\u2500".repeat(i[u]??Tr(l)))))));for(let l of t)c.push(a(l));return c.join(`
|
|
1934
|
+
`)}function eu(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`${tt()?e.map(n=>Ut($t.cyan,n)).join(`
|
|
1841
1935
|
`):e.join(`
|
|
1842
1936
|
`)}
|
|
1843
|
-
${g.dim(` ${t}`)}`}var
|
|
1844
|
-
`),i}catch(i){throw s(),r&&
|
|
1845
|
-
`),i}}function
|
|
1846
|
-
`),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),
|
|
1847
|
-
`)},stop(){clearInterval(a),i(),
|
|
1937
|
+
${g.dim(` ${t}`)}`}var Mt=t=>{process.stderr.write(t)};function Gi(){return tt()&&process.stderr.isTTY===!0}function ly(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${g.dim("\u2591".repeat(e-n))}`}async function ae(t,e){let r=Gi(),n=0,o;r&&(Mt(We.hideCursor),o=setInterval(()=>{Mt(`${We.col0}${We.clearLine}${g.magenta(co[n++%co.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Mt(`${We.col0}${We.clearLine}${We.showCursor}`)};try{let i=await e();return s(),r&&Mt(`${He.success(t)}
|
|
1938
|
+
`),i}catch(i){throw s(),r&&Mt(`${He.error(t)}
|
|
1939
|
+
`),i}}function tu(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=g.magenta(co[e%co.length]),l=g.cyan(r.stage),u=r.runStatus?` ${g.dim(`(${r.runStatus})`)}`:"",p=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${c} ${t} ${g.dim("\u25B8")} ${l}${u} ${ly(r.percent)} ${p}`},s=()=>{Mt(`${We.col0}${We.clearLine}${o()}`),n=!0},i=()=>{n&&Mt(`${We.col0}${We.clearLine}`),n=!1};Mt(We.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Mt(`${c}
|
|
1940
|
+
`),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Mt(We.showCursor);let l=c.stage!=="failed",u=`${t} ${g.dim("\u25B8")} ${a0(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Mt(`${l?He.success(u):He.error(u)}
|
|
1941
|
+
`)},stop(){clearInterval(a),i(),Mt(We.showCursor)}}}function a0(t){return t==="completed"?g.green(t):t==="failed"?g.red(t):g.cyan(t)}function mt(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(b=>!b.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=b=>{process.stderr.write(b)},c=process.stdin,l=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${g.bold(g.cyan("?"))} ${g.bold(t)}
|
|
1848
1942
|
`),a(`${g.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
|
|
1849
|
-
`),a(We.hideCursor);let u=0,p=()=>{let b=process.stderr.columns??process.stdout.columns??80;u>0&&(a(We.cursorUp(u)),a(We.clearToEnd));let
|
|
1850
|
-
`)
|
|
1851
|
-
`),o(new Error("aborted"));return}if(
|
|
1852
|
-
`){let P=e[i];if(P.disabled)return;w(),n(P.value);return}if(
|
|
1853
|
-
`)}),o=r.sleep??
|
|
1854
|
-
`)});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(
|
|
1855
|
-
binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function
|
|
1856
|
-
`)}),n=e.sleep??
|
|
1943
|
+
`),a(We.hideCursor);let u=0,p=()=>{let b=process.stderr.columns??process.stdout.columns??80;u>0&&(a(We.cursorUp(u)),a(We.clearToEnd));let $=0;for(let E=0;E<e.length;E+=1){let P=e[E],z=E===i,V=z?g.cyan("\u25B6"):" ",Q=P.disabled?g.grey(P.label):z?g.bold(g.cyan(P.label)):P.label,Je=P.description?` ${g.dim(P.description)}`:"",Qe=` ${V} ${Q}${Je}`;a(`\r${Qe}
|
|
1944
|
+
`),$+=Yl(Qe,b)}u=$},w=()=>{c.removeListener("data",h),c.setRawMode?.(l??!1),c.pause(),a(We.showCursor)},m=b=>{let $=i;for(let E=0;E<e.length;E+=1)if($=($+b+e.length)%e.length,!e[$].disabled){i=$;return}},h=b=>{let $=b.toString("utf8");if($===""||$==="q"){w(),a(`
|
|
1945
|
+
`),o(new Error("aborted"));return}if($==="\r"||$===`
|
|
1946
|
+
`){let P=e[i];if(P.disabled)return;w(),n(P.value);return}if($==="\x1B[A"||$==="k"){m(-1),p();return}if($==="\x1B[B"||$==="j"){m(1),p();return}let E=Number($);Number.isFinite(E)&&E>=1&&E<=e.length&&!e[E-1].disabled&&(i=E-1,p())};c.on("data",h),p()})}function Ji(t,e){return`${lo(t)}${" ".repeat(Math.max(0,e-t.length))}`}var dy=t=>new Promise(e=>setTimeout(e,t));function uy(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}] ${Ji(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function py(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
|
|
1947
|
+
`)}),o=r.sleep??dy,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(uy(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 p=await t.conduitEvents(e,{since:c||void 0,limit:200});for(let w of[...p].reverse())n(uy(w)),a+=1,w.updatedAt>c&&(c=w.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} ${Ji(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function hy(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
|
|
1948
|
+
`)});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(`
|
|
1949
|
+
binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function l0(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),r=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),n=t.occurrences>1?` x${t.occurrences}`:"",o=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",s=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${Ji(t.severity,5)} ${Ji(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function fy(t,e={}){let r=e.sink??(E=>{process.stdout.write(`${E}
|
|
1950
|
+
`)}),n=e.sleep??dy,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:c,sleep:l,intervalMs:u,...p}=e,w=E=>{r(a?JSON.stringify(E):l0(E))},m=await t.platformEvents({...p,limit:p.limit??100});if(m.length===0&&!s)return r("logs: no events matched."),0;let h=0,b="";for(let E of[...m].reverse())w(E),h+=1,E.ts>b&&(b=E.ts);if(!s)return h;let $=i??Number.POSITIVE_INFINITY;for(let E=0;E<$;E+=1){await n(o);let P=await t.platformEvents({...p,...b?{after:b,since:void 0}:{},limit:200});for(let z of[...P].reverse())w(z),h+=1,z.ts>b&&(b=z.ts)}return h}Yi();function gy(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 ru=".github/workflows/turbobase-release-deploy.yml",h0=`# \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
|
|
1857
1951
|
# Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
|
|
1858
1952
|
#
|
|
1859
1953
|
# Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
|
|
@@ -1955,7 +2049,7 @@ jobs:
|
|
|
1955
2049
|
--ref "\${{ github.sha }}" \\
|
|
1956
2050
|
--project . \\
|
|
1957
2051
|
--follow
|
|
1958
|
-
`,
|
|
2052
|
+
`,f0=".github/workflows/turbobase-app-deploy.yml",m0=`# \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
|
|
1959
2053
|
# Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
|
|
1960
2054
|
#
|
|
1961
2055
|
# What ships from this repo, and when:
|
|
@@ -2173,14 +2267,14 @@ jobs:
|
|
|
2173
2267
|
else
|
|
2174
2268
|
echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
|
|
2175
2269
|
fi
|
|
2176
|
-
`;function
|
|
2270
|
+
`;function yy(){return[{path:ru,content:h0}]}function by(){return[{path:f0,content:m0}]}Yi();var g0=[".mcp.json"];function _y(t,e=g0){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
|
|
2177
2271
|
`).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(`
|
|
2178
2272
|
`)?t:`${t}
|
|
2179
2273
|
`}
|
|
2180
2274
|
# Added by the Turbobase scaffold.
|
|
2181
2275
|
${o.join(`
|
|
2182
2276
|
`)}
|
|
2183
|
-
`}var
|
|
2277
|
+
`}var y0=`# Turbobase Extensions \u2014 extension project
|
|
2184
2278
|
|
|
2185
2279
|
This directory authors **Turbobase extensions** (hooks today; conduits later)
|
|
2186
2280
|
against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
|
|
@@ -2249,8 +2343,8 @@ order is the signal, and it is the part the product team reads first.
|
|
|
2249
2343
|
|
|
2250
2344
|
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
|
|
2251
2345
|
updating a test. It is checked into the repo so the whole team sees it.
|
|
2252
|
-
`,
|
|
2253
|
-
`;function
|
|
2346
|
+
`,b0=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)+`
|
|
2347
|
+
`;function w0(t){return`---
|
|
2254
2348
|
name: generate-types
|
|
2255
2349
|
description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
|
|
2256
2350
|
---
|
|
@@ -2261,7 +2355,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
|
|
|
2261
2355
|
|
|
2262
2356
|
The OpenAPI half is cookie-session-gated, so a headless run with a stored token
|
|
2263
2357
|
degrades to record shapes only and says so \u2014 that is expected, not a failure.
|
|
2264
|
-
`}var
|
|
2358
|
+
`}var v0=`---
|
|
2265
2359
|
name: mock-test
|
|
2266
2360
|
description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
|
|
2267
2361
|
---
|
|
@@ -2270,7 +2364,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
|
|
|
2270
2364
|
self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
|
|
2271
2365
|
against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
|
|
2272
2366
|
fixture for each branch (a passing record and a rejecting record).
|
|
2273
|
-
`,
|
|
2367
|
+
`,_0=`---
|
|
2274
2368
|
name: deploy
|
|
2275
2369
|
description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
2276
2370
|
---
|
|
@@ -2278,7 +2372,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
|
2278
2372
|
Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
|
|
2279
2373
|
/v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
|
|
2280
2374
|
the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
|
|
2281
|
-
`;function
|
|
2375
|
+
`;function x0(t){return`# ${t} \u2014 Turbobase app
|
|
2282
2376
|
|
|
2283
2377
|
This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
|
|
2284
2378
|
same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
|
|
@@ -2364,7 +2458,7 @@ to your default branch is what makes all of it live.
|
|
|
2364
2458
|
| \`conduits/*.ts\` | bridges that move a record from one source to another | same |
|
|
2365
2459
|
| \`turbobase/sync.json\` | which fields are promoted, which tables are mirrored | same |
|
|
2366
2460
|
| \`turbobase/schedules.json\` | scheduled jobs (cron) | same |
|
|
2367
|
-
| \`public/turbobase.json\` | the app's name, icon, tables
|
|
2461
|
+
| \`public/turbobase.json\` | the app's name, icon, tables, declared writes and roles | read by both |
|
|
2368
2462
|
|
|
2369
2463
|
\`.github/workflows/turbobase-app-deploy.yml\` runs this for you: a pull request
|
|
2370
2464
|
gets a **preview URL** (updated in place on every push) plus a **plan** of the
|
|
@@ -2400,6 +2494,30 @@ admin (Compliance \u2192 Guardrails) to open it.
|
|
|
2400
2494
|
Declaring is worth it: without it you find out a write is blocked one row at a
|
|
2401
2495
|
time, in production, from an end user.
|
|
2402
2496
|
|
|
2497
|
+
### Roles: you DECLARE, an admin ASSIGNS
|
|
2498
|
+
|
|
2499
|
+
Tailored roles go in the same file:
|
|
2500
|
+
|
|
2501
|
+
\`\`\`json
|
|
2502
|
+
{ "roles": [{ "name": "Warehouse clerk",
|
|
2503
|
+
"capabilities": ["read:order", "write:order_fulfillment"] }] }
|
|
2504
|
+
\`\`\`
|
|
2505
|
+
|
|
2506
|
+
Deploying creates it as an ordinary role \u2014 the same one an admin manages in
|
|
2507
|
+
Admin \u2192 Roles. Same asymmetry as guardrails, one step further: **a declared role
|
|
2508
|
+
has no holders until an admin assigns it in Admin \u2192 Users.** Deploying grants
|
|
2509
|
+
nobody anything, including you. You cannot declare \`appRole\` (admin is assigned,
|
|
2510
|
+
never authored) or \`scopes\` (row-level narrowing is the admin's).
|
|
2511
|
+
|
|
2512
|
+
Redeploying ADDS missing capabilities to an existing role and never removes any \u2014
|
|
2513
|
+
a role can have live holders, so a deploy must not be able to revoke access.
|
|
2514
|
+
|
|
2515
|
+
Gate your screens on the same capability strings with \`hasCapability()\` from
|
|
2516
|
+
\`src/lib/turbobase.ts\`, and catch \`TurbobasePermissionError\` on writes \u2014 that
|
|
2517
|
+
is UX, not security. **RLS is the guarantee**: a denied READ comes back as an
|
|
2518
|
+
empty list rather than an error, so check before you render or a permission
|
|
2519
|
+
problem looks like missing data. See the \`roles-and-permissions\` skill.
|
|
2520
|
+
|
|
2403
2521
|
## Layout
|
|
2404
2522
|
|
|
2405
2523
|
- \`src/App.tsx\` \u2014 the app. Start here.
|
|
@@ -2584,7 +2702,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
|
|
|
2584
2702
|
review, so what you write reaches the knowledge base and the product team instead
|
|
2585
2703
|
of evaporating at the end of the session. Keep the section headings exactly as
|
|
2586
2704
|
they are \u2014 the ingest finds entries by heading, not by filename.
|
|
2587
|
-
`}var
|
|
2705
|
+
`}var uo="customer",Rn="email",k0="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",$0=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
|
|
2588
2706
|
//
|
|
2589
2707
|
// It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
|
|
2590
2708
|
// the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
|
|
@@ -2603,8 +2721,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
|
|
|
2603
2721
|
// Pure and credentials-free: no secrets, no network, no Node builtins, one
|
|
2604
2722
|
// concern per file, nothing factored into a shared module (the sandbox fences
|
|
2605
2723
|
// every import except the SDK).
|
|
2606
|
-
`;function
|
|
2607
|
-
`;return[{path:t.relativePath,content:`${
|
|
2724
|
+
`;function S0(){let t=Hr("hook",{recordType:uo,event:"before_save",template:"enforce-format",field:Rn,regex:k0,id:`app:${uo}:${Rn}-format`,description:`Reject a ${uo} write whose ${Rn} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:uo,event:"before_save",payload:r},expect:n},null,2)+`
|
|
2725
|
+
`;return[{path:t.relativePath,content:`${$0}${t.content}`},{path:`samples/${uo}.${Rn}-ok.json`,content:e({company_name:"Acme Supply",[Rn]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${uo}.${Rn}-malformed.json`,content:e({company_name:"Acme Supply",[Rn]:"ada-at-example"},"reject","a malformed address is rejected")}]}var T0="---\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",E0=`---
|
|
2608
2726
|
name: ship-app
|
|
2609
2727
|
description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
|
|
2610
2728
|
---
|
|
@@ -2647,7 +2765,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
|
|
|
2647
2765
|
non-text, so images and fonts belong in the build pipeline or object storage, not
|
|
2648
2766
|
the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
|
|
2649
2767
|
project root and DO travel \u2014 deploy reads them.
|
|
2650
|
-
`,
|
|
2768
|
+
`,R0=`---
|
|
2651
2769
|
name: business-rule-to-hook
|
|
2652
2770
|
description: Decide where a rule belongs \u2014 a hook on the instance (enforced for every writer, reusable by every app) or the app's UI. Use whenever you are about to write a validation, threshold, or "you can't do that" check.
|
|
2653
2771
|
---
|
|
@@ -2715,7 +2833,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
|
|
|
2715
2833
|
standing rules for every agent on the instance \u2014 see the record-learning skill.
|
|
2716
2834
|
A rule enforced in code and nowhere written down gets re-litigated by the next
|
|
2717
2835
|
person.
|
|
2718
|
-
`;function
|
|
2836
|
+
`;function P0(t){return`---
|
|
2719
2837
|
name: record-learning
|
|
2720
2838
|
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.
|
|
2721
2839
|
---
|
|
@@ -2760,7 +2878,7 @@ the product team acts on first, so it is maintained with the entries.
|
|
|
2760
2878
|
|
|
2761
2879
|
Do not reword the three headings. The deploy-side ingest recognises entries by
|
|
2762
2880
|
heading, not by filename, so a renamed section is a finding nobody receives.
|
|
2763
|
-
`}function
|
|
2881
|
+
`}function A0(t){return`# What this instance's source system actually does
|
|
2764
2882
|
|
|
2765
2883
|
Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
|
|
2766
2884
|
Written for the knowledge base, and **everything here is verified against real
|
|
@@ -2879,7 +2997,7 @@ finding has not been handed to the knowledge base yet.
|
|
|
2879
2997
|
and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
|
|
2880
2998
|
already live, which is worth reading before adding another rule. -->
|
|
2881
2999
|
|
|
2882
|
-
`}function
|
|
3000
|
+
`}function I0(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
|
|
2883
3001
|
|
|
2884
3002
|
Everything below cost time or produced a wrong result. Not speculation, and not
|
|
2885
3003
|
a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
|
|
@@ -2943,7 +3061,23 @@ Expected / happened / cost / fix.
|
|
|
2943
3061
|
|
|
2944
3062
|
<!-- Rank the findings above by how much time each would have saved. Position is
|
|
2945
3063
|
the signal \u2014 1 is the biggest win. -->
|
|
2946
|
-
|
|
3064
|
+
|
|
3065
|
+
## Platform asks
|
|
3066
|
+
|
|
3067
|
+
<!-- A capability you WANTED and could not find, as opposed to something that
|
|
3068
|
+
misbehaved. One bullet each. Unranked on purpose \u2014 these are requests, not a
|
|
3069
|
+
prioritization, and a list position would be read as a priority you did not
|
|
3070
|
+
state. Put them here rather than in a file of your own: a section this file
|
|
3071
|
+
names is read on every deploy, a file it does not is read by nobody. -->
|
|
3072
|
+
|
|
3073
|
+
## Requested rollups
|
|
3074
|
+
|
|
3075
|
+
<!-- Aggregates you had to compute client-side and would rather ask the server
|
|
3076
|
+
for \u2014 one bullet per view, with the grain ("per shipment", "per deal item")
|
|
3077
|
+
and what it would replace. These are the highest-signal entries in the file:
|
|
3078
|
+
each one is a page downloading rows to fold that it could have asked for
|
|
3079
|
+
folded. -->
|
|
3080
|
+
`}function O0(t,e){let r=e?`
|
|
2947
3081
|
# INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
|
|
2948
3082
|
# --records focus a previous run stamped into the file, so a refresh never
|
|
2949
3083
|
# narrows what an agent deliberately widened.
|
|
@@ -2974,8 +3108,8 @@ ${r}
|
|
|
2974
3108
|
# surface unticked items at the start of a session.
|
|
2975
3109
|
turbobase project adopt -o ADOPT.md >/dev/null \\
|
|
2976
3110
|
|| echo "turbobase: \\\`turbobase project adopt\\\` failed (its error is above) \u2014 ADOPT.md was NOT refreshed." >&2
|
|
2977
|
-
`}var
|
|
2978
|
-
name: ${
|
|
3111
|
+
`}var xy="Turbobase consultant",C0="turbobase-consultant",N0=`---
|
|
3112
|
+
name: ${xy}
|
|
2979
3113
|
description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
|
|
2980
3114
|
keep-coding-instructions: true
|
|
2981
3115
|
---
|
|
@@ -3048,8 +3182,8 @@ exists on purpose.
|
|
|
3048
3182
|
- Do not show a stack trace. Say what broke and what you are doing about it.
|
|
3049
3183
|
- Do not apologise repeatedly or pad with "great question".
|
|
3050
3184
|
- Do not use a table when a sentence works.
|
|
3051
|
-
`,
|
|
3052
|
-
`,
|
|
3185
|
+
`,z0=JSON.stringify({outputStyle:xy,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"}]}]}},null,2)+`
|
|
3186
|
+
`,j0=`#!/usr/bin/env bash
|
|
3053
3187
|
# PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
|
|
3054
3188
|
#
|
|
3055
3189
|
# Advisory only: exits 0 always, and adds a note for the agent when the edited
|
|
@@ -3066,7 +3200,7 @@ set -uo pipefail
|
|
|
3066
3200
|
command -v node >/dev/null 2>&1 || exit 0
|
|
3067
3201
|
|
|
3068
3202
|
exec node "$(dirname "$0")/check-rule-placement.mjs"
|
|
3069
|
-
`,
|
|
3203
|
+
`,L0=String.raw`/**
|
|
3070
3204
|
* Is the file that was just edited enforcing a business rule inside the SPA?
|
|
3071
3205
|
*
|
|
3072
3206
|
* Reads the PostToolUse payload on stdin, and when BOTH signals are present —
|
|
@@ -3135,7 +3269,158 @@ process.stdout.write(
|
|
|
3135
3269
|
},
|
|
3136
3270
|
}),
|
|
3137
3271
|
);
|
|
3138
|
-
`,
|
|
3272
|
+
`,D0=`---
|
|
3273
|
+
name: roles-and-permissions
|
|
3274
|
+
description: Decide who can open a screen and who can change a record \u2014 declare roles in public/turbobase.json, gate the UI on capabilities, and turn a denial into a message that names the role to ask for. Use when adding a screen, a nav item, a write button, a role, or answering "who can see/do X".
|
|
3275
|
+
---
|
|
3276
|
+
|
|
3277
|
+
Two things are true at once on this platform, and holding both is the whole
|
|
3278
|
+
skill:
|
|
3279
|
+
|
|
3280
|
+
1. **The database decides.** Every read and write runs as the signed-in user.
|
|
3281
|
+
Row-level security reads their capabilities off the session and filters or
|
|
3282
|
+
refuses. Nothing you write in a component changes what they can reach.
|
|
3283
|
+
2. **Your app has to EXPLAIN that.** RLS refuses silently \u2014 a denied read comes
|
|
3284
|
+
back as an empty list, not an error. If you don't check first, a user with no
|
|
3285
|
+
access sees "Invoices (0)" and reports missing data.
|
|
3286
|
+
|
|
3287
|
+
So: **the database is the guarantee, your UI is the explanation.** Never write
|
|
3288
|
+
one without the other.
|
|
3289
|
+
|
|
3290
|
+
## Declaring a role
|
|
3291
|
+
|
|
3292
|
+
Roles go in \`public/turbobase.json\`, alongside your tables and writes:
|
|
3293
|
+
|
|
3294
|
+
\`\`\`json
|
|
3295
|
+
{
|
|
3296
|
+
"roles": [
|
|
3297
|
+
{
|
|
3298
|
+
"name": "Warehouse clerk",
|
|
3299
|
+
"description": "Picks and ships orders",
|
|
3300
|
+
"capabilities": ["read:order", "write:order_fulfillment", "read:cr_pick_list"]
|
|
3301
|
+
}
|
|
3302
|
+
]
|
|
3303
|
+
}
|
|
3304
|
+
\`\`\`
|
|
3305
|
+
|
|
3306
|
+
Deploying creates it as an ordinary role \u2014 the same one an administrator sees in
|
|
3307
|
+
**Admin \u2192 Roles**, indistinguishable from one they made by hand.
|
|
3308
|
+
|
|
3309
|
+
### DECLARING GRANTS NOTHING
|
|
3310
|
+
|
|
3311
|
+
**A declared role has zero holders until an administrator assigns it.** Deploying
|
|
3312
|
+
does not give anybody access, and it does not give YOU access.
|
|
3313
|
+
|
|
3314
|
+
Never tell the user "you now have permission to X" after a deploy. Say the role
|
|
3315
|
+
exists and an administrator has to assign it in **Admin \u2192 Users**.
|
|
3316
|
+
|
|
3317
|
+
This is the same rule as declared writes: you may say what your app needs, never
|
|
3318
|
+
what it is allowed. An app that could grant itself access would make the
|
|
3319
|
+
permission system decorative.
|
|
3320
|
+
|
|
3321
|
+
### What you cannot declare
|
|
3322
|
+
|
|
3323
|
+
- **\`appRole\`** \u2014 a manifest role is always a standard role. Admin bypasses
|
|
3324
|
+
every capability check, so it is assigned, never authored. Declaring it is a
|
|
3325
|
+
deploy error, not a silently ignored key.
|
|
3326
|
+
- **\`scopes\`** \u2014 row-level narrowing ("only this subsidiary", "only my own
|
|
3327
|
+
records") is authored by an administrator. If a user needs to see fewer ROWS
|
|
3328
|
+
of a table rather than fewer tables, that is a scope, and it is their job.
|
|
3329
|
+
|
|
3330
|
+
### Changing a role later
|
|
3331
|
+
|
|
3332
|
+
Adding a capability to a declared role and redeploying adds it. **Removing one
|
|
3333
|
+
from the manifest does NOT remove it from the role** \u2014 a role can have live
|
|
3334
|
+
holders, and a deploy must never be able to revoke someone's access. Ask an
|
|
3335
|
+
administrator to narrow it in the role editor.
|
|
3336
|
+
|
|
3337
|
+
Run \`turbobase apps plan\` to see exactly what a deploy would create or widen
|
|
3338
|
+
before you ship it. It writes nothing.
|
|
3339
|
+
|
|
3340
|
+
## Capabilities
|
|
3341
|
+
|
|
3342
|
+
The vocabulary is \`<verb>:<record>\`:
|
|
3343
|
+
|
|
3344
|
+
| Capability | Means |
|
|
3345
|
+
| --- | --- |
|
|
3346
|
+
| \`read:order\` | see orders |
|
|
3347
|
+
| \`write:invoice\` | create/update invoices |
|
|
3348
|
+
| \`delete:invoice\` | delete invoices (\`write\` does NOT imply it) |
|
|
3349
|
+
| \`read:cr_pick_list\` | see the rows of a custom table your app declared |
|
|
3350
|
+
| \`read:entity:customer\` | see customers specifically |
|
|
3351
|
+
|
|
3352
|
+
**Gate on the same strings you declared.** If the role says
|
|
3353
|
+
\`write:order_fulfillment\`, the ship button checks \`write:order_fulfillment\`. A
|
|
3354
|
+
screen that gates on a capability no role grants is unreachable; a role that
|
|
3355
|
+
grants a capability nothing gates is invisible.
|
|
3356
|
+
|
|
3357
|
+
## Gating the UI
|
|
3358
|
+
|
|
3359
|
+
\`src/lib/turbobase.ts\` gives you three things:
|
|
3360
|
+
|
|
3361
|
+
\`\`\`ts
|
|
3362
|
+
import {
|
|
3363
|
+
hasCapability,
|
|
3364
|
+
requireCapability,
|
|
3365
|
+
TurbobasePermissionError,
|
|
3366
|
+
} from './lib/turbobase';
|
|
3367
|
+
\`\`\`
|
|
3368
|
+
|
|
3369
|
+
### Hide what they cannot open
|
|
3370
|
+
|
|
3371
|
+
\`\`\`tsx
|
|
3372
|
+
{hasCapability('read:invoice') && <NavLink to="/invoices">Invoices</NavLink>}
|
|
3373
|
+
\`\`\`
|
|
3374
|
+
|
|
3375
|
+
### Check BEFORE you render a list \u2014 this is the one people miss
|
|
3376
|
+
|
|
3377
|
+
\`\`\`tsx
|
|
3378
|
+
if (!hasCapability('read:invoice')) {
|
|
3379
|
+
return <Empty>You don't have access to invoices. Ask an administrator for the Auditor role.</Empty>;
|
|
3380
|
+
}
|
|
3381
|
+
const invoices = await select('invoice?select=*');
|
|
3382
|
+
\`\`\`
|
|
3383
|
+
|
|
3384
|
+
Without that check the query succeeds and returns \`[]\`, and the screen says
|
|
3385
|
+
"No invoices yet" to someone who simply may not see them. An empty state and a
|
|
3386
|
+
denial must never look the same.
|
|
3387
|
+
|
|
3388
|
+
### Catch a denied write and name the role
|
|
3389
|
+
|
|
3390
|
+
\`\`\`tsx
|
|
3391
|
+
try {
|
|
3392
|
+
await write('itemFulfillment', { parent, lines });
|
|
3393
|
+
} catch (e) {
|
|
3394
|
+
if (e instanceof TurbobasePermissionError) {
|
|
3395
|
+
setError("You don't have permission to ship orders \u2014 ask an administrator for the Warehouse clerk role.");
|
|
3396
|
+
return;
|
|
3397
|
+
}
|
|
3398
|
+
throw e;
|
|
3399
|
+
}
|
|
3400
|
+
\`\`\`
|
|
3401
|
+
|
|
3402
|
+
A refused write throws \`TurbobasePermissionError\` specifically, so you can tell
|
|
3403
|
+
it apart from a validation failure. Showing a raw error for a permission problem
|
|
3404
|
+
sends the user to support instead of to their administrator.
|
|
3405
|
+
|
|
3406
|
+
### hasCapability is UX, not security
|
|
3407
|
+
|
|
3408
|
+
It reads the session's own claims, so it is exactly as trustworthy as the user's
|
|
3409
|
+
browser. It is there to make the interface honest, never to protect anything.
|
|
3410
|
+
Whatever it hides, the database still refuses \u2014 and whatever it shows, the
|
|
3411
|
+
database still decides. Never use it to protect data, and never skip it and let
|
|
3412
|
+
a denial look like emptiness.
|
|
3413
|
+
|
|
3414
|
+
## Checklist when adding a screen
|
|
3415
|
+
|
|
3416
|
+
- Which capability does this screen need? Is it in a role in
|
|
3417
|
+
\`public/turbobase.json\`?
|
|
3418
|
+
- Does the nav entry check \`hasCapability\`?
|
|
3419
|
+
- Does the screen check BEFORE rendering, with a message naming the role?
|
|
3420
|
+
- Does every write catch \`TurbobasePermissionError\`?
|
|
3421
|
+
- Did you run \`turbobase apps plan\`?
|
|
3422
|
+
- Did you tell the user their administrator still has to ASSIGN the role?
|
|
3423
|
+
`,U0=`---
|
|
3139
3424
|
name: app-design
|
|
3140
3425
|
description: How a Turbobase app should look and behave. Read the published design system first, then the display rules here that stop a working build showing wrong data. Use before building any screen.
|
|
3141
3426
|
---
|
|
@@ -3215,7 +3500,7 @@ The design system covers the look. Two rules it does not:
|
|
|
3215
3500
|
Load it in the browser and check: does it render with ZERO rows, with ONE row,
|
|
3216
3501
|
and with several hundred? Does it survive the query failing? Does tab reach every
|
|
3217
3502
|
control, with a visible focus ring? A green \`npm run build\` proves none of these.
|
|
3218
|
-
`,
|
|
3503
|
+
`,Xi="",wy=String.raw`{
|
|
3219
3504
|
"_comment": [
|
|
3220
3505
|
"Declarative sync config — part of this repo's desired state.",
|
|
3221
3506
|
" turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
|
|
@@ -3237,7 +3522,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
|
|
|
3237
3522
|
"fields": [],
|
|
3238
3523
|
"tables": []
|
|
3239
3524
|
}
|
|
3240
|
-
`,
|
|
3525
|
+
`,vy=String.raw`{
|
|
3241
3526
|
"_comment": [
|
|
3242
3527
|
"Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
|
|
3243
3528
|
"Removing an entry does NOT remove the schedule unless you pass --prune.",
|
|
@@ -3253,51 +3538,51 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
|
|
|
3253
3538
|
],
|
|
3254
3539
|
"schedules": []
|
|
3255
3540
|
}
|
|
3256
|
-
`,
|
|
3541
|
+
`,M0=t=>`node_modules/
|
|
3257
3542
|
|
|
3258
3543
|
# Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
|
|
3259
3544
|
.mcp.json
|
|
3260
3545
|
|
|
3261
3546
|
.DS_Store
|
|
3262
|
-
`;function
|
|
3263
|
-
`))r(i)}return n}async function
|
|
3264
|
-
`)}),n=e.sleep??
|
|
3547
|
+
`;function nu(t={}){let e=b0.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:M0(r)},{path:"INSTANCE-LEARNINGS.md",content:A0(o)},{path:"TURBOBASE-FEEDBACK.md",content:I0(o)},{path:".claude/settings.json",content:z0},{path:`.claude/output-styles/${C0}.md`,content:N0},{path:".claude/skills/generate-types/SKILL.md",content:w0(n)},{path:".claude/skills/record-learning/SKILL.md",content:P0(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:R0},{path:".claude/hooks/session-start-refresh-types.sh",content:O0(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:j0,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:L0}];return r?[{path:"CLAUDE.md",content:x0(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:T0},{path:".claude/skills/ship-app/SKILL.md",content:E0},{path:".claude/skills/app-design/SKILL.md",content:U0},{path:".claude/skills/roles-and-permissions/SKILL.md",content:D0},...S0(),{path:"conduits/.gitkeep",content:Xi},{path:"turbobase/sync.json",content:wy},{path:"turbobase/schedules.json",content:vy},...by()]:[{path:"CLAUDE.md",content:y0},...s,{path:".claude/skills/mock-test/SKILL.md",content:v0},{path:".claude/skills/deploy/SKILL.md",content:_0},{path:"hooks/.gitkeep",content:Xi},{path:"conduits/.gitkeep",content:Xi},{path:"samples/.gitkeep",content:Xi},{path:"turbobase/sync.json",content:wy},{path:"turbobase/schedules.json",content:vy}]}import{promises as su}from"node:fs";import{join as Er,resolve as Ey}from"node:path";function $y(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var us="bundle.json",Qi="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 ou(a)}function ou(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(ky)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(ky)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function ky(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Ty(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}")`}}var ra="hooks",na="conduits",Vr="turbobase/sync.json",Kr="turbobase/schedules.json";function iu(t){let e=c=>{let l=new RegExp(`${c}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return l?l[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineHook\s*[<(]/.test(t);if(!r&&!n)return null;let o=e("id"),s=e("recordType");if(r){let c=e("on"),l=e("source");return!o||!s||!c||!l?null:{id:o,recordType:s,event:c,source:l,extensionKind:"conduit"}}let i=e("event"),a=e("source")??"standalone";return!o||!s||!i?null:{id:o,recordType:s,event:i,source:a,extensionKind:"hook"}}async function ea(t){let e;try{e=await su.readdir(t,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of e){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let o of await ea(Er(t,n.name)))r.push(`${n.name}/${o}`);continue}n.name.endsWith(".ts")&&(n.name.endsWith(".test.ts")||n.name.endsWith(".d.ts")||r.push(n.name))}return r.sort()}async function ta(t,e){let r;try{r=await su.readFile(t,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${e} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function q0(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function Z0(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function B0(t){let e={name:String(t.name??""),scheduleKind:String(t.scheduleKind??"cron"),scheduleExpr:String(t.scheduleExpr??""),scheduleTz:String(t.scheduleTz??"UTC"),body:t.body??{}};return typeof t.status=="string"&&(e.status=t.status),e}async function Ry(t=process.cwd()){let e=Ey(t),[r,n]=await Promise.all([ea(Er(e,ra)),ea(Er(e,na))]);if(r.length>0||n.length>0)return!0;let[o,s]=await Promise.all([ta(Er(e,Vr),Vr).catch(()=>{}),ta(Er(e,Kr),Kr).catch(()=>{})]);return o!==void 0||s!==void 0}async function Py(t=process.cwd(),e={}){let r=Ey(t),n=$y(e.tenant),o=[],s=[];for(let c of[ra,na])for(let l of await ea(Er(r,c))){let u=`${c}/${l}`,p=await su.readFile(Er(r,c,l),"utf8"),w=iu(p);if(!w){/\bdefine(Hook|Conduit)\s*[<(]/.test(p)&&s.push({file:u,reason:"could not read id / recordType / event"});continue}let m={id:w.id,kind:w.extensionKind,recordType:w.recordType,event:w.event,source:w.source,sourceCode:p};w.extensionKind==="conduit"?n.conduits.push(m):n.hooks.push(m),o.push(u)}let i=await ta(Er(r,Vr),Vr);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Vr} must be a JSON object with "fields" and/or "tables".`);let c=i;for(let l of Array.isArray(c.fields)?c.fields:[])n.sync.fields.push(q0(l));for(let l of Array.isArray(c.tables)?c.tables:[])n.sync.tables.push(Z0(l));o.push(Vr)}let a=await ta(Er(r,Kr),Kr);if(a!==void 0){let c=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(c===null)throw new Error(`${Kr} must be a JSON array, or an object with a "schedules" array.`);for(let l of c)n.schedules.push(B0(l));o.push(Kr)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(c=>c.event==="before_save").map(c=>c.id).sort(),{manifest:ou(n),contributed:o,unparsed:s}}import{promises as lu}from"node:fs";import{resolve as G0}from"node:path";var F0="For app developers \u2014 adopt these";function Ay(t){let e=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(t.trim());return e?{core:[Number(e[1]),Number(e[2]??0),Number(e[3]??0)],prerelease:e[4]??""}:null}function Iy(t,e){let r=Ay(t),n=Ay(e);if(!r&&!n)return 0;if(!r)return-1;if(!n)return 1;for(let o=0;o<3;o++){let s=(r.core[o]??0)-(n.core[o]??0);if(s!==0)return s}return r.prerelease===n.prerelease?0:r.prerelease?n.prerelease?r.prerelease<n.prerelease?-1:1:-1:1}function H0(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var _q=H0(F0);os();Sr();var V0=t=>new Promise(e=>setTimeout(e,t));function Oy(t){return t.stage==="completed"||t.stage==="failed"}function K0(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function W0(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(`
|
|
3548
|
+
`))r(i)}return n}async function au(t,e={}){let r=e.sink??(w=>{process.stdout.write(`${w}
|
|
3549
|
+
`)}),n=e.sleep??V0,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(w=>r(K0(w))),a=e.onPoll,c="",l="",u=w=>{a?.(w),w.stage!==l&&i(w),c=W0(w,c,r),l=w.stage},p=await t();if(u(p),Oy(p))return p;for(let w=0;w<s;w+=1)if(await n(o),p=await t(),u(p),Oy(p))return p;return p}var _=t=>{process.stdout.write(`${t}
|
|
3265
3550
|
`)},q=t=>{process.stderr.write(`${t}
|
|
3266
|
-
`)};function x(t){q(g.red(`turbobase: ${t}`)),process.exit(1)}var
|
|
3267
|
-
`)){let o=
|
|
3551
|
+
`)};function x(t){q(g.red(`turbobase: ${t}`)),process.exit(1)}var ds=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Cy(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&Ql(!1)}async function ne(t){let e=await Yt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await $r();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";x(`not signed in to ${Lt(t)}.${n} Run \`turbobase auth login --base-url ${Lt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&x("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ft())try{let n=await mt("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await Bi(n);let o=await Yt();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}x(`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 se(t,e,r){if(!(t instanceof pe)||t.status!==403)return;t.body?.error==="approval_required"&&x(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),x(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function cu(t,e,r){let n=r?Number(r):void 0;if(Gi()){let s=tu(e),i;try{i=await au(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(),x(`${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 au(t,{sink:_,intervalMs:n})}catch(s){x(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&x(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),_(`${e} ${o.stage}.`)}var J0=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function Y0(t){try{let e=await lu.readFile(t,"utf8");return J0.exec(e)?.[1]??null}catch{return null}}var X0=/GENERATED by `turbobase project adopt`/,zy=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,Q0=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Ny(t){let e=[],r=null;for(let n of t.split(`
|
|
3552
|
+
`)){let o=zy.exec(n);if(o){r={version:o[1],items:[]},e.push(r);continue}if(/^#{1,6}[ \t]/.test(n)){r=null;continue}if(!r)continue;let s=Q0.exec(n);if(s){let a=s[2].trim();r.items.push({key:a.replace(/\s+/g," "),done:s[1]!==" ",text:a,extra:[]});continue}let i=r.items[r.items.length-1];i&&n.trim()!==""&&i.extra.push(n)}return e}function eR(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
|
|
3268
3553
|
`)).join(`
|
|
3269
3554
|
`);return`## v${t.version}
|
|
3270
3555
|
|
|
3271
|
-
${e}`}function
|
|
3272
|
-
`),a=i.findIndex(u=>
|
|
3556
|
+
${e}`}function tR(t,e){let r=Ny(t);if(r.length===0&&!X0.test(t))return null;let n=new Map(r.map(u=>[u.version,u])),o=[],s=0;for(let u of Ny(e)){let p=n.get(u.version);n.delete(u.version);let w=new Set(u.items.map(h=>h.key)),m=u.items.map(h=>{let b=p?.items.find($=>$.key===h.key);return b?{...h,done:b.done,extra:b.extra}:h});for(let h of p?.items??[])w.has(h.key)||h.done||(m.push(h),s+=1);o.push({version:u.version,items:m})}for(let u of n.values()){let p=u.items.filter(w=>!w.done);p.length!==0&&(s+=p.length,o.push({version:u.version,items:p}))}o.sort((u,p)=>Iy(p.version,u.version));let i=e.split(`
|
|
3557
|
+
`),a=i.findIndex(u=>zy.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
|
|
3273
3558
|
`).replace(/\s+$/,"");return{markdown:o.length===0?`${c}
|
|
3274
3559
|
`:`${c}
|
|
3275
3560
|
|
|
3276
|
-
${o.map(
|
|
3561
|
+
${o.map(eR).join(`
|
|
3277
3562
|
|
|
3278
3563
|
`)}
|
|
3279
|
-
`,carried:s}}function
|
|
3280
|
-
|
|
3281
|
-
`,m=await
|
|
3282
|
-
`);for(let n of r.slice(0,
|
|
3283
|
-
`)),_(
|
|
3284
|
-
`))}catch(l){if(l instanceof pe&&l.status===409){q(g.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),q(`re-run \`${
|
|
3285
|
-
`))}async function
|
|
3286
|
-
`))r.push(` ${g.dim("|")} ${a}`)}r.push("")}),r}function
|
|
3287
|
-
`)),_(
|
|
3288
|
-
`+g.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}_(Xt(o.map(Qy),{head:
|
|
3289
|
-
`))}async function
|
|
3564
|
+
`,carried:s}}function jy(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 ne(e.baseUrl),o=G0(process.cwd(),e.out),s=e.since?.trim()||await Y0(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||x(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){_(`${r} ships no release notes to adopt from (nothing written).`);return}let u=l.releases.reduce(($,E)=>$+E.items.length,0);if(u===0){_(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${l.currentVersion?` (instance is on v${l.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let p=l.currentVersion??l.releases[0]?.version??"",w=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${p}. Re-run to refresh; delete this file once every line is done. -->
|
|
3565
|
+
|
|
3566
|
+
`,m=await lu.readFile(o,"utf8").catch(()=>null),h=l.markdown,b=0;if(m!==null&&m.trim()!==""){let $=tR(m,l.markdown);$||x(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),h=$.markdown,b=$.carried}await lu.writeFile(o,w+h,"utf8"),_(`wrote ${o} \u2014 ${u} item(s) across ${l.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${b>0?`, keeping ${b} unticked item(s) already in the file`:""}.`)})}Sr();var ps=["suggested_kb_edit","kb_correction"];var rR=[{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:"Platform asks",section:"platform_feedback",ranked:!1},{heading:"Requested rollups",section:"platform_feedback",ranked:!1},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function nR(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var Nq=new Map(rR.map(t=>[nR(t.heading),t]));var zq=new RegExp(["^the (situation|context|background|problem|ask|point|gist|upshot|part\\b)","^the (one|two|three|four|five|six|seven|eight|nine|ten|\\d{1,2}) \\w+s?\\b","^(on|about) \\w+ing\\b","^(concrete|specific|possible|suggested) \\w+","^what (we|i|you)(\\b|'d| would| could| should)","^(background|summary|context|recommendations?|next steps|takeaways?|conclusion|in short|tl;?dr)\\b","^why (this|that|it) matters\\b"].join("|"),"i");function oR(t){return t.diff??!!t.dryRun}var sR={update_page:"append to the existing page",new_page:"create a NEW page"},Rr=(t,e)=>` ${g.dim(t.padEnd(11))}${e}`,Dy=t=>t.ownerEmail??t.ownerId;function po(t){return!t.needsPageRef&&!t.blockedBy}var oa=t=>g.green(t?` + ${t}`:" +"),iR=t=>g.red(t?` - ${t}`:" -"),Pn=t=>g.dim(` ${t}`),aR=` ${g.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,uu=80;function cR(t){let e=[aR];t.target?(e.push(Pn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(iR(`visibility: ${t.target.visibility}`)),e.push(oa("visibility: admin"))):e.push(Pn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(Pn("title, slug, evidence: untouched")),e.push(Pn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(Pn("turbobase.document \xB7 new")),e.push(oa(`title: ${t.pageTitle}`)),e.push(oa("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(Pn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(Pn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
|
|
3567
|
+
`);for(let n of r.slice(0,uu))e.push(oa(n?` ${n}`:""));return r.length>uu&&e.push(g.yellow(` \u2026 ${r.length-uu} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function lR(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${g.bold(n.pageTitle)}`),r.push(Rr("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:g.dim("new \u2014 no existing page matches"))),r.push(Rr("action",po(n)?sR[n.action]:g.red("SKIP \u2014 nothing is written"))),n.needsPageRef){let a=[...new Set(i.map(c=>c.kb_page_ref?.trim()).filter(c=>!!c))];r.push(Rr("unresolved",g.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(Rr("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?` ${g.dim(`\xB7 ${a.verdict}`)}`:"",l=a.kb_page_ref?` ${g.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${g.dim("\xB7")} ${a.title.trim()}${l}${c}`)}),r.push(Rr("confidence",n.withdraws?g.red("WITHDRAWN from readers (text untouched)"):g.dim("untouched"))),n.supersedes&&r.push(Rr("supersedes",g.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(Rr("blocked",g.red(`unpublished work on this page belongs to ${Dy(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Rr("ambiguous",g.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(p=>p.key===c),u=l>=0?t[l]:void 0;return u?`#${l+1} "${u.pageTitle}"`:c});r.push(Rr("similar",g.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&&po(n)&&r.push(...cR(n)),r.push("")}),r}function uR(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"}`,`${e(po)} page(s)`,`${e(l=>l.action==="update_page"&&po(l))} appended`,`${e(l=>l.action==="new_page"&&po(l))} created (unpublished)`,...s>0?[g.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?g.red(`${n} page(s) WITHDRAWN from readers`):g.dim("no page withdrawn"),c=o>0?` \xB7 ${g.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${c}`}function dR(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(`${g.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?Dy(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(`${g.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(`${g.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?g.green("created "):g.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${g.bold(o.documentId??"?")}`+(o.created?g.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${g.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${g.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${g.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Ly(t){if(t instanceof pe){let e=t.body;t.status===403&&e?.reason==="admin_required"&&x("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&&x("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}se(t,"extensions:deploy","learnings push-kb")}async function hs(t,e){let r;try{r=await ae("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof pe&&o.status===404?q(g.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):q(g.yellow(`could not re-read the pushed markdown: ${pR(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return q(g.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),r;let n=[`${r.filesScanned} file(s) scanned`];return r.docsIngested>0&&n.push(`${r.docsIngested} changed`),r.docsUnchanged>0&&n.push(`${r.docsUnchanged} unchanged`),n.push(`${r.entriesAdded} new finding(s)`),r.entriesDuplicate>0&&n.push(`${r.entriesDuplicate} already known`),r.parseSkipped>0&&n.push(g.yellow(`${r.parseSkipped} unparseable`)),q(g.dim(n.join(" \xB7 "))),r}function pR(t){return t instanceof Error?t.message:String(t)}async function Uy(t,e=r=>new X(r)){t.section&&!ps.includes(t.section.trim())&&x(`unknown --section "${t.section}" \u2014 expected one of ${ps.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&x("--limit must be a positive integer.");let r=await ne(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=await hs(n,t.app),i;try{i=await ae("reading the pending queue",()=>n.learningsPending(o))}catch(l){Ly(l),x(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){q(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}q(i.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${i.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(_(lR(i.items,{diff:oR(t)}).join(`
|
|
3568
|
+
`)),_(uR(i.items)),t.dryRun){q(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(po);if(a.length===0){q(g.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let c=a.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!ft()){q(g.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 mt(`Push ${c} finding(s) into the knowledge base as ${a.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"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await ae("writing pages",()=>n.learningsPushKb(i.planToken,o));_(dR(l.applied,i.items).join(`
|
|
3569
|
+
`))}catch(l){if(l instanceof pe&&l.status===409){q(g.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),q(`re-run \`${ds} kb push\` to review the current plan.`),process.exitCode=2;return}Ly(l),q(g.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}Sr();var ho=t=>new X(t);async function fo(t,e){let r=await ne(t.baseUrl);return e(r)}async function sa(t,e,r,n){return n.yes?!0:ft()?await mt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function hR(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function My(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function fR(t){if(t.items.length===0)return["no pages in this knowledge base."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${My(g.bold(s.slug),e)} ${My(hR(s),10)} ${g.dim(s.path)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} page(s) \xB7 ${n} readable \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function qy(t,e=ho){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&x(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await fo(t,e),o;try{o=await ae("reading the knowledge base",()=>n.docsList(r))}catch(s){se(s,"docs:publish","read the knowledge base"),x(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}_(fR(o).join(`
|
|
3570
|
+
`))}async function Zy(t,e,r=ho){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&x("name at least one page slug. `turbobase kb list` shows them.");let o=await fo(e,r);if(!await sa(`Publish ${n.length} page(s)?`,"Yes \u2014 publish them","every member can read them, and retrieval can ground answers on them, from now on",e))return;let i;try{i=await ae("publishing",()=>o.docsPublish(n))}catch(c){se(c,"docs:publish","publish a page"),x(`publish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.published.map(c=>c.slug);_(g.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(q(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),q(g.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function By(t,e,r=ho){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&x("name at least one page slug. `turbobase kb list` shows them.");let o=await fo(e,r);if(!await sa(`Hide ${n.length} page(s) from readers?`,"Yes \u2014 unpublish them","they drop out of the reader snapshot immediately; the text and its history are kept",e))return;let i;try{i=await ae("unpublishing",()=>o.docsUnpublish(n))}catch(c){se(c,"docs:publish","unpublish a page"),x(`unpublish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.unpublished.map(c=>c.slug);_(g.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),q(g.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(q(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Fy(t,e=ho){let r=await fo(t,e),n;try{n=await ae("reading the releases",()=>r.docsVersions())}catch(o){se(o,"docs:publish","read the knowledge-base releases"),x(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){_("no releases yet \u2014 nothing has been published.");return}for(let o of n.items){let s=o.is_current?g.green("current"):g.dim(" ");_(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${g.dim(o.published_by)}`:""}`),o.release_note&&_(` ${g.dim(o.release_note)}`)}}async function Hy(t,e,r=ho){let n=Number(t);(!Number.isInteger(n)||n<1)&&x(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await fo(e,r);if(await sa(`Roll the knowledge base back to release v${n}?`,"Yes \u2014 roll it back","every reader sees that release\u2019s content until something is published again",e))try{let i=await ae("rolling back",()=>o.docsRollback(n));_(g.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){se(i,"docs:publish","roll the knowledge base back"),x(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Vy(t,e,r=ho){let n=(t??"").trim();n||x("name the page slug to delete. `turbobase kb list` shows them.");let o=await fo(e,r);if(await sa(`Delete "${n}"?`,"Yes \u2014 delete it","it drops out of the tree and every reader release; its subtree goes with it, and it stays restorable from the editor\u2019s trash",e))try{let i=await ae("deleting",()=>o.docsDelete(n));_(g.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){se(i,"docs:publish","delete a page"),x(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}Sr();function mR(t){return t.diff??!!t.dryRun}function gR(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?g.green("new rule"):g.yellow("amend rule"),i=n.targetPublished?` ${g.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${g.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${g.dim(n.description)}`);for(let a of n.entries)r.push(` ${g.dim("\xB7")} ${g.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
|
|
3571
|
+
`))r.push(` ${g.dim("|")} ${a}`)}r.push("")}),r}function yR(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(g.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function Ky(t,e=r=>new X(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&x("--limit must be a positive integer.");let r=await ne(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},s=await hs(n,t.app),i;try{i=await ae("reading the pending rules",()=>n.rulesPending(o))}catch(c){se(c,"extensions:deploy","read the pending rules"),x(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){q(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}q(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(_(gR(i.items,{diff:mR(t)}).join(`
|
|
3572
|
+
`)),_(yR(i.items)),t.dryRun){q(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((c,l)=>c+l.entries.length,0);if(!t.yes){if(!ft()){q(g.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 mt(`Push ${a} finding(s) as ${i.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land as DRAFTS; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await ae("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof pe&&c.status===409&&x("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),x(`push failed: ${c instanceof Error?c.message:String(c)}`)}_(g.green(`wrote ${i.items.length} draft rule(s).`)),q(g.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}Sr();var bR=["proposed","active","rejected"],wR=["mechanic","operator","learning","code-baseline"],ia=t=>new X(t);async function aa(t,e){let r=await ne(t.baseUrl);return e(r)}function Wy(t,e,r){if(!t)return;let n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length!==0){for(let o of n)e.includes(o)||x(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function vR(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&x("--limit must be a positive number."),Math.floor(e)}function Yy(t){let e=Wy(t.status,bR,"--status"),r=Wy(t.provenance,wR,"--provenance"),n=vR(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function Gy(t){return!!(t.provenance?.length||t.recordType||t.source)}var Xy=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function _R(t){return t.status==="active"?g.green("active"):t.status==="rejected"?g.dim("rejected"):g.yellow("proposed")}function xR(t){return t.message?t.message:t.kind&&t.field?g.dim(`${t.kind} ${t.field}`):t.kind?g.dim(t.kind):g.dim("(no description)")}function Qy(t){return[t.hookId,_R(t),t.provenance==="learning"?g.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),xR(t)]}async function eb(t={},e=ia){let r=await aa(t,e),n=Yy(t),o;try{o=await r.proposals(n)}catch(i){se(i,"extensions:deploy","list hook proposals"),x(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return _(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return _(`no ${i} hook proposals.
|
|
3573
|
+
`+g.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}_(Xt(o.map(Qy),{head:Xy})),_(g.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let s=o.filter(i=>i.provenance==="learning"&&i.status==="proposed");s.length>0&&_(g.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function kR(t,e,r){return r.yes?!0:ft()?await mt(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function $R(t){return!(t instanceof pe)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function du(t,e){$R(t)&&se(t,"extensions:deploy",e)}function pu(t,e){let r=e instanceof pe?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);q(He.error(`${g.bold(t)} \u2014 ${s}`))}async function Jy(t,e){try{let r=await t.proposalPromote(e);return _(He.success(`${g.bold(e)} ${g.dim(`${r.previousStatus} \u2192`)} ${g.green(r.status)}`)),!0}catch(r){return du(r,"promote a hook proposal"),pu(e,r),!1}}async function tb(t,e={},r=ia){!e.auto&&t.length===0&&x("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&x("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&x("promote: --apply / --all only mean something with --auto.");let n=await aa(e,r);if(!e.auto){let u=0;for(let p of t)await Jy(n,p)&&(u+=1);u>0&&_(g.dim(` ${u} hook(s) armed \u2014 the loader compiles them on its next reload.`)),u<t.length&&(process.exitCode=1);return}let o=Yy({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&x("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),o.status?.some(u=>u!=="proposed")&&x("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(u){se(u,"extensions:deploy","list hook proposals"),x(`list hook proposals failed: ${u instanceof Error?u.message:String(u)}`)}let i=s.filter(u=>u.provenance==="learning"),a=s.filter(u=>u.provenance!=="learning");if(e.json&&(_(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(_(`nothing to promote${Gy(o)?" for that filter":""}.`),i.length>0&&_(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(_(e.apply?`promoting ${g.bold(String(a.length))} hook proposal(s):`:`${g.bold("dry run")} \u2014 would promote ${g.bold(String(a.length))} hook proposal(s):`),_(Xt(a.map(Qy),{head:Xy})),i.length>0&&_(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){_(""),_(He.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Gy(o)&&!e.all&&x(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await kR(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let l=0;for(let u of a)await Jy(n,u.hookId)&&(l+=1);_(g.dim(` ${l}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),l<a.length&&(process.exitCode=1)}async function rb(t,e={},r=ia){t.length===0&&x("retract: name at least one proposal id.");let n=await aa(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);_(He.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.yellow(i.status)}`)),o+=1}catch(i){du(i,"retract a hook proposal"),pu(s,i)}o>0&&_(g.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function nb(t,e={},r=ia){t.length===0&&x("reject: name at least one proposal id.");let n=await aa(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);_(He.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.dim(i.status)}`)),o+=1}catch(i){du(i,"reject a hook proposal"),pu(s,i)}o<t.length&&(process.exitCode=1)}Sr();var mo=t=>new X(t);async function go(t,e){let r=await ne(t.baseUrl);return e(r)}async function ca(t,e,r,n){return n.yes?!0:ft()?await mt(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function SR(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function ob(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function TR(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${ob(g.bold(s.slug),e)} ${ob(SR(s),10)} ${s.surfaces.join(",")||g.dim("none")}`),s.description&&r.push(` ${g.dim(s.description)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} skill(s) \xB7 ${n} injected \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function sb(t,e=mo){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&x(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await go(t,e),o;try{o=await ae("reading the skills",()=>n.skillsList(r))}catch(s){se(s,"skills:publish","read the instance skills"),x(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}_(TR(o).join(`
|
|
3574
|
+
`))}async function ib(t,e,r=mo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&x("name at least one skill slug. `turbobase skills list` shows them.");let o=await go(e,r);if(!await ca(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await ae("publishing",()=>o.skillsPublish(n))}catch(a){se(a,"skills:publish","publish a skill"),x(`publish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),q(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function ab(t,e,r=mo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&x("name at least one skill slug. `turbobase skills list` shows them.");let o=await go(e,r);if(!await ca(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await ae("unpublishing",()=>o.skillsUnpublish(n))}catch(a){se(a,"skills:publish","unpublish a skill"),x(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),q(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function cb(t,e,r=mo){let n=Number(t);(!Number.isInteger(n)||n<1)&&x(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await go(e,r);if(await ca(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await ae("rolling back",()=>o.skillsRollback(n));_(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){se(i,"skills:publish","roll back a skills release"),x(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function lb(t,e=mo){let r=await go(t,e),n;try{n=await ae("reading the releases",()=>r.skillsReleases())}catch(o){se(o,"skills:publish","read the skills releases"),x(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){q("no releases yet.");return}for(let o of n.items){let s=o.is_current?g.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";_(`${s} v${o.version_no} ${o.skill_count} skill(s) ${g.dim(o.published_at)}${o.published_by?g.dim(` by ${o.published_by}`):""}${g.dim(i)}`)}}async function ub(t,e,r=mo){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&x("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await go(e,r);if(!await ca(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
|
|
3290
3575
|
${n.join(`
|
|
3291
|
-
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let l of n)try{i.push(await ae(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof pe&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),
|
|
3292
|
-
`,{mode:384})}async function tP(t){let e=await wu();e.push(t),await vb(e)}async function _b(t){let e=await wu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await vb(e),n??null}async function la(){return wu()}function vu(t,e=Date.now()){let r=[],n=[];for(let o of t)BR(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function xb(t,e){bu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new gs(r);let n=FR(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>YR(l)))(e.fromTenant),i=XR(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=HR(l.rows,n),p=GR(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ZR(e.ttl,o),sampleFraction:n,url:eP(s,e.baseUrl)};return await tP(c),c}async function kb(t,e){bu(t.target());let n=(await la()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await _b(e),n):null}async function _u(t,e=Date.now()){bu(t.target());let r=await la(),{expired:n}=vu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await _b(s.name),o.push(s)}return o}var ys={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish"],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"}},mZ=Object.keys(ys).filter(t=>ys[t].mintable);var bZ=ys.pat.prefix,rP=Object.entries(ys).map(([t,e])=>[e.prefix,t]),nP=/^[A-Za-z0-9_-]{20,}$/;function oP(t){if(typeof t!="string")return null;for(let[e,r]of rP)if(t.startsWith(e)&&nP.test(t.slice(e.length)))return r;return null}function $b(t){return oP(t)==="pat"}ss();var sP=8e3,iP={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function aP(t){return iP[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function cP(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(sP)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Sb(t){return t.state==="accepted"?et()?g.green("accepted"):"accepted":t.state==="rejected"?et()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:et()?g.yellow("unreachable"):"unreachable"}async function Tb(t={},e=fetch){let r=await Sr(),{file:n}=qi();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Qt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await cP(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(et())_(Xt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Sb(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Sb(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${aP(i.check.reason)}.`)),q(g.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function OD(t){let e=await Sr();e.length===0&&x("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ht()||x("this command needs an explicit <base-url> in a non-interactive shell.");try{return await ft(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{x("cancelled.")}}async function CD(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}`}}function ND(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function zD(t,e,r){let n=await Ug({baseUrl:t,token:e}),o=(await Sr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),ND(n.baseUrl),!r)return;let s=await CD(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function jD(t){let e=await ls(t),r=su(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);x(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Go(t,e,r,n){try{return await ye.access(t),"skipped"}catch{}return await ye.mkdir(Ko(t),{recursive:!0}),await ye.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ye.chmod(t,n),"wrote"}async function TS(t,e){if(ES(t)!==".gitignore")return Go(t,e.content,e.executable,e.mode);let r=await ye.readFile(t,"utf8").catch(()=>null);if(r===null)return Go(t,e.content,e.executable,e.mode);let n=vy(r);return n===null?"skipped":(await ye.writeFile(t,n,"utf8"),"merged")}function Lm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;x(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function rl(t){process.exit(t)}function LD(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 DD(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 UD(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 Bm({includeInternal:t=!0}={}){let e=new cg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.5.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Xl()}
|
|
3293
|
-
`),e.hook("preAction",(d,f)=>{
|
|
3294
|
-
${
|
|
3295
|
-
`).length} lines).`)}),
|
|
3576
|
+
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let l of n)try{i.push(await ae(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof pe&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),se(u,"skills:publish","delete a skill"),x(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&_(g.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&q(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(q(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as db}from"node:fs";import{join as ER,relative as RR,resolve as PR,sep as AR}from"node:path";var IR=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),OR=new Set([".mcp.json",".env"]);function CR(t){return OR.has(t)||t.startsWith(".env.")&&t!==".env.example"}function NR(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function zR(t){return t.includes(0)}async function pb(t){let e=PR(t),r={},n=[],o=[],s=[];async function i(a){let c=await db.readdir(a,{withFileTypes:!0});for(let l of c){let u=ER(a,l.name);if(l.isDirectory()){if(IR.has(l.name))continue;await i(u);continue}if(!l.isFile())continue;let p=RR(e,u).split(AR).join("/");if(CR(l.name)){o.push(p);continue}let w=await db.readFile(u);if(!NR(w)){n.push(p);continue}zR(w)&&s.push(p),r[p]=w.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as jR}from"node:crypto";var LR="/_tb/app-assets",DR=16,UR=/^[0-9a-f]{32}$/;function hb(){return jR(DR).toString("hex")}function MR(t){return UR.test(t)}function fb(t){if(!MR(t))throw new Error(`not a build id: ${t}`);return`${LR}/${t}/`}var mb=7;import la from"node:fs/promises";import fs from"node:path";var hu={esbuild:"0.28.1","isolated-vm":"6.1.2"},fu="@turbobase/isolated-vm-prebuilds";function mu(t,e){return`${t}-${e}`}function gu(t=process.versions){return`abi${t.modules}`}var gb=["darwin-x64","win32-arm64"];async function yb(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=mu(e,r),o=fs.join(t.home,"node_modules"),s=fs.join(o,...fu.split("/"),"prebuilds",n),i=fs.join(o,"isolated-vm","prebuilds",n),a;try{a=await la.readdir(s)}catch{return[]}let c=[];await la.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=fs.join(i,l);try{await la.copyFile(fs.join(s,l),u,la.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as qR}from"node:os";import{join as bb}from"node:path";import{promises as yu}from"node:fs";function vb(){let t=process.env.TURBOBASE_HOME??bb(qR(),".turbobase");return{dir:t,file:bb(t,"sandboxes.json")}}var ZR={s:1e3,m:6e4,h:36e5,d:864e5};function BR(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*ZR[e[2]]}function FR(t,e=Date.now()){return new Date(e+BR(t)).toISOString()}function HR(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function VR(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 KR(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 WR="[REDACTED]",ms=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},bu=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 GR(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new bu(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:WR:n[o]=s}return n}function JR(t,e,r){return e.map(n=>GR(t,n,r))}var wb=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),YR=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function XR(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 wu(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 YR)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=XR(t);if(!wb.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...wb].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function QR(t,e=eP){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function eP(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function tP(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function rP(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function vu(){let{file:t}=vb();try{let e=await yu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function _b(t){let{dir:e,file:r}=vb();await yu.mkdir(e,{recursive:!0}),await yu.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
3577
|
+
`,{mode:384})}async function nP(t){let e=await vu();e.push(t),await _b(e)}async function xb(t){let e=await vu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await _b(e),n??null}async function ua(){return vu()}function _u(t,e=Date.now()){let r=[],n=[];for(let o of t)HR(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function kb(t,e){wu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new ms(r);let n=VR(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>QR(l)))(e.fromTenant),i=tP(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=KR(l.rows,n),p=JR(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:FR(e.ttl,o),sampleFraction:n,url:rP(s,e.baseUrl)};return await nP(c),c}async function $b(t,e){wu(t.target());let n=(await ua()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await xb(e),n):null}async function xu(t,e=Date.now()){wu(t.target());let r=await ua(),{expired:n}=_u(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await xb(s.name),o.push(s)}return o}var gs={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish"],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"}},yZ=Object.keys(gs).filter(t=>gs[t].mintable);var vZ=gs.pat.prefix,oP=Object.entries(gs).map(([t,e])=>[e.prefix,t]),sP=/^[A-Za-z0-9_-]{20,}$/;function iP(t){if(typeof t!="string")return null;for(let[e,r]of oP)if(t.startsWith(e)&&sP.test(t.slice(e.length)))return r;return null}function Sb(t){return iP(t)==="pat"}os();var aP=8e3,cP={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function lP(t){return cP[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function uP(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(aP)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Tb(t){return t.state==="accepted"?tt()?g.green("accepted"):"accepted":t.state==="rejected"?tt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:tt()?g.yellow("unreachable"):"unreachable"}async function Eb(t={},e=fetch){let r=await $r(),{file:n}=Zi();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Yt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await uP(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(tt())_(Xt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Tb(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Tb(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${lP(i.check.reason)}.`)),q(g.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function ND(t){let e=await $r();e.length===0&&x("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ft()||x("this command needs an explicit <base-url> in a non-interactive shell.");try{return await mt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{x("cancelled.")}}async function zD(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}`}}function jD(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function LD(t,e,r){let n=await Mg({baseUrl:t,token:e}),o=(await $r()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),jD(n.baseUrl),!r)return;let s=await zD(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function DD(t){let e=await cs(t),r=iu(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);x(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Ko(t,e,r,n){try{return await ye.access(t),"skipped"}catch{}return await ye.mkdir(Vo(t),{recursive:!0}),await ye.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ye.chmod(t,n),"wrote"}async function ES(t,e){if(RS(t)!==".gitignore")return Ko(t,e.content,e.executable,e.mode);let r=await ye.readFile(t,"utf8").catch(()=>null);if(r===null)return Ko(t,e.content,e.executable,e.mode);let n=_y(r);return n===null?"skipped":(await ye.writeFile(t,n,"utf8"),"merged")}function Dm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;x(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function nl(t){process.exit(t)}function UD(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 MD(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 qD(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 Fm({includeInternal:t=!0}={}){let e=new lg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.5.2").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${eu()}
|
|
3578
|
+
`),e.hook("preAction",(d,f)=>{Cy(e.opts(),f.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 d=>{let f=Lt(d.baseUrl);d.token||x(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
3579
|
+
${ds} auth login --base-url ${f} --token tb_pat_\u2026`),Sb(d.token)||x("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await LD(f,d.token,d.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async d=>Eb({probe:d.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let f=d??await ND("Pick the active instance:"),v=await Bi(f);if(!v){let T=await $r();x(`no stored sign-in for ${Lt(f)}.`+(T.length?` Stored: ${T.map(k=>k.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Lt(f)} --token tb_pat_\u2026\`.`)}_(`active instance \u2192 ${v.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 d=>{if(d.all){let T=await $r();for(let k of T)await Bl(k.baseUrl);_(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let f=await Bl(d.baseUrl);f||x(d.baseUrl?`no stored sign-in for ${Lt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await Yt();_(`signed out of ${f}.`+(v?` Active instance \u2192 ${v.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 d=>{let{baseUrl:f,token:v}=await ne(d.baseUrl),T;try{T=await En({baseUrl:f,token:v,recordsOnly:d.recordsOnly})}catch(y){let S=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(S)){q("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{T=await En({baseUrl:f,token:v,recordsOnly:!0})}catch(R){x(`types generation failed: ${R instanceof Error?R.message:String(R)}`)}}else x(`types generation failed: ${S}`)}let k=xe(process.cwd(),d.out);await ye.writeFile(k,T,"utf8"),_(`wrote ${k} (${T.split(`
|
|
3580
|
+
`).length} lines).`)}),jy(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 d=>{let{baseUrl:f,token:v}=await ne(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let k=T.toString(),y=await fetch(`${f}/v1/catalog/grounding${k?`?${k}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});y.ok||x(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let R=((await y.json()).markdown??"").trim(),C=xe(process.cwd(),d.out),N=d.records?` records=${d.records}`:"",j=`<!-- GENERATED by \`turbobase project grounding\` against ${f}${N} \u2014 do not edit; re-run to refresh. -->
|
|
3296
3581
|
|
|
3297
|
-
`;await ye.writeFile(
|
|
3582
|
+
`;await ye.writeFile(C,j+(R?`${R}
|
|
3298
3583
|
`:`(no grounding available yet)
|
|
3299
|
-
`),"utf8"),_(`wrote ${
|
|
3300
|
-
${R===0?g.green(O):g.yellow(O)}`),rl(R>0?1:0)}),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 project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,f)=>{if(f.to){let S=await Dm(),{baseUrl:R,token:O}=await te(f.baseUrl),C=new Y({baseUrl:R,token:O});try{let U=await ae(`applying bundle to ${f.to}`,()=>C.configApply(S,{prune:f.prune}));_(`applied bundle to ${f.to}: +${U.applied.add} ~${U.applied.change} -${U.applied.destroy}`+(U.backfillsQueued.length?` (${U.backfillsQueued.length} backfill(s) queued)`:""));let ie=U.skippedDestroys??[];if(ie.length>0){q(`${ie.length} resource(s) exist on ${f.to} but are not declared by this project \u2014 NOT removed:`);for(let M of ie)q(` ${M.kind} ${M.id}`);q("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(U){U instanceof pe&&U.status===403&&x("apply forbidden (403) \u2014 the stored PAT is not for an admin."),x(`bundle apply failed: ${U instanceof Error?U.message:String(U)}`)}return}d||x("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:v,token:T}=await te(f.baseUrl),$=await jD(xe(process.cwd(),d)),y=new Y({baseUrl:v,token:T});try{let S=await ae(`deploying ${ES(d)}`,()=>y.deploy($));et()?_(Zr("Deployed",[`${g.bold(S.id)} ${uo(S.status)} ${g.dim(S.outcome)}`])):_(`deployed ${S.id} \u2192 status=${S.status} (${S.outcome}).`)}catch(S){S instanceof pe&&S.status===403&&x("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),x(`deploy failed: ${S instanceof Error?S.message:String(S)}`)}});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.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,f,v)=>{let T=!!(v.preview||v.replace||v.replaceLabel);v.replace&&v.replaceLabel&&x("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let $=xe(process.cwd(),f??".");await ye.mkdir($,{recursive:!0});let y=v.proposal??await b($),{baseUrl:S,token:R}=await te(v.baseUrl),O=new Y({baseUrl:S,token:R}),C=!1;try{C=(await O.appsList()).some(ke=>ke.slug===d||ke.id===d)}catch(ke){oe(ke,"extensions:deploy","deploy"),x(`could not reach ${S}: ${ke instanceof Error?ke.message:String(ke)}`)}if(!C){v.create||x(`no app "${d}" on ${S} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let ke=await ae(`creating app ${d}`,()=>u(S,R,{slug:d},{tolerateExisting:!0}));ke.existed||_(`created ${ke.slug??d}.`)}let U;if(v.replace)if(typeof v.replace=="string")U=v.replace;else{let{previews:ke}=await V(S,R,d);if(ke.length===0&&x(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),ke.length>1){for(let Xe of ke)_(` ${Xe.previewId} v${Xe.version}${Xe.label?` ${Xe.label}`:""} ${Xe.url}`);x(`${d} has ${ke.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${ke[0].previewId}\`.`)}U=ke[0].previewId}let ie;if(v.replaceLabel){let ke=v.replaceLabel,{previews:Xe}=await V(S,R,d),cr=Xe.filter(sl=>sl.label===ke);cr.length>0?(U=cr[0].previewId,cr.length>1&&q(`${cr.length} open previews carry the label "${ke}"; replacing the newest (${U}). Close the others with \`turbobase apps preview discard\`.`)):_(`no open preview labelled "${ke}" \u2014 opening one.`),ie=ke}let M=ke=>ye.stat(At($,ke)).then(()=>!0).catch(()=>!1),ne=d,Re=$,Ie=v.build!==!1;if(Ie&&!await M("package.json"))if(await M("index.html"))_("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Ie=!1;else if(v.pull===!1)x(`${$} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ke=await ae(`pulling ${d}`,()=>p(S,R,d));ne=ke.slug??d,await w($,ke.files,!0),_(`pulled generated source (rev ${ke.rev}).`)}let Yn;if(Ie){let ke=pb();if(Yn={buildId:ke,assetBase:hb(ke)},v.install!==!1&&!await M("node_modules")){_("installing dependencies\u2026");try{await E(["install"],$)}catch(Xe){x(`npm install failed: ${Xe instanceof Error?Xe.message:String(Xe)}`)}}_("building\u2026");try{await E(["run","build"],$,{TURBOBASE_ASSET_BASE:Yn.assetBase})}catch(Xe){x(`build failed: ${Xe instanceof Error?Xe.message:String(Xe)}`)}await M("dist")||x(`no dist/ after build in ${$} \u2014 check the app's build script.`),Re=At($,"dist")}T&&!Yn&&x(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${ne}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let vt=await Q(S,R,ne,Re,v.entry,y,Yn,T?{label:v.label??ie,replacePreviewId:U}:void 0);if(T){let ke=vt.previewUrl??"(no url returned)",Xe=vt.expiresAt?new Date(vt.expiresAt).toLocaleDateString():`${fb} days`,cr=vt.replacedVersion==null?null:`replaced v${vt.replacedVersion} \u2014 same URL`;if(et())_(Zr(cr?"Preview replaced":"Preview deployed",[`${g.bold(ne)} ${g.green(`v${vt.version??"?"}`)} ${g.dim("not live")}`,`${g.bold(ke)}`,...cr?[g.dim(cr)]:[],g.dim(`expires ${Xe}`)]));else{let sl=cr?`; ${cr}`:"";_(`preview ${ne} v${vt.version??"?"} \u2192 ${ke} (expires ${Xe}; /a/${ne} unchanged${sl}).`)}_(`next: turbobase apps promote ${ne} ${vt.previewId??"<preview-id>"} # make it live`),_(` turbobase apps preview discard ${vt.previewId??"<preview-id>"}`);return}et()?_(Zr("Deployed",[`${g.bold(ne)} ${g.green(`v${vt.version??"?"}`)} ${g.dim(vt.url??`/a/${ne}`)}`])):_(`deployed ${ne} \u2192 v${vt.version??"?"} (${vt.url??`/a/${ne}`}).`),await Ge(vt,$)}),c.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts + guardrail-blocked writes. Writes nothing.").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 tables as `cli` or `app:<slug>`.").action(async(d,f)=>{let v=await qD(d??".");v||x(`no public/turbobase.json under ${xe(process.cwd(),d??".")}.`);let T=Array.isArray(v.manifest.tables)?v.manifest.tables:[],$=Array.isArray(v.manifest.writes)?v.manifest.writes:[];if(T.length===0&&$.length===0)return _(`${v.manifestPath} declares no tables and no writes \u2014 nothing to plan.`);let{baseUrl:y,token:S}=await te(f.baseUrl),R=new Y({baseUrl:y,token:S});if(T.length>0){let O;try{O=await ae("planning tables",()=>R.tablesPlan({claimedBy:f.as,tables:T}))}catch(C){oe(C,"extensions:deploy","plan tables"),Wn(C)}_(`claiming as ${g.bold(O.claimedBy)}`);for(let C of O.tables)dn(C,{showClaimants:!0})}if($.length>0){let O;try{O=await ae("checking declared writes",()=>R.appsPlan($))}catch(C){oe(C,"extensions:deploy","plan writes"),x(`plan writes failed: ${C instanceof Error?C.message:String(C)}`)}_("");for(let C of O.verdicts){let U=`${C.source} ${C.recordType}.${C.op}`;C.allowed?C.heldForApproval?_(`${g.dim("HELD")} ${U} \u2014 allowed, but each write waits for operator approval.`):_(`${g.dim("ok")} ${U}`):q(`${g.bold("DENIED")} ${U}${C.rule?` \u2014 guardrail "${C.rule}"`:""} (${C.reason})`)}O.ok||(_(""),x(O.message??"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them."))}_(""),_(g.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),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(d,f,v)=>{let{baseUrl:T,token:$}=await te(v.baseUrl),y=await ae(`promoting ${f}`,()=>z(T,$,d,"promote",{previewId:f}));et()?_(Zr("Promoted",[`${g.bold(d)} ${g.green(`v${y.version??"?"}`)} ${g.dim(y.url??`/a/${d}`)}`])):_(`promoted ${d} \u2192 v${y.version??"?"} is now live at ${y.url??`/a/${d}`}.`),await Ge(y)});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).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),$=await V(v,T,d);if(f.json)return _(JSON.stringify($.previews,null,2));if($.previews.length===0){_(`no open previews for ${d}.`);return}for(let y of $.previews){let S=y.label?` ${y.label}`:"",R=y.expiresAt?new Date(y.expiresAt).toLocaleDateString():"?";_(`v${y.version} ${y.previewId}${S} ${y.url} (expires ${R})`)}}),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(d,f,v)=>{let{baseUrl:T,token:$}=await te(v.baseUrl);await ae(`discarding ${f}`,()=>z(T,$,d,"discard",{previewId:f})),_(`discarded ${f}.`)}),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(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),$=await ae(`creating ${d}`,()=>u(v,T,{slug:d,name:f.name,description:f.description})),y=$.slug??d;et()?_(Zr("Created",[`${g.bold(y)} ${g.dim($.url??`/a/${y}`)}`])):_(`created ${y} (${$.url??`/a/${y}`}).`),_(`next: turbobase apps push ${y} . # store the source`),_(` turbobase apps deploy ${y} # build + go live`)});async function u(d,f,v,T={}){let $=`${d.replace(/\/+$/,"")}/v1/apps`,y;try{y=await fetch($,{method:"POST",headers:{Authorization:`Bearer ${f}`,"content-type":"application/json"},body:JSON.stringify({slug:v.slug,name:v.name??v.slug,description:v.description})})}catch(S){x(`create request failed: ${S instanceof Error?S.message:String(S)}`)}if(y.status===401&&x("create unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&x("create forbidden (403) \u2014 the PAT is not for an admin."),y.status===409){if(T.tolerateExisting)return{slug:v.slug,existed:!0};x(`an app with slug "${v.slug}" already exists.`)}return y.ok||x(`create failed: HTTP ${y.status} ${(await y.text().catch(()=>"")).slice(0,200)}`),await y.json().catch(()=>({}))}async function p(d,f,v){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/pull`,$;try{$=await fetch(T,{headers:{Authorization:`Bearer ${f}`}})}catch(y){x(`pull request failed: ${y instanceof Error?y.message:String(y)}`)}return $.status===401&&x("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),$.status===403&&x("pull forbidden (403) \u2014 the PAT is not for an admin."),$.status===404&&x(`no generated source for "${v}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),$.ok||x(`pull failed: HTTP ${$.status} ${(await $.text().catch(()=>"")).slice(0,200)}`),await $.json()}async function w(d,f,v){let T=xe(d),$=0;for(let[y,S]of Object.entries(f)){let R=xe(T,y);R!==T&&!R.startsWith(T+qm)&&x(`refusing to write outside ${T}: ${y}`),v||await ye.stat(R).then(()=>!0).catch(()=>!1)&&x(`${R} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ye.mkdir(Ko(R),{recursive:!0}),await ye.writeFile(R,S,"utf8"),$+=1}return $}function m(d){let f=d.indexOf(","),v=d.startsWith("data:")?f>=0?d.slice(f+1):"":d;if(!v)return null;try{let T=Buffer.from(v,"base64");return T.length>0?new Uint8Array(T):null}catch{return null}}async function h(d,f,v){let T=xe(d),$=async(S,R)=>{let O=xe(T,S);O!==T&&!O.startsWith(T+qm)&&x(`refusing to write outside ${T}: ${S}`),v||await ye.stat(O).then(()=>!0).catch(()=>!1)&&x(`${O} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ye.mkdir(Ko(O),{recursive:!0}),await ye.writeFile(O,R)},y=`# ${f.title||"App change request"}
|
|
3584
|
+
`),"utf8"),_(`wrote ${C}${R?"":" (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 (${ps.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,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(d=>Uy(d)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>qy(d)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Zy(d,f)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>By(d,f)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Fy(d)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Hy(d,f)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Vy(d,f)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. 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.",d=>Number.parseInt(d,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("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>Ky(d)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>sb(d)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>ib(d,f)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>ab(d,f)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>lb(d)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>cb(d,f)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>ub(d,f));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 d=>{let f;try{f=Hr("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(k){x(k instanceof Error?k.message:String(k))}let v=xe(process.cwd(),f.relativePath);await Ko(v,f.content)==="skipped"&&x(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),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 d=>{let f;try{f=Hr("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(k){x(k instanceof Error?k.message:String(k))}let v=xe(process.cwd(),f.relativePath);await Ko(v,f.content)==="skipped"&&x(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),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(d,f)=>{let v=Dm(f.reporter),T=await cs(xe(process.cwd(),d)),k=xe(process.cwd(),f.samples),y=await as(k);y.length===0&&!v&&_(`no samples found under ${k} \u2014 add JSON fixtures to dry-run against.`);let S;try{S=await Vi(T,y.map(N=>N.fixture))}catch(N){x(`bundle failed: ${N instanceof Error?N.message:String(N)}`)}if(v){let N=UD(S);_(Wi(N,v)),nl(N.cases.some(j=>j.status==="failed")?1:0)}let R=0;for(let N of S){let j=N.pass?g.green("PASS"):g.red("FAIL");N.pass||(R+=1);let K=N.error?` (error: ${N.error})`:N.observed!==N.expected?` (expected ${N.expected}, observed ${N.observed})`:N.rejection?` (rejected: ${N.rejection.code??"rejected"})`:"";_(` ${j} ${N.name}${K}`)}let C=`${S.length-R}/${S.length} sample(s) passed.`;_(`
|
|
3585
|
+
${R===0?g.green(C):g.yellow(C)}`),nl(R>0?1:0)}),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 project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,f)=>{if(f.to){let S=await Um(),{baseUrl:R,token:C}=await ne(f.baseUrl),N=new X({baseUrl:R,token:C});try{let j=await ae(`applying bundle to ${f.to}`,()=>N.configApply(S,{prune:f.prune}));_(`applied bundle to ${f.to}: +${j.applied.add} ~${j.applied.change} -${j.applied.destroy}`+(j.backfillsQueued.length?` (${j.backfillsQueued.length} backfill(s) queued)`:""));let K=j.skippedDestroys??[];if(K.length>0){q(`${K.length} resource(s) exist on ${f.to} but are not declared by this project \u2014 NOT removed:`);for(let M of K)q(` ${M.kind} ${M.id}`);q("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(j){j instanceof pe&&j.status===403&&x("apply forbidden (403) \u2014 the stored PAT is not for an admin."),x(`bundle apply failed: ${j instanceof Error?j.message:String(j)}`)}return}d||x("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:v,token:T}=await ne(f.baseUrl),k=await DD(xe(process.cwd(),d)),y=new X({baseUrl:v,token:T});try{let S=await ae(`deploying ${RS(d)}`,()=>y.deploy(k));tt()?_(Br("Deployed",[`${g.bold(S.id)} ${lo(S.status)} ${g.dim(S.outcome)}`])):_(`deployed ${S.id} \u2192 status=${S.status} (${S.outcome}).`)}catch(S){S instanceof pe&&S.status===403&&x("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),x(`deploy failed: ${S instanceof Error?S.message:String(S)}`)}});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.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,f,v)=>{let T=!!(v.preview||v.replace||v.replaceLabel);v.replace&&v.replaceLabel&&x("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let k=xe(process.cwd(),f??".");await ye.mkdir(k,{recursive:!0});let y=v.proposal??await b(k),{baseUrl:S,token:R}=await ne(v.baseUrl),C=new X({baseUrl:S,token:R}),N=!1;try{N=(await C.appsList()).some(ke=>ke.slug===d||ke.id===d)}catch(ke){se(ke,"extensions:deploy","deploy"),x(`could not reach ${S}: ${ke instanceof Error?ke.message:String(ke)}`)}if(!N){v.create||x(`no app "${d}" on ${S} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let ke=await ae(`creating app ${d}`,()=>u(S,R,{slug:d},{tolerateExisting:!0}));ke.existed||_(`created ${ke.slug??d}.`)}let j;if(v.replace)if(typeof v.replace=="string")j=v.replace;else{let{previews:ke}=await V(S,R,d);if(ke.length===0&&x(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),ke.length>1){for(let et of ke)_(` ${et.previewId} v${et.version}${et.label?` ${et.label}`:""} ${et.url}`);x(`${d} has ${ke.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${ke[0].previewId}\`.`)}j=ke[0].previewId}let K;if(v.replaceLabel){let ke=v.replaceLabel,{previews:et}=await V(S,R,d),ar=et.filter(il=>il.label===ke);ar.length>0?(j=ar[0].previewId,ar.length>1&&q(`${ar.length} open previews carry the label "${ke}"; replacing the newest (${j}). Close the others with \`turbobase apps preview discard\`.`)):_(`no open preview labelled "${ke}" \u2014 opening one.`),K=ke}let M=ke=>ye.stat(At(k,ke)).then(()=>!0).catch(()=>!1),te=d,Ee=k,Ie=v.build!==!1;if(Ie&&!await M("package.json"))if(await M("index.html"))_("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Ie=!1;else if(v.pull===!1)x(`${k} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ke=await ae(`pulling ${d}`,()=>p(S,R,d));te=ke.slug??d,await w(k,ke.files,!0),_(`pulled generated source (rev ${ke.rev}).`)}let Jn;if(Ie){let ke=hb();if(Jn={buildId:ke,assetBase:fb(ke)},v.install!==!1&&!await M("node_modules")){_("installing dependencies\u2026");try{await E(["install"],k)}catch(et){x(`npm install failed: ${et instanceof Error?et.message:String(et)}`)}}_("building\u2026");try{await E(["run","build"],k,{TURBOBASE_ASSET_BASE:Jn.assetBase})}catch(et){x(`build failed: ${et instanceof Error?et.message:String(et)}`)}await M("dist")||x(`no dist/ after build in ${k} \u2014 check the app's build script.`),Ee=At(k,"dist")}T&&!Jn&&x(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${te}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let ht=await Q(S,R,te,Ee,v.entry,y,Jn,T?{label:v.label??K,replacePreviewId:j}:void 0);if(T){let ke=ht.previewUrl??"(no url returned)",et=ht.expiresAt?new Date(ht.expiresAt).toLocaleDateString():`${mb} days`,ar=ht.replacedVersion==null?null:`replaced v${ht.replacedVersion} \u2014 same URL`;if(tt())_(Br(ar?"Preview replaced":"Preview deployed",[`${g.bold(te)} ${g.green(`v${ht.version??"?"}`)} ${g.dim("not live")}`,`${g.bold(ke)}`,...ar?[g.dim(ar)]:[],g.dim(`expires ${et}`)]));else{let il=ar?`; ${ar}`:"";_(`preview ${te} v${ht.version??"?"} \u2192 ${ke} (expires ${et}; /a/${te} unchanged${il}).`)}_(`next: turbobase apps promote ${te} ${ht.previewId??"<preview-id>"} # make it live`),_(` turbobase apps preview discard ${ht.previewId??"<preview-id>"}`);return}tt()?_(Br("Deployed",[`${g.bold(te)} ${g.green(`v${ht.version??"?"}`)} ${g.dim(ht.url??`/a/${te}`)}`])):_(`deployed ${te} \u2192 v${ht.version??"?"} (${ht.url??`/a/${te}`}).`),Je(ht),await Qe(ht,k)}),c.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").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 tables as `cli` or `app:<slug>`.").action(async(d,f)=>{let v=await BD(d??".");v||x(`no public/turbobase.json under ${xe(process.cwd(),d??".")}.`);let T=Array.isArray(v.manifest.tables)?v.manifest.tables:[],k=Array.isArray(v.manifest.writes)?v.manifest.writes:[],y=Array.isArray(v.manifest.roles)?v.manifest.roles:[];if(T.length===0&&k.length===0&&y.length===0)return _(`${v.manifestPath} declares no tables, writes or roles \u2014 nothing to plan.`);let{baseUrl:S,token:R}=await ne(f.baseUrl),C=new X({baseUrl:S,token:R});if(T.length>0){let N;try{N=await ae("planning tables",()=>C.tablesPlan({claimedBy:f.as,tables:T}))}catch(j){se(j,"extensions:deploy","plan tables"),ki(j)}_(`claiming as ${g.bold(N.claimedBy)}`);for(let j of N.tables)Wn(j,{showClaimants:!0})}if(k.length>0||y.length>0){let N;try{N=await ae("checking declared writes and roles",()=>C.appsPlan({writes:k,roles:y}))}catch(j){se(j,"extensions:deploy","plan writes"),x(`plan writes failed: ${j instanceof Error?j.message:String(j)}`)}if(N.roles&&N.roles.verdicts.length>0){_(""),_(g.bold("roles"));let j=Math.max(...N.roles.verdicts.map(K=>K.name.length));for(let K of N.roles.verdicts){let M=K.name.padEnd(j);if(K.action==="error")q(` ${g.bold("ERROR")} ${M} \u2014 ${K.message??"cannot be created"}`);else if(K.action==="create"){let te=K.addCapabilities?.length??0;_(` create ${M} ${g.dim(`${te} capabilit${te===1?"y":"ies"}`)}`)}else if(K.action==="add_capabilities"){let te=(K.addCapabilities??[]).map(Ee=>`+${Ee}`).join(", ");_(` add ${M} ${g.dim(te)}`)}else _(` ${g.dim("ok")} ${M} ${g.dim("already up to date")}`)}N.roles.verdicts.some(K=>K.action!=="error")&&_(g.dim(" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users."))}k.length>0&&_("");for(let j of N.verdicts){let K=`${j.source} ${j.recordType}.${j.op}`;j.allowed?j.heldForApproval?_(`${g.dim("HELD")} ${K} \u2014 allowed, but each write waits for operator approval.`):_(`${g.dim("ok")} ${K}`):q(`${g.bold("DENIED")} ${K}${j.rule?` \u2014 guardrail "${j.rule}"`:""} (${j.reason})`)}N.ok||(_(""),x(N.message??(N.roles&&!N.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}_(""),_(g.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),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(d,f,v)=>{let{baseUrl:T,token:k}=await ne(v.baseUrl),y=await ae(`promoting ${f}`,()=>z(T,k,d,"promote",{previewId:f}));tt()?_(Br("Promoted",[`${g.bold(d)} ${g.green(`v${y.version??"?"}`)} ${g.dim(y.url??`/a/${d}`)}`])):_(`promoted ${d} \u2192 v${y.version??"?"} is now live at ${y.url??`/a/${d}`}.`),await Qe(y)});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).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,f)=>{let{baseUrl:v,token:T}=await ne(f.baseUrl),k=await V(v,T,d);if(f.json)return _(JSON.stringify(k.previews,null,2));if(k.previews.length===0){_(`no open previews for ${d}.`);return}for(let y of k.previews){let S=y.label?` ${y.label}`:"",R=y.expiresAt?new Date(y.expiresAt).toLocaleDateString():"?";_(`v${y.version} ${y.previewId}${S} ${y.url} (expires ${R})`)}}),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(d,f,v)=>{let{baseUrl:T,token:k}=await ne(v.baseUrl);await ae(`discarding ${f}`,()=>z(T,k,d,"discard",{previewId:f})),_(`discarded ${f}.`)}),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(d,f)=>{let{baseUrl:v,token:T}=await ne(f.baseUrl),k=await ae(`creating ${d}`,()=>u(v,T,{slug:d,name:f.name,description:f.description})),y=k.slug??d;tt()?_(Br("Created",[`${g.bold(y)} ${g.dim(k.url??`/a/${y}`)}`])):_(`created ${y} (${k.url??`/a/${y}`}).`),_(`next: turbobase apps push ${y} . # store the source`),_(` turbobase apps deploy ${y} # build + go live`)});async function u(d,f,v,T={}){let k=`${d.replace(/\/+$/,"")}/v1/apps`,y;try{y=await fetch(k,{method:"POST",headers:{Authorization:`Bearer ${f}`,"content-type":"application/json"},body:JSON.stringify({slug:v.slug,name:v.name??v.slug,description:v.description})})}catch(S){x(`create request failed: ${S instanceof Error?S.message:String(S)}`)}if(y.status===401&&x("create unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&x("create forbidden (403) \u2014 the PAT is not for an admin."),y.status===409){if(T.tolerateExisting)return{slug:v.slug,existed:!0};x(`an app with slug "${v.slug}" already exists.`)}return y.ok||x(`create failed: HTTP ${y.status} ${(await y.text().catch(()=>"")).slice(0,200)}`),await y.json().catch(()=>({}))}async function p(d,f,v){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/pull`,k;try{k=await fetch(T,{headers:{Authorization:`Bearer ${f}`}})}catch(y){x(`pull request failed: ${y instanceof Error?y.message:String(y)}`)}return k.status===401&&x("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),k.status===403&&x("pull forbidden (403) \u2014 the PAT is not for an admin."),k.status===404&&x(`no generated source for "${v}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),k.ok||x(`pull failed: HTTP ${k.status} ${(await k.text().catch(()=>"")).slice(0,200)}`),await k.json()}async function w(d,f,v){let T=xe(d),k=0;for(let[y,S]of Object.entries(f)){let R=xe(T,y);R!==T&&!R.startsWith(T+Zm)&&x(`refusing to write outside ${T}: ${y}`),v||await ye.stat(R).then(()=>!0).catch(()=>!1)&&x(`${R} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ye.mkdir(Vo(R),{recursive:!0}),await ye.writeFile(R,S,"utf8"),k+=1}return k}function m(d){let f=d.indexOf(","),v=d.startsWith("data:")?f>=0?d.slice(f+1):"":d;if(!v)return null;try{let T=Buffer.from(v,"base64");return T.length>0?new Uint8Array(T):null}catch{return null}}async function h(d,f,v){let T=xe(d),k=async(S,R)=>{let C=xe(T,S);C!==T&&!C.startsWith(T+Zm)&&x(`refusing to write outside ${T}: ${S}`),v||await ye.stat(C).then(()=>!0).catch(()=>!1)&&x(`${C} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ye.mkdir(Vo(C),{recursive:!0}),await ye.writeFile(C,R)},y=`# ${f.title||"App change request"}
|
|
3301
3586
|
|
|
3302
3587
|
> Widget proposal \`${f.proposalId}\` \u2014 build this change, then ship it with
|
|
3303
3588
|
> \`turbobase apps deploy ${f.appSlug}\`. The deploy stamps this proposal complete.
|
|
@@ -3307,35 +3592,35 @@ ${f.bodyMarkdown||"_No description provided._"}
|
|
|
3307
3592
|
## Screen context
|
|
3308
3593
|
|
|
3309
3594
|
`+(f.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.
|
|
3310
|
-
`);if(await
|
|
3311
|
-
`)}async function b(d){try{let f=await ye.readFile(At(d,".turbobase","proposal.json"),"utf8"),v=JSON.parse(f);return typeof v.proposalId=="string"&&v.proposalId?v.proposalId:void 0}catch{return}}async function k(d,f,v,T,$,y){let S=new Y({baseUrl:d,token:f});try{return await S.appsPush(v,T,{note:$,proposalId:y})}catch(R){if(R instanceof pe){let O=R.body;if(R.status===401&&x("push unauthorized (401) \u2014 re-run `turbobase auth login`."),R.status===403&&O?.error==="admin_required"&&x("push forbidden (403) \u2014 the PAT is not for an admin."),R.status===403&&oe(R,"extensions:deploy","push app source"),R.status===404&&x(`no app "${v}" on this instance \u2014 create it with \`turbobase apps create ${v}\`.`),R.status===413&&(O?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&x("push rejected: the request body exceeded the instance limit."),x(`push rejected: ${O?.error??"too large"} (limit ${O?.limit??"?"}).`)),R.status===400){let C=O?.path?` in ${O.path}`:"",U=O?.reason?` (${O.reason})`:"";x(`push rejected: ${O?.error??"bad request"}${U}${C}.`)}}x(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function E(d,f,v){return new Promise((T,$)=>{let y=Zm("npm",d,{cwd:f,stdio:"inherit",...v?{env:{...process.env,...v}}:{}});y.on("error",$),y.on("exit",S=>S===0?T():$(new Error(`npm ${d.join(" ")} exited ${S??"?"}`)))})}async function P(d,f,v,T){let $=`${d.replace(/\/+$/,"")}${v}`,y;try{y=await fetch($,{method:T.method,headers:{Authorization:`Bearer ${f}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch(S){x(`request failed: ${S instanceof Error?S.message:String(S)}`)}if(y.status===401&&x("unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&x("forbidden (403) \u2014 the PAT is not for an admin."),!y.ok){let S=await y.text().catch(()=>""),R=S.slice(0,300);try{let O=JSON.parse(S);R=O.message??O.error??R}catch{}x(`failed: HTTP ${y.status} ${R}`)}return await y.json().catch(()=>({}))}async function z(d,f,v,T,$){return await P(d,f,`/v1/apps/${encodeURIComponent(v)}/preview/${T}`,{method:"POST",body:$})}async function V(d,f,v){return{previews:(await P(d,f,`/v1/apps/${encodeURIComponent(v)}/previews`,{method:"GET"})).previews??[]}}async function Q(d,f,v,T,$,y,S,R){let O;try{O=await ae(`zipping ${T}`,()=>ry(T))}catch(M){x(`could not zip ${T}: ${M instanceof Error?M.message:String(M)}`)}O.fileCount===0&&x(`${T} is empty \u2014 the build produced nothing.`);let C={Authorization:`Bearer ${f}`,"Content-Type":"application/zip"};$&&(C["x-app-entry"]=$),y&&(C["x-proposal-id"]=y),S&&(C["x-app-build-id"]=S.buildId,C["x-app-asset-base"]=S.assetBase),R&&(C["x-app-channel"]="preview",R.label&&(C["x-app-preview-label"]=encodeURIComponent(R.label)),R.replacePreviewId&&(C["x-app-preview-replace"]=R.replacePreviewId));let U=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/deploy`,ie;try{ie=await ae(`deploying ${v} (${O.fileCount} file${O.fileCount===1?"":"s"})`,()=>fetch(U,{method:"POST",headers:C,body:new Uint8Array(O.buffer)}))}catch(M){x(`deploy request failed: ${M instanceof Error?M.message:String(M)}`)}if(ie.status===401&&x("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),ie.status===403&&x("deploy forbidden (403) \u2014 the PAT is not for an admin."),ie.status===404){let M=await ie.text().catch(()=>""),ne={};try{ne=JSON.parse(M)}catch{}ne.error==="no_preview"&&x(`${ne.message??`no open preview to replace on ${v}`} \u2014 list them with \`turbobase apps preview list ${v}\`.`),x(`no app "${v}" on ${d} \u2014 create it with \`turbobase apps create ${v}\`.`)}if(!ie.ok){let M=await ie.text().catch(()=>""),ne=M.slice(0,300);try{let Re=JSON.parse(M);ne=Re.message??Re.error??ne}catch{}x(`deploy failed: HTTP ${ie.status} ${ne}`)}return await ie.json().catch(()=>({}))}async function Ge(d,f){let v=my(d,{localDocsModifiedAt:await rt(f)});v&&_(v.level==="warn"?g.yellow(v.message):g.dim(v.message))}async function rt(d){if(!d)return null;let f=null;for(let v of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await ye.stat(At(d,v));(f===null||T.mtimeMs>f)&&(f=T.mtimeMs)}catch{}return f===null?null:new Date(f)}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(d,f,v)=>{let{baseUrl:T,token:$}=await te(v.baseUrl);if(v.proposal){let O=new Y({baseUrl:T,token:$}),C;try{C=await ae(`fetching proposal ${v.proposal}`,()=>O.appPullContext(v.proposal))}catch(Re){oe(Re,"extensions:deploy","pull proposal"),Re instanceof pe&&Re.status===404&&x(`no widget proposal "${v.proposal}" on ${T}.`),x(`could not fetch proposal ${v.proposal}: ${Re instanceof Error?Re.message:String(Re)}`)}let U=await ae(`pulling ${C.appSlug}`,()=>p(T,$,C.appSlug)),ie=f??d,M=xe(process.cwd(),ie??C.appSlug);await ye.mkdir(M,{recursive:!0});let ne=await w(M,U.files,!!v.force);await h(M,C,!!v.force),_(`pulled ${ne} file${ne===1?"":"s"} \u2192 ${M} (rev ${U.rev}), linked to proposal ${C.proposalId}.`),_(`next: cd ${nl(process.cwd(),M)||"."} && turbobase apps deploy ${C.appSlug}`);return}d||x("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let y=await ae(`pulling ${d}`,()=>p(T,$,d)),S=xe(process.cwd(),f??y.slug??d);await ye.mkdir(S,{recursive:!0});let R=await w(S,y.files,!!v.force);_(`pulled ${R} file${R===1?"":"s"} \u2192 ${S} (rev ${y.rev}).`),_(`next: cd ${nl(process.cwd(),S)||"."} && turbobase apps deploy ${y.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(d,f,v)=>{let T=xe(process.cwd(),f??d),$=await Qt(v.baseUrl).catch(()=>null),{scaffoldAppFiles:y,starterApp:S}=await Promise.resolve().then(()=>(Wb(),Gb)),R=v.title??d,O=y({slug:d,title:R,appTsx:S(R),instanceOrigin:$?.baseUrl});await ye.mkdir(T,{recursive:!0});let C=await w(T,O,!!v.force);if(_(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${T}`),v.claude!==!1){let ie=ru({baseUrl:$?.baseUrl,token:$?.token,appSlug:d}),M=0;for(let ne of ie){let Re=await TS(At(T,ne.path),ne);(Re==="wrote"||Re==="merged")&&(M+=1)}_(`wired Claude Code: ${M} file${M===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),$||q("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 U=nl(process.cwd(),T)||".";_(`next: cd ${U} && npm install && npm run dev`),_(` turbobase apps create ${d}`),_(` turbobase apps push ${d} .`),_(` turbobase apps deploy ${d} .`)}),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 d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new Y({baseUrl:f,token:v}),$;try{$=await T.appsList()}catch(y){oe(y,"extensions:deploy","list apps"),x(`list apps failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify($,null,2));if($.length===0)return _("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");_(Xt($.map(y=>[y.slug,y.name,y.deployed?"yes":"no",y.sourceRev===null?"\u2014":`rev ${y.sourceRev}`,y.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(d,f,v)=>{let T=xe(process.cwd(),f??".");await ye.stat(T).then(Ie=>Ie.isDirectory()).catch(()=>!1)||x(`${T} is not a directory.`);let{baseUrl:y,token:S}=await te(v.baseUrl),R=v.proposal??await b(T),{files:O,skipped:C,secrets:U,unstorable:ie}=await db(T),M=Object.keys(O).length;if(M===0&&x(`no source files found under ${T} (build output and node_modules are skipped).`),ie.length>0){for(let Ie of ie)q(`${Ie} contains a NUL byte (U+0000), which cannot be stored.`);x(`push aborted: ${ie.length} ${ie.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let Ie of C)q(g.dim(`skipped binary file ${Ie}`));for(let Ie of U)q(g.dim(`skipped ${Ie} (holds credentials \u2014 never pushed)`));let ne=await ae(`pushing ${M} file${M===1?"":"s"}`,()=>k(y,S,d,O,v.note,R));_(`pushed ${ne.files} file${ne.files===1?"":"s"} \u2192 ${ne.slug} rev ${ne.rev} (source only, nothing deployed).`);let Re=await fs(new Y({baseUrl:y,token:S}),ne.slug);Re&&Re.entriesAdded>0&&_(`${Re.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),_(`next: turbobase apps deploy ${ne.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) 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 d=>{let f=await Dm(),{baseUrl:v,token:T}=await te(d.baseUrl),$=new Y({baseUrl:v,token:T}),y;try{y=await ae(`planning against ${d.to??v}`,()=>$.configPlan(f))}catch(S){x(`plan failed: ${S instanceof Error?S.message:String(S)}`)}BD(y,d.to??v)}),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).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let f=await Dm(),{baseUrl:v,token:T}=await te(d.baseUrl),$=f.tenant??FD(v),y=Sy(d.confirm,$);y.ok||x(`promote refused (fail-closed): ${y.reason}`);let S=new Y({baseUrl:v,token:T});try{let R=await ae(`promoting ${d.from} \u2192 ${d.to} (${$})`,()=>S.configApply(f,{prune:d.prune}));if(et()){let C=[`${g.bold(`${d.from} \u2192 ${d.to}`)} ${g.dim($??"")}`,`${qr.add(String(R.applied.add))} ${qr.change(String(R.applied.change))} ${qr.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&C.push(g.dim(`${R.backfillsQueued.length} backfill(s) queued`)),_(Zr("Promoted",C))}else _(`promoted ${d.from} \u2192 ${d.to} (${$}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""));let O=R.skippedDestroys??[];if(O.length>0){q(`${O.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let C of O)q(` ${C.kind} ${C.id}`);q("Re-run with --prune to remove them, or add them to this repo.")}}catch(R){R instanceof pe&&R.status===403&&x("promote forbidden (403) \u2014 the stored PAT is not for an admin."),x(`promote failed: ${R instanceof Error?R.message:String(R)}`)}}),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(d,f)=>{let v=Lm(f.reporter),T=xe(process.cwd(),d),$=await ls(T),y=oy($);v?_(Ki(DD(d,y),v)):_(sy(d,y,{warn:g.yellow,ok:g.green,dim:g.dim})),f.ci&&y.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(d,f)=>{let v=Lm(f.reporter),T=await Jg(xe(process.cwd(),d));if(f.against){f.against!=="sandbox"&&x(`unknown --against target '${f.against}' (only 'sandbox' is supported).`);try{await Gg(Wl(T))}catch(S){x(S instanceof Error?S.message:String(S))}return}f.fixture||x("replay needs a --fixture <file> (offline) or --against sandbox (online).");let $;try{$=await Wg(xe(process.cwd(),f.fixture))}catch(S){x(`could not read fixture ${f.fixture}: ${S instanceof Error?S.message:String(S)}`)}let y=await Kg(T,$,f.fixture);if(v){let S=UD(y);_(Ki(S,v)),rl(S.cases.some(R=>R.status==="failed")?1:0)}_(Yg(y,!!f.trace)),rl(y.error?1:0)}),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 d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new Y({baseUrl:f,token:v});try{await py(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:_})}catch($){$ instanceof pe&&$.status===403&&x("forbidden (403) \u2014 binding --retry requires an admin PAT."),$ instanceof pe&&$.status===409&&x("binding is not retryable (only divergent/blocked bindings can be retried)."),x(`ext binding failed: ${$ instanceof Error?$.message:String($)}`)}});let Gt=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");Gt.command("list").description("List hook proposals and the evidence behind each (defaults to the pending queue).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <list>","proposed | active | rejected (comma-joined). Default: proposed.").option("--provenance <list>","mechanic | operator | learning | code-baseline (comma-joined).").option("--record-type <type>","Only proposals for this record type.").option("--source <system>","Only proposals for this adapter id.").option("--limit <n>","Max rows listed (default 200).").option("--json","Emit raw JSON instead of a table.").action(async d=>{await Xy(d)}),Gt.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(d,f)=>{await eb(d??[],f)}),Gt.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{await tb(d,f)}),Gt.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(d,f)=>{await rb(d,f)}),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(d,f)=>{let v=d.lastIndexOf("@"),T=v>0?d.slice(0,v):d,$=v>0?d.slice(v+1):void 0,y=Bl();y||x(`marketplace not configured \u2014 set ${ao} and ${Bi}.
|
|
3312
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=
|
|
3313
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=
|
|
3314
|
-
project init: ${T} written, ${y} merged, ${
|
|
3595
|
+
`);if(await k("PROPOSAL.md",y),f.screenshot){let S=m(f.screenshot);S&&await k("proposal-screenshot.png",S)}await k(At(".turbobase","proposal.json"),`${JSON.stringify({proposalId:f.proposalId},null,2)}
|
|
3596
|
+
`)}async function b(d){try{let f=await ye.readFile(At(d,".turbobase","proposal.json"),"utf8"),v=JSON.parse(f);return typeof v.proposalId=="string"&&v.proposalId?v.proposalId:void 0}catch{return}}async function $(d,f,v,T,k,y){let S=new X({baseUrl:d,token:f});try{return await S.appsPush(v,T,{note:k,proposalId:y})}catch(R){if(R instanceof pe){let C=R.body;if(R.status===401&&x("push unauthorized (401) \u2014 re-run `turbobase auth login`."),R.status===403&&C?.error==="admin_required"&&x("push forbidden (403) \u2014 the PAT is not for an admin."),R.status===403&&se(R,"extensions:deploy","push app source"),R.status===404&&x(`no app "${v}" on this instance \u2014 create it with \`turbobase apps create ${v}\`.`),R.status===413&&(C?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&x("push rejected: the request body exceeded the instance limit."),x(`push rejected: ${C?.error??"too large"} (limit ${C?.limit??"?"}).`)),R.status===400){let N=C?.path?` in ${C.path}`:"",j=C?.reason?` (${C.reason})`:"";x(`push rejected: ${C?.error??"bad request"}${j}${N}.`)}}x(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function E(d,f,v){return new Promise((T,k)=>{let y=Bm("npm",d,{cwd:f,stdio:"inherit",...v?{env:{...process.env,...v}}:{}});y.on("error",k),y.on("exit",S=>S===0?T():k(new Error(`npm ${d.join(" ")} exited ${S??"?"}`)))})}async function P(d,f,v,T){let k=`${d.replace(/\/+$/,"")}${v}`,y;try{y=await fetch(k,{method:T.method,headers:{Authorization:`Bearer ${f}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch(S){x(`request failed: ${S instanceof Error?S.message:String(S)}`)}if(y.status===401&&x("unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&x("forbidden (403) \u2014 the PAT is not for an admin."),!y.ok){let S=await y.text().catch(()=>""),R=S.slice(0,300);try{let C=JSON.parse(S);R=C.message??C.error??R}catch{}x(`failed: HTTP ${y.status} ${R}`)}return await y.json().catch(()=>({}))}async function z(d,f,v,T,k){return await P(d,f,`/v1/apps/${encodeURIComponent(v)}/preview/${T}`,{method:"POST",body:k})}async function V(d,f,v){return{previews:(await P(d,f,`/v1/apps/${encodeURIComponent(v)}/previews`,{method:"GET"})).previews??[]}}async function Q(d,f,v,T,k,y,S,R){let C;try{C=await ae(`zipping ${T}`,()=>ny(T))}catch(M){x(`could not zip ${T}: ${M instanceof Error?M.message:String(M)}`)}C.fileCount===0&&x(`${T} is empty \u2014 the build produced nothing.`);let N={Authorization:`Bearer ${f}`,"Content-Type":"application/zip"};k&&(N["x-app-entry"]=k),y&&(N["x-proposal-id"]=y),S&&(N["x-app-build-id"]=S.buildId,N["x-app-asset-base"]=S.assetBase),R&&(N["x-app-channel"]="preview",R.label&&(N["x-app-preview-label"]=encodeURIComponent(R.label)),R.replacePreviewId&&(N["x-app-preview-replace"]=R.replacePreviewId));let j=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/deploy`,K;try{K=await ae(`deploying ${v} (${C.fileCount} file${C.fileCount===1?"":"s"})`,()=>fetch(j,{method:"POST",headers:N,body:new Uint8Array(C.buffer)}))}catch(M){x(`deploy request failed: ${M instanceof Error?M.message:String(M)}`)}if(K.status===401&&x("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),K.status===403&&x("deploy forbidden (403) \u2014 the PAT is not for an admin."),K.status===404){let M=await K.text().catch(()=>""),te={};try{te=JSON.parse(M)}catch{}te.error==="no_preview"&&x(`${te.message??`no open preview to replace on ${v}`} \u2014 list them with \`turbobase apps preview list ${v}\`.`),x(`no app "${v}" on ${d} \u2014 create it with \`turbobase apps create ${v}\`.`)}if(!K.ok){let M=await K.text().catch(()=>""),te=M.slice(0,300);try{let Ee=JSON.parse(M);te=Ee.message??Ee.error??te}catch{}x(`deploy failed: HTTP ${K.status} ${te}`)}return await K.json().catch(()=>({}))}function Je(d){let f=d.roles;if(!f||f.verdicts.length===0)return;let v=f.verdicts.filter(k=>k.action!=="noop");if(v.length===0)return;_(""),_(g.bold(f.applied?"roles":"roles (preview \u2014 not applied)"));let T=Math.max(...v.map(k=>k.name.length));for(let k of v){let y=k.name.padEnd(T);if(k.action==="create"){let S=k.addCapabilities?.length??0;_(` created ${y} ${g.dim(`${S} capabilit${S===1?"y":"ies"}`)}`)}else if(k.action==="add_capabilities"){let S=(k.addCapabilities??[]).map(C=>`+${C}`).join(", "),R=k.holdersRestamped?g.dim(` (${k.holdersRestamped} holder${k.holdersRestamped===1?"":"s"} re-stamped)`):"";_(` updated ${y} ${g.dim(S)}${R}`)}}_(g.dim(f.applied?" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.":" nothing was created \u2014 promoting this preview applies them."))}async function Qe(d,f){let v=gy(d,{localDocsModifiedAt:await Nr(f)});v&&_(v.level==="warn"?g.yellow(v.message):g.dim(v.message))}async function Nr(d){if(!d)return null;let f=null;for(let v of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await ye.stat(At(d,v));(f===null||T.mtimeMs>f)&&(f=T.mtimeMs)}catch{}return f===null?null:new Date(f)}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(d,f,v)=>{let{baseUrl:T,token:k}=await ne(v.baseUrl);if(v.proposal){let C=new X({baseUrl:T,token:k}),N;try{N=await ae(`fetching proposal ${v.proposal}`,()=>C.appPullContext(v.proposal))}catch(Ee){se(Ee,"extensions:deploy","pull proposal"),Ee instanceof pe&&Ee.status===404&&x(`no widget proposal "${v.proposal}" on ${T}.`),x(`could not fetch proposal ${v.proposal}: ${Ee instanceof Error?Ee.message:String(Ee)}`)}let j=await ae(`pulling ${N.appSlug}`,()=>p(T,k,N.appSlug)),K=f??d,M=xe(process.cwd(),K??N.appSlug);await ye.mkdir(M,{recursive:!0});let te=await w(M,j.files,!!v.force);await h(M,N,!!v.force),_(`pulled ${te} file${te===1?"":"s"} \u2192 ${M} (rev ${j.rev}), linked to proposal ${N.proposalId}.`),_(`next: cd ${ol(process.cwd(),M)||"."} && turbobase apps deploy ${N.appSlug}`);return}d||x("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let y=await ae(`pulling ${d}`,()=>p(T,k,d)),S=xe(process.cwd(),f??y.slug??d);await ye.mkdir(S,{recursive:!0});let R=await w(S,y.files,!!v.force);_(`pulled ${R} file${R===1?"":"s"} \u2192 ${S} (rev ${y.rev}).`),_(`next: cd ${ol(process.cwd(),S)||"."} && turbobase apps deploy ${y.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(d,f,v)=>{let T=xe(process.cwd(),f??d),k=await Yt(v.baseUrl).catch(()=>null),{scaffoldAppFiles:y,starterApp:S}=await Promise.resolve().then(()=>(Jb(),Gb)),R=v.title??d,C=y({slug:d,title:R,appTsx:S(R),instanceOrigin:k?.baseUrl});await ye.mkdir(T,{recursive:!0});let N=await w(T,C,!!v.force);if(_(`scaffolded ${N} file${N===1?"":"s"} \u2192 ${T}`),v.claude!==!1){let K=nu({baseUrl:k?.baseUrl,token:k?.token,appSlug:d}),M=0;for(let te of K){let Ee=await ES(At(T,te.path),te);(Ee==="wrote"||Ee==="merged")&&(M+=1)}_(`wired Claude Code: ${M} file${M===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),k||q("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 j=ol(process.cwd(),T)||".";_(`next: cd ${j} && npm install && npm run dev`),_(` turbobase apps create ${d}`),_(` turbobase apps push ${d} .`),_(` turbobase apps deploy ${d} .`)}),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 d=>{let{baseUrl:f,token:v}=await ne(d.baseUrl),T=new X({baseUrl:f,token:v}),k;try{k=await T.appsList()}catch(y){se(y,"extensions:deploy","list apps"),x(`list apps failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(k,null,2));if(k.length===0)return _("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");_(Xt(k.map(y=>[y.slug,y.name,y.deployed?"yes":"no",y.sourceRev===null?"\u2014":`rev ${y.sourceRev}`,y.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(d,f,v)=>{let T=xe(process.cwd(),f??".");await ye.stat(T).then(Ie=>Ie.isDirectory()).catch(()=>!1)||x(`${T} is not a directory.`);let{baseUrl:y,token:S}=await ne(v.baseUrl),R=v.proposal??await b(T),{files:C,skipped:N,secrets:j,unstorable:K}=await pb(T),M=Object.keys(C).length;if(M===0&&x(`no source files found under ${T} (build output and node_modules are skipped).`),K.length>0){for(let Ie of K)q(`${Ie} contains a NUL byte (U+0000), which cannot be stored.`);x(`push aborted: ${K.length} ${K.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let Ie of N)q(g.dim(`skipped binary file ${Ie}`));for(let Ie of j)q(g.dim(`skipped ${Ie} (holds credentials \u2014 never pushed)`));let te=await ae(`pushing ${M} file${M===1?"":"s"}`,()=>$(y,S,d,C,v.note,R));_(`pushed ${te.files} file${te.files===1?"":"s"} \u2192 ${te.slug} rev ${te.rev} (source only, nothing deployed).`);let Ee=await hs(new X({baseUrl:y,token:S}),te.slug);Ee&&Ee.entriesAdded>0&&_(`${Ee.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),_(`next: turbobase apps deploy ${te.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) 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 d=>{let f=await Um(),{baseUrl:v,token:T}=await ne(d.baseUrl),k=new X({baseUrl:v,token:T}),y;try{y=await ae(`planning against ${d.to??v}`,()=>k.configPlan(f))}catch(S){x(`plan failed: ${S instanceof Error?S.message:String(S)}`)}HD(y,d.to??v)}),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).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let f=await Um(),{baseUrl:v,token:T}=await ne(d.baseUrl),k=f.tenant??VD(v),y=Ty(d.confirm,k);y.ok||x(`promote refused (fail-closed): ${y.reason}`);let S=new X({baseUrl:v,token:T});try{let R=await ae(`promoting ${d.from} \u2192 ${d.to} (${k})`,()=>S.configApply(f,{prune:d.prune}));if(tt()){let N=[`${g.bold(`${d.from} \u2192 ${d.to}`)} ${g.dim(k??"")}`,`${Zr.add(String(R.applied.add))} ${Zr.change(String(R.applied.change))} ${Zr.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&N.push(g.dim(`${R.backfillsQueued.length} backfill(s) queued`)),_(Br("Promoted",N))}else _(`promoted ${d.from} \u2192 ${d.to} (${k}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""));let C=R.skippedDestroys??[];if(C.length>0){q(`${C.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let N of C)q(` ${N.kind} ${N.id}`);q("Re-run with --prune to remove them, or add them to this repo.")}}catch(R){R instanceof pe&&R.status===403&&x("promote forbidden (403) \u2014 the stored PAT is not for an admin."),x(`promote failed: ${R instanceof Error?R.message:String(R)}`)}}),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(d,f)=>{let v=Dm(f.reporter),T=xe(process.cwd(),d),k=await cs(T),y=sy(k);v?_(Wi(MD(d,y),v)):_(iy(d,y,{warn:g.yellow,ok:g.green,dim:g.dim})),f.ci&&y.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(d,f)=>{let v=Dm(f.reporter),T=await Yg(xe(process.cwd(),d));if(f.against){f.against!=="sandbox"&&x(`unknown --against target '${f.against}' (only 'sandbox' is supported).`);try{await Gg(Jl(T))}catch(S){x(S instanceof Error?S.message:String(S))}return}f.fixture||x("replay needs a --fixture <file> (offline) or --against sandbox (online).");let k;try{k=await Jg(xe(process.cwd(),f.fixture))}catch(S){x(`could not read fixture ${f.fixture}: ${S instanceof Error?S.message:String(S)}`)}let y=await Wg(T,k,f.fixture);if(v){let S=qD(y);_(Wi(S,v)),nl(S.cases.some(R=>R.status==="failed")?1:0)}_(Xg(y,!!f.trace)),nl(y.error?1:0)}),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 d=>{let{baseUrl:f,token:v}=await ne(d.baseUrl),T=new X({baseUrl:f,token:v});try{await hy(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:_})}catch(k){k instanceof pe&&k.status===403&&x("forbidden (403) \u2014 binding --retry requires an admin PAT."),k instanceof pe&&k.status===409&&x("binding is not retryable (only divergent/blocked bindings can be retried)."),x(`ext binding failed: ${k instanceof Error?k.message:String(k)}`)}});let zr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");zr.command("list").description("List hook proposals and the evidence behind each (defaults to the pending queue).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <list>","proposed | active | rejected (comma-joined). Default: proposed.").option("--provenance <list>","mechanic | operator | learning | code-baseline (comma-joined).").option("--record-type <type>","Only proposals for this record type.").option("--source <system>","Only proposals for this adapter id.").option("--limit <n>","Max rows listed (default 200).").option("--json","Emit raw JSON instead of a table.").action(async d=>{await eb(d)}),zr.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(d,f)=>{await tb(d??[],f)}),zr.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{await rb(d,f)}),zr.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(d,f)=>{await nb(d,f)}),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(d,f)=>{let v=d.lastIndexOf("@"),T=v>0?d.slice(0,v):d,k=v>0?d.slice(v+1):void 0,y=Fl();y||x(`marketplace not configured \u2014 set ${io} and ${Fi}.
|
|
3597
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=Hl(y.registryUrl);S&&x(S);let{baseUrl:R,token:C}=await ne(f.baseUrl),N=new ss(y),j;try{j=await ae(`fetching ${d}`,()=>N.fetchBundle(T,k))}catch(Ie){x(`marketplace fetch failed for ${d}: ${Ie instanceof Error?Ie.message:String(Ie)}`)}let K=Li(j.manifest),M=null;if(K.length>0){if(!f.connection){let Ie=K.map(Jn=>Jn.source_system).join(", ");x(`${j.name}@${j.version} declares a connection input (source: ${Ie}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}M=f.connection}let te=ZD(j.bundle,j.name,j.kind),Ee=new X({baseUrl:R,token:C});try{let Ie=await ae(`installing ${j.name}@${j.version}`,()=>Ee.deploy({...te,provenance:"marketplace",...M?{connectionId:M}:{}}));_(`installed ${j.name}@${j.version} \u2192 ${Ie.id} (status=${Ie.status}, ${Ie.outcome})`+(M?` bound to connection ${M}.`:"."))}catch(Ie){Ie instanceof pe&&Ie.status===403&&x("install forbidden (403) \u2014 the stored PAT is not for an admin."),x(`install failed: ${Ie instanceof Error?Ie.message:String(Ie)}`)}}),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(d,f)=>{let v=Fl();v||x(`marketplace not configured \u2014 set ${io} and ${Fi}.
|
|
3598
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=Hl(v.registryUrl);T&&x(T);let k=xe(process.cwd(),d),y=await cs(k),S=/\bdefineConduit\s*[<(]/.test(y)?"conduit":"hook",R={};if(f.manifest){let j=xe(process.cwd(),f.manifest),K;try{K=await ye.readFile(j,"utf8")}catch{x(`manifest not found at ${f.manifest}.`)}let M;try{M=JSON.parse(K)}catch{x(`manifest is not valid JSON: ${f.manifest}.`)}(typeof M!="object"||M===null||Array.isArray(M))&&x("manifest must be a JSON object."),R=M}try{Pl(R,y)}catch(j){j instanceof qr&&x(j.message),x(`manifest validation failed: ${j instanceof Error?j.message:String(j)}`)}let C=new ss(v);try{await ae(`publishing ${f.name}@${f.pkgVersion}`,()=>C.publish({name:f.name,version:f.pkgVersion,kind:S,bundle:y,manifest:R}))}catch(j){j instanceof pe&&j.status===403&&x("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),j instanceof pe&&j.status===409&&x(`version already published \u2014 ${f.name}@${f.pkgVersion} exists. Bump the version.`),x(`publish failed: ${j instanceof Error?j.message:String(j)}`)}let N=Li(R);_(`published ${f.name}@${f.pkgVersion} (kind=${S}) to the marketplace.`),N.length>0&&_(` declares ${N.length} connection input(s): ${N.map(j=>j.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 d=>{let f=await Yt(d.baseUrl).catch(()=>null),v=nu({baseUrl:f?.baseUrl,token:f?.token}),T=0,k=0,y=0;for(let S of v){let R=xe(process.cwd(),S.path),C=await ES(R,S);C==="wrote"?(T+=1,_(` wrote ${S.path}`)):C==="merged"?(y+=1,_(` merged ${S.path} (added the .mcp.json rule)`)):(k+=1,_(` skipped ${S.path} (exists)`))}_(`
|
|
3599
|
+
project init: ${T} written, ${y} merged, ${k} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${ru} (non-destructive).`).action(async()=>{let d=yy(),f=0,v=0;for(let T of d){let k=xe(process.cwd(),T.path);await Ko(k,T.content,T.executable)==="wrote"?(f+=1,_(` wrote ${T.path}`)):(v+=1,_(` skipped ${T.path} (exists)`))}_(`
|
|
3315
3600
|
project ci: ${f} written, ${v} skipped.`),f>0&&(_(`
|
|
3316
|
-
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),_("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),_("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 d=>{let{baseUrl:f,token:v}=await
|
|
3317
|
-
`;d.force?(await ye.mkdir(
|
|
3318
|
-
samples init: ${R} written, ${
|
|
3319
|
-
`+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(Xt($.map(un),{head:Wo})),_(g.dim(" first match wins; lower PRIO is evaluated first."))}),Wt.command("create <name>").description("Create a rule gating 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("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T}),y;try{y=await $.guardrailCreate({name:d,source:f.source,record:f.record,decision:f.decision,...f.op?{op:f.op}:{},...f.target?{target:f.target}:{},...f.actor?{actor:f.actor}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when?{when:f.when}:{},...f.reason?{reason:f.reason}:{},...f.disabled?{enabled:!1}:{},...f.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){oe(S,"extensions:deploy","create a guardrail"),x(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),_(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),Wt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.decision===void 0&&f.priority===void 0&&f.when===void 0&&f.reason===void 0&&x("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T}),y;try{y=await $.guardrailUpdate(d,{...f.decision!==void 0?{decision:f.decision}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when!==void 0?{when:f.when}:{},...f.reason!==void 0?{reason:f.reason}:{}})}catch(S){oe(S,"extensions:deploy","edit a guardrail"),x(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,f,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Wt.command(`${d} <name>`).description(f==="active"?"Arm a parked or proposed 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(T,$)=>{let{baseUrl:y,token:S}=await te($.baseUrl),R=new Y({baseUrl:y,token:S});try{await R.guardrailUpdate(T,{status:f})}catch(O){oe(O,"extensions:deploy",`${d} a guardrail`),x(`${d} guardrail failed: ${O instanceof Error?O.message:String(O)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(T)} ${v}`),f==="inactive"&&_(g.dim(" writes it was gating now fall through to the other rules."))});Wt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T});try{await $.guardrailDelete(d)}catch(y){oe(y,"extensions:deploy","delete a guardrail"),x(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),Wt.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T}),y=O=>O==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let O;try{O=await $.guardrailPostureGet()}catch(C){oe(C,"extensions:deploy","read the guardrail posture"),x(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}_(`guardrail posture: ${g.bold(y(O.mode))}`),_(g.dim(O.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&x("posture must be 'allow' or 'deny'.");let R;try{R=await $.guardrailPostureSet(S)}catch(O){oe(O,"extensions:deploy","set the guardrail posture"),x(`set posture failed: ${O instanceof Error?O.message:String(O)}`)}_(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(R.mode))}`),R.mode==="deny"&&_(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Wt.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let f;if(d.fields)try{f=JSON.parse(d.fields)}catch(R){x(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:v,token:T}=await te(d.baseUrl),$=new Y({baseUrl:v,token:T}),y;try{y=await $.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...f?{fields:f}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){oe(R,"extensions:deploy","test guardrails"),x(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return _(JSON.stringify(y,null,2));let S=`${d.source}/${y.op??d.record}`;y.degraded?(_(`${g.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(g.dim(` ${y.reason}`))):y.allowed?_(`${g.green("\u2713")} ${S} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(_(`${g.red("\u2717")} ${S} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&_(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&_(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let zr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),dn=(d,f={})=>{let v=`${g.bold(d.table)} ${g.dim(d.displayName)}`;_(d.exists===!1?`${v} ${g.dim("(new)")}`:v);for(let T of d.fields){let $=[T.required?"required":null].filter(Boolean).join(", "),y=f.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";_(` ${T.column.padEnd(28)} ${T.type}${$?` (${$})`:""}${y}`)}f.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Wn(d){if(d instanceof pe&&d.status===409){let f=d.body;f?.error==="table_conflict"&&f.message&&(q(f.message),process.exit(1))}x(`tables: ${d instanceof Error?d.message:String(d)}`)}let Fm=async d=>{let f=At(xe(process.cwd(),d),"public","turbobase.json"),v=await ye.readFile(f,"utf8").catch(()=>null);if(v===null)return null;let T;try{T=JSON.parse(v)}catch(y){x(`${f} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let $=T.tables;return $===void 0?{tables:[],manifestPath:f}:(Array.isArray($)||x(`${f}: "tables" must be an array.`),{tables:$,manifestPath:f})};zr.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 d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new Y({baseUrl:f,token:v}),$;try{$=await T.tablesList()}catch(y){oe(y,"extensions:deploy","list tables"),x(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify($,null,2));if($.length===0)return _("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");_(Xt($.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),zr.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(d,f)=>{let v=await Fm(d??".");if(v||x(`no public/turbobase.json under ${xe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:$}=await te(f.baseUrl),y=new Y({baseUrl:T,token:$}),S;try{S=await ae("planning tables",()=>y.tablesPlan({claimedBy:f.as,tables:v.tables}))}catch(R){oe(R,"extensions:deploy","plan tables"),Wn(R)}_(`claiming as ${g.bold(S.claimedBy)}`);for(let R of S.tables)dn(R,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),zr.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(d,f)=>{let v=await Fm(d??".");if(v||x(`no public/turbobase.json under ${xe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:$}=await te(f.baseUrl),y=new Y({baseUrl:T,token:$}),S;try{S=await ae("applying tables",()=>y.tablesApply({claimedBy:f.as,tables:v.tables}))}catch(R){oe(R,"extensions:deploy","apply tables"),Wn(R)}for(let R of S.tables)dn(R,{showClaimants:!0});_(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),zr.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.",(d,f)=>[...f??[],d],[]).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(d,f)=>{let v=f.field.map(R=>{let[O,C,U]=R.split(":");return(!O||!C)&&x(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),U!==void 0&&U!=="required"&&x(`--field "${R}": the third part may only be "required".`),{name:O,type:C,...U==="required"?{required:!0}:{}}}),{baseUrl:T,token:$}=await te(f.baseUrl),y=new Y({baseUrl:T,token:$}),S;try{S=await ae(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:f.name??d,fields:v,...f.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){oe(R,"extensions:deploy","create a table"),Wn(R)}for(let R of S.tables)dn(R);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),zr.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(d,f)=>{f.confirm!==d&&x(`drop refused: --confirm "${f.confirm}" does not match "${d}".`);let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T}),y;try{y=await ae(`dropping cr_${d}`,()=>$.tablesDrop(d,f.confirm))}catch(S){oe(S,"extensions:deploy","drop a table"),x(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!y.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${y.table} and every row in it.`)});let ol=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ol.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 d=>{process.env.TURBOBASE_SANDBOX="1";let f=Um(),v;try{v=await xb(f,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof gs&&x(T.message),x(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}_(`sandbox ${v.name} ready.`),_(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),_(` url: ${v.url}`),_(` expires: ${v.expiresAt}`)}),ol.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let f=Um();await _u(f).catch(()=>[]);let v;try{v=await kb(f,d)}catch(T){x(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}v||x(`no sandbox named '${d}'.`),_(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),ol.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Um(),f=await _u(d).catch(()=>[]),v=await la(),{active:T}=vu(v);if(T.length===0)_("no active sandboxes.");else{for(let $ of T)_(` ${$.name} from=${$.fromTenant} expires=${$.expiresAt} ${$.url}`);_(`
|
|
3320
|
-
${T.length} active sandbox(es).`)}f.length>0&&_(`(reaped ${f.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Qi).action(async d=>{let{baseUrl:f,token:v}=await
|
|
3321
|
-
`,S=xe(process.cwd(),d.out,
|
|
3322
|
-
`).length} lines).`)});let
|
|
3323
|
-
run \`${
|
|
3324
|
-
${
|
|
3325
|
-
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=v.filter(
|
|
3601
|
+
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),_("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),_("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 d=>{let{baseUrl:f,token:v}=await ne(d.baseUrl),T=new X({baseUrl:f,token:v}),k;try{k=await T.catalogRecords()}catch(N){N instanceof pe&&(N.status===401||N.status===403)&&x("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),x(`catalog fetch failed: ${N instanceof Error?N.message:String(N)}`)}if(k.length===0){_("no records in the instance catalog \u2014 nothing to generate.");return}let y=xe(process.cwd(),d.out),S=ey(k,{event:d.event}),R=0,C=0;for(let{recordType:N,fixture:j}of S){let K=At(y,`${N}.json`),M=`${JSON.stringify(j,null,2)}
|
|
3602
|
+
`;d.force?(await ye.mkdir(Vo(K),{recursive:!0}),await ye.writeFile(K,M,{mode:420}),R+=1,_(` wrote ${d.out}/${N}.json`)):await Ko(K,M)==="wrote"?(R+=1,_(` wrote ${d.out}/${N}.json`)):(C+=1,_(` skipped ${d.out}/${N}.json (exists \u2014 use --force to overwrite)`))}_(`
|
|
3603
|
+
samples init: ${R} written, ${C} skipped.`)});let It=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),Wo=d=>[d.name??g.dim(d.id.slice(0,8)),d.status==="active"?g.green("active"):d.status==="proposed"?g.yellow("proposed"):g.dim("inactive"),d.decision==="deny"?g.red(d.decision):d.decision==="require_confirm"?g.yellow(d.decision):g.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??g.dim("any"),d.when||g.dim("(always)"),d.reason??""],xi=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];It.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:v}=await ne(d.baseUrl),T=new X({baseUrl:f,token:v}),k;try{k=await T.guardrailsList()}catch(y){se(y,"extensions:deploy","list guardrails"),x(`list guardrails failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(k,null,2));if(k.length===0)return _(`no write guardrails \u2014 every record the admin entitlement allows is writable.
|
|
3604
|
+
`+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(Xt(k.map(Wo),{head:xi})),_(g.dim(" first match wins; lower PRIO is evaluated first."))}),It.command("create <name>").description("Create a rule gating 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("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await ne(f.baseUrl),k=new X({baseUrl:v,token:T}),y;try{y=await k.guardrailCreate({name:d,source:f.source,record:f.record,decision:f.decision,...f.op?{op:f.op}:{},...f.target?{target:f.target}:{},...f.actor?{actor:f.actor}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when?{when:f.when}:{},...f.reason?{reason:f.reason}:{},...f.disabled?{enabled:!1}:{},...f.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){se(S,"extensions:deploy","create a guardrail"),x(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),_(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),It.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.decision===void 0&&f.priority===void 0&&f.when===void 0&&f.reason===void 0&&x("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:T}=await ne(f.baseUrl),k=new X({baseUrl:v,token:T}),y;try{y=await k.guardrailUpdate(d,{...f.decision!==void 0?{decision:f.decision}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when!==void 0?{when:f.when}:{},...f.reason!==void 0?{reason:f.reason}:{}})}catch(S){se(S,"extensions:deploy","edit a guardrail"),x(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,f,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])It.command(`${d} <name>`).description(f==="active"?"Arm a parked or proposed 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(T,k)=>{let{baseUrl:y,token:S}=await ne(k.baseUrl),R=new X({baseUrl:y,token:S});try{await R.guardrailUpdate(T,{status:f})}catch(C){se(C,"extensions:deploy",`${d} a guardrail`),x(`${d} guardrail failed: ${C instanceof Error?C.message:String(C)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(T)} ${v}`),f==="inactive"&&_(g.dim(" writes it was gating now fall through to the other rules."))});It.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await ne(f.baseUrl),k=new X({baseUrl:v,token:T});try{await k.guardrailDelete(d)}catch(y){se(y,"extensions:deploy","delete a guardrail"),x(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),It.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await ne(f.baseUrl),k=new X({baseUrl:v,token:T}),y=C=>C==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let C;try{C=await k.guardrailPostureGet()}catch(N){se(N,"extensions:deploy","read the guardrail posture"),x(`read posture failed: ${N instanceof Error?N.message:String(N)}`)}_(`guardrail posture: ${g.bold(y(C.mode))}`),_(g.dim(C.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&x("posture must be 'allow' or 'deny'.");let R;try{R=await k.guardrailPostureSet(S)}catch(C){se(C,"extensions:deploy","set the guardrail posture"),x(`set posture failed: ${C instanceof Error?C.message:String(C)}`)}_(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(R.mode))}`),R.mode==="deny"&&_(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),It.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let f;if(d.fields)try{f=JSON.parse(d.fields)}catch(R){x(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:v,token:T}=await ne(d.baseUrl),k=new X({baseUrl:v,token:T}),y;try{y=await k.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...f?{fields:f}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){se(R,"extensions:deploy","test guardrails"),x(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return _(JSON.stringify(y,null,2));let S=`${d.source}/${y.op??d.record}`;y.degraded?(_(`${g.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(g.dim(` ${y.reason}`))):y.allowed?_(`${g.green("\u2713")} ${S} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(_(`${g.red("\u2717")} ${S} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&_(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&_(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let jr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Wn=(d,f={})=>{let v=`${g.bold(d.table)} ${g.dim(d.displayName)}`;_(d.exists===!1?`${v} ${g.dim("(new)")}`:v);for(let T of d.fields){let k=[T.required?"required":null].filter(Boolean).join(", "),y=f.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";_(` ${T.column.padEnd(28)} ${T.type}${k?` (${k})`:""}${y}`)}f.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function ki(d){if(d instanceof pe&&d.status===409){let f=d.body;f?.error==="table_conflict"&&f.message&&(q(f.message),process.exit(1))}x(`tables: ${d instanceof Error?d.message:String(d)}`)}let Hm=async d=>{let f=At(xe(process.cwd(),d),"public","turbobase.json"),v=await ye.readFile(f,"utf8").catch(()=>null);if(v===null)return null;let T;try{T=JSON.parse(v)}catch(y){x(`${f} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let k=T.tables;return k===void 0?{tables:[],manifestPath:f}:(Array.isArray(k)||x(`${f}: "tables" must be an array.`),{tables:k,manifestPath:f})};jr.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 d=>{let{baseUrl:f,token:v}=await ne(d.baseUrl),T=new X({baseUrl:f,token:v}),k;try{k=await T.tablesList()}catch(y){se(y,"extensions:deploy","list tables"),x(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(k,null,2));if(k.length===0)return _("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");_(Xt(k.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),jr.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(d,f)=>{let v=await Hm(d??".");if(v||x(`no public/turbobase.json under ${xe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:k}=await ne(f.baseUrl),y=new X({baseUrl:T,token:k}),S;try{S=await ae("planning tables",()=>y.tablesPlan({claimedBy:f.as,tables:v.tables}))}catch(R){se(R,"extensions:deploy","plan tables"),ki(R)}_(`claiming as ${g.bold(S.claimedBy)}`);for(let R of S.tables)Wn(R,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),jr.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(d,f)=>{let v=await Hm(d??".");if(v||x(`no public/turbobase.json under ${xe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:k}=await ne(f.baseUrl),y=new X({baseUrl:T,token:k}),S;try{S=await ae("applying tables",()=>y.tablesApply({claimedBy:f.as,tables:v.tables}))}catch(R){se(R,"extensions:deploy","apply tables"),ki(R)}for(let R of S.tables)Wn(R,{showClaimants:!0});_(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),jr.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.",(d,f)=>[...f??[],d],[]).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(d,f)=>{let v=f.field.map(R=>{let[C,N,j]=R.split(":");return(!C||!N)&&x(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),j!==void 0&&j!=="required"&&x(`--field "${R}": the third part may only be "required".`),{name:C,type:N,...j==="required"?{required:!0}:{}}}),{baseUrl:T,token:k}=await ne(f.baseUrl),y=new X({baseUrl:T,token:k}),S;try{S=await ae(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:f.name??d,fields:v,...f.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){se(R,"extensions:deploy","create a table"),ki(R)}for(let R of S.tables)Wn(R);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),jr.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(d,f)=>{f.confirm!==d&&x(`drop refused: --confirm "${f.confirm}" does not match "${d}".`);let{baseUrl:v,token:T}=await ne(f.baseUrl),k=new X({baseUrl:v,token:T}),y;try{y=await ae(`dropping cr_${d}`,()=>k.tablesDrop(d,f.confirm))}catch(S){se(S,"extensions:deploy","drop a table"),x(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!y.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${y.table} and every row in it.`)});let sl=e.command("sandbox").description("Ephemeral local authoring sandboxes.");sl.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 d=>{process.env.TURBOBASE_SANDBOX="1";let f=Mm(),v;try{v=await kb(f,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof ms&&x(T.message),x(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}_(`sandbox ${v.name} ready.`),_(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),_(` url: ${v.url}`),_(` expires: ${v.expiresAt}`)}),sl.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let f=Mm();await xu(f).catch(()=>[]);let v;try{v=await $b(f,d)}catch(T){x(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}v||x(`no sandbox named '${d}'.`),_(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),sl.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Mm(),f=await xu(d).catch(()=>[]),v=await ua(),{active:T}=_u(v);if(T.length===0)_("no active sandboxes.");else{for(let k of T)_(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);_(`
|
|
3605
|
+
${T.length} active sandbox(es).`)}f.length>0&&_(`(reaped ${f.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Qi).action(async d=>{let{baseUrl:f,token:v}=await ne(d.baseUrl),T=new X({baseUrl:f,token:v}),k;try{k=await ae("exporting instance config",()=>T.configExport())}catch(R){R instanceof pe&&(R.status===401||R.status===403)&&x("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),x(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let y=typeof k.serialized=="string"?k.serialized:`${JSON.stringify(k.manifest??k,null,2)}
|
|
3606
|
+
`,S=xe(process.cwd(),d.out,us);await ye.mkdir(Vo(S),{recursive:!0}),await ye.writeFile(S,y,"utf8"),_(`wrote ${d.out}/${us} (${y.split(`
|
|
3607
|
+
`).length} lines).`)});let Vm=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),PS=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Km=()=>process.env.TURBOBASE_HOME?.trim()||At(CD(),".turbobase"),AS=()=>"1.5.2",$i=async()=>Promise.all(PS.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Vm.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await $i();for(let f of d)_(`${f.present?He.success("installed"):He.warn("missing")} ${g.bold(f.name)} \u2014 ${f.needs}`);d.some(f=>!f.present)&&_(`
|
|
3608
|
+
run \`${ds} ext extras install\` to fetch them into ${Km()}.`)}),Vm.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await $i();if(d.every(C=>C.present)){_(He.success("extras already installed \u2014 nothing to do."));return}let f=Km();await ye.mkdir(f,{recursive:!0});let v=d.filter(C=>!C.present).map(C=>C.name),T=mu(process.platform,process.arch),k=async(C,N)=>{let{code:j,stderr:K}=await _i("npm",["install","--prefix",f,"--no-audit","--no-fund",...C]);j!==0&&x(`extras install failed while installing ${N} (npm exited ${j}).
|
|
3609
|
+
${K.trim()}
|
|
3610
|
+
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=v.filter(C=>C!=="isolated-vm");if(y.length>0){let C=y.map(N=>`${N}@${hu[N]??"latest"}`);_(`installing ${C.join(", ")} \u2192 ${f}/node_modules \u2026`),await k(C,y.join(", "))}if(v.includes("isolated-vm")){let C=`isolated-vm@${hu["isolated-vm"]}`;if(_(`installing ${C} \u2192 ${f}/node_modules \u2026`),await k(["--ignore-scripts",C],"isolated-vm"),gb.includes(T)){let j=`${fu}@${AS()}`;_(`fetching ${j} (no upstream binary for ${T}) \u2026`);let{code:K}=await _i("npm",["install","--prefix",f,"--no-audit","--no-fund","--ignore-scripts",j]);K!==0&&_(He.warn(`could not fetch ${j} \u2014 falling back to a source build.`))}let N=await yb({home:f});N.length>0&&_(` ${He.success("prebuilt")} ${N.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await $i(),R=S.filter(C=>!C.present).map(C=>C.name);if(R.includes("isolated-vm")){_(He.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${gu()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:C}=await _i("npm",["rebuild","--prefix",f,"isolated-vm"]);C===0&&(S=await $i(),R=S.filter(N=>!N.present).map(N=>N.name))}R.length>0&&x(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${gu()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(He.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Gn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Gn.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 d=>{let f=d.target==="approved"?"approved":d.target==="auto"?"auto":null;f||x(`--target must be 'auto' or 'approved' (got '${d.target}').`);let v=await KD(xe(process.cwd(),d.project??".")),T=Object.keys(v).length;!d.solution&&T===0&&x("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let y=(d.ref?await qm(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await qm(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await qm(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,C=d.prUrl??process.env.PR_URL??null,{baseUrl:N,token:j}=await ne(d.baseUrl),K=new X({baseUrl:N,token:j}),M;try{M=await K.releaseDeploy({solutionId:d.solution??null,target:f,approvedBy:d.approvedBy??null,files:T>0?v:null,gitRepo:S,gitRef:R,gitSha:y,prUrl:C})}catch(te){se(te,"releases:write","release deploy"),te instanceof pe&&te.status===404&&x("solution_not_found \u2014 no solution with that id."),x(`release deploy failed: ${te instanceof Error?te.message:String(te)}`)}_(`release ${M.releaseId} enqueued \u2192 taskId=${M.taskId} (target=${f}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await cu(()=>K.releaseStatus(M.releaseId),`release ${M.releaseId}`,d.intervalMs)}),Gn.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(d,f)=>{let{baseUrl:v,token:T}=await ne(f.baseUrl),k=new X({baseUrl:v,token:T}),y;try{y=await k.releaseFiles(d)}catch(C){C instanceof pe&&C.status===404&&x(`release ${d} not found.`),C instanceof pe&&C.status===409&&x(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),se(C,"releases:write","pull a release"),x(`release pull failed: ${C instanceof Error?C.message:String(C)}`)}let S=xe(process.cwd(),f.dir),R=0;for(let[C,N]of[["owned",y.owned],["context",y.context]])for(let[j,K]of Object.entries(N)){let M=At(S,C,j);await ye.mkdir(Vo(M),{recursive:!0}),await ye.writeFile(M,K,"utf8"),R++}await ye.writeFile(At(S,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),_(`pulled release ${y.releaseId} (${y.status}) \u2192 ${S}
|
|
3326
3611
|
${Object.keys(y.owned).length} owned file(s), ${Object.keys(y.context).length} context file(s), ${R} total
|
|
3327
3612
|
`+(y.logTail?`
|
|
3328
3613
|
the failure these bytes produced:
|
|
3329
3614
|
${y.logTail.trim()}
|
|
3330
3615
|
`:"")+`
|
|
3331
3616
|
edit the files under owned/, then:
|
|
3332
|
-
turbobase release push ${y.releaseId} --dir ${f.dir}`)}),
|
|
3333
|
-
`+
|
|
3334
|
-
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let
|
|
3617
|
+
turbobase release push ${y.releaseId} --dir ${f.dir}`)}),Gn.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(d,f)=>{let{baseUrl:v,token:T}=await ne(f.baseUrl),k=new X({baseUrl:v,token:T}),y=xe(process.cwd(),f.dir),S;try{S=await k.releaseFiles(d)}catch(M){M instanceof pe&&M.status===404&&x(`release ${d} not found.`),se(M,"releases:write","push a release"),x(`release push failed: ${M instanceof Error?M.message:String(M)}`)}let R=async(M,te)=>{try{return await ye.readFile(At(y,M,te),"utf8")}catch{return null}},C=[];for(let[M,te]of Object.entries(S.context)){let Ee=await R("context",M);Ee!==null&&Ee!==te&&C.push(M)}C.length>0&&x(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
|
|
3618
|
+
`+C.map(M=>` context/${M}`).join(`
|
|
3619
|
+
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let N={...S.context},j=0;for(let[M,te]of Object.entries(S.owned)){let Ee=await R("owned",M);N[M]=Ee??te,Ee!==null&&Ee!==te&&j++}j===0&&_("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let K=f.target==="approved"?"approved":"auto";try{let M=await k.releasePush(d,{files:N,target:K,...f.approvedBy?{approvedBy:f.approvedBy}:{}});_(`pushed ${Object.keys(N).length} file(s) (${j} edited) \u2192 release ${M.releaseId} (task ${M.taskId}).
|
|
3335
3620
|
follow it with:
|
|
3336
|
-
turbobase release status ${M.releaseId} --follow`)}catch(M){M instanceof pe&&M.status===403&&x("an approved target needs --approved-by (the deploy gate fails closed)."),M instanceof pe&&M.status===409&&x("that solution already has an active release \u2014 roll it back or wait for it."),
|
|
3337
|
-
${
|
|
3338
|
-
`)),t&&void 0,e}function
|
|
3339
|
-
Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return
|
|
3340
|
-
${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
|
|
3621
|
+
turbobase release status ${M.releaseId} --follow`)}catch(M){M instanceof pe&&M.status===403&&x("an approved target needs --approved-by (the deploy gate fails closed)."),M instanceof pe&&M.status===409&&x("that solution already has an active release \u2014 roll it back or wait for it."),se(M,"releases:write","push a release"),x(`release push failed: ${M instanceof Error?M.message:String(M)}`)}}),Gn.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(d,f)=>{let{baseUrl:v,token:T}=await ne(f.baseUrl),k=new X({baseUrl:v,token:T});if(f.follow){await cu(()=>k.releaseStatus(d),`release ${d}`,f.intervalMs);return}let y;try{y=await k.releaseStatus(d)}catch(S){se(S,"releases:write","release status"),S instanceof pe&&S.status===404&&x(`release ${d} not found.`),x(`release status failed: ${S instanceof Error?S.message:String(S)}`)}_(`release ${d}: status=${y.releaseStatus??"?"} stage=${y.stage} ${y.percent}%`+(y.runStatus?` (${y.runStatus})`:"")),y.outputTail&&_(y.outputTail.replace(/\n+$/,""))}),Gn.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(d,f)=>{let{baseUrl:v,token:T}=await ne(f.baseUrl),k=new X({baseUrl:v,token:T}),y;try{y=await k.releaseRollback(d)}catch(S){se(S,"releases:write","release rollback"),S instanceof pe&&S.status===404&&x(`release ${d} not found.`),S instanceof pe&&S.status===409&&x(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),x(`release rollback failed: ${S instanceof Error?S.message:String(S)}`)}_(`release ${y.releaseId} rolled back \u2192 status=${y.release?.status??"rolled_back"}.`)}),Gn.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 d=>{let{baseUrl:f,token:v}=await ne(d.baseUrl),T=new X({baseUrl:f,token:v}),k;try{k=await T.releaseList()}catch(y){se(y,"releases:write","release list"),x(`release list failed: ${y instanceof Error?y.message:String(y)}`)}if(k.length===0){_("no releases.");return}if(tt())_(Xt(k.map(y=>[y.id,lo(y.status),y.target,y.backend,y.solutionTitles?.length?y.solutionTitles.map(S=>`"${S}"`).join(", "):g.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let y of k){let S=y.solutionTitles?.length?` "${y.solutionTitles.join('", "')}"`:"";_(` ${y.id} ${y.status.padEnd(11)} target=${y.target} backend=${y.backend}${S}`)}_(`
|
|
3622
|
+
${k.length} release(s).`)}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:f,token:v}=await ne(d.baseUrl),T=new X({baseUrl:f,token:v}),k=d.limit?Number(d.limit):void 0,y=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await py(T,d.conduit,{...d.follow?{follow:!0}:{},...k!==void 0?{limit:k}:{},...y!==void 0?{intervalMs:y}:{},sink:_})}catch(S){x(`logs --conduit failed: ${S instanceof Error?S.message:String(S)}`)}return}if(d.extension){try{let S=await T.logs(d.extension,k);S.length===0&&_(`no logs for ${d.extension}.`);for(let R of S)_(` [${R.level}] ${R.ts??""} ${R.message}`)}catch(S){x(`logs --extension failed: ${S instanceof Error?S.message:String(S)}`)}return}try{await fy(T,{...d.subsystem?{subsystem:d.subsystem}:{},...d.severity?{severity:d.severity}:{},...d.code?{code:d.code}:{},...d.since?{since:d.since}:{},...d.correlationId?{correlationId:d.correlationId}:{},...d.follow?{follow:!0}:{},...d.json?{json:!0}:{},...k!==void 0?{limit:k}:{},...y!==void 0?{intervalMs:y}:{},sink:_})}catch(S){x(`logs failed: ${S instanceof Error?S.message:String(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 d=>{let{runAuthoringMcpServer:f}=await Promise.resolve().then(()=>(TS(),SS));await f({baseUrl:d.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(`
|
|
3623
|
+
`)),t&&void 0,e}function ZD(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 BD(t){let e=At(xe(process.cwd(),t),"public","turbobase.json"),r=await ye.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){x(`${e} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&x(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function FD(){let t=xe(process.cwd(),Qi,us),e;try{e=await ye.readFile(t,"utf8")}catch{x(`no config found \u2014 this project authors none (no ${ra}/, ${na}/, ${Vr} or ${Kr}) and there is no ${Qi}/${us}.
|
|
3624
|
+
Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Sy(e)}catch(r){x(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function Um(){let t=process.cwd();if(!await Ry(t))return FD();let e;try{e=await Py(t)}catch(r){x(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)q(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&x(`${e.unparsed.length} extension file(s) could not be identified. Every hook/conduit needs a literal \`id:\`, \`recordType:\` and \`event:\`/\`on:\` \u2014 run \`turbobase ext lint <file>\` on each.`),e.manifest}function HD(t,e){_(`plan against ${e}:`);for(let r of t.add)_(` ${Zr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)_(` ${Zr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)_(` ${Zr.destroy(`${r.kind} ${r.id}`)}`);_(`
|
|
3625
|
+
${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 VD(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function _i(t,e,r){return new Promise(n=>{let o=Bm(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 Mm(){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 _i("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 _i("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 KD(t){let e=xe(t,"src"),r={},n=async o=>{let s;try{s=await ye.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=At(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=ol(e,a).split(Zm).join("/");r[c]=await ye.readFile(a,"utf8")}}};return await n(e),r}function qm(t){return new Promise(e=>{let r=Bm("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 WD=!1;WD&&Fm().parseAsync(process.argv).catch(t=>x(t instanceof Error?t.message:String(t)));Fm().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
|
|
3341
3626
|
`),process.exit(1)});
|