@turbobase/cli 1.48.1 → 1.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,58 +1,58 @@
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 BR=Object.create;var zl=Object.defineProperty;var ZR=Object.getOwnPropertyDescriptor;var VR=Object.getOwnPropertyNames;var HR=Object.getPrototypeOf,KR=Object.prototype.hasOwnProperty;var cs=(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 L=(t,e)=>()=>(t&&(e=t(t=0)),e);var B=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ls=(t,e)=>{for(var r in e)zl(t,r,{get:e[r],enumerable:!0})},WR=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of VR(e))!KR.call(t,o)&&o!==r&&zl(t,o,{get:()=>e[o],enumerable:!(n=ZR(e,o))||n.enumerable});return t};var Dl=(t,e,r)=>(r=t!=null?BR(HR(t)):{},WR(e||!t||!t.__esModule?zl(r,"default",{value:t,enumerable:!0}):r,t));var us=B(Ul=>{var Bi=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}},Ml=class extends Bi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Ul.CommanderError=Bi;Ul.InvalidArgumentError=Ml});var Zi=B(Fl=>{var{InvalidArgumentError:GR}=us(),ql=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 GR(`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 JR(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Fl.Argument=ql;Fl.humanReadableArgName=JR});var Zl=B(Bg=>{var{humanReadableArgName:YR}=Zi(),Bl=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=>YR(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(m,b){if(b){let $=`${m.padEnd(n+i)}${b}`;return r.wrap($,o-s,n+i)}return m}function c(m){return m.join(`
4
+ var ZR=Object.create;var Dl=Object.defineProperty;var VR=Object.getOwnPropertyDescriptor;var HR=Object.getOwnPropertyNames;var KR=Object.getPrototypeOf,WR=Object.prototype.hasOwnProperty;var cs=(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 L=(t,e)=>()=>(t&&(e=t(t=0)),e);var B=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ls=(t,e)=>{for(var r in e)Dl(t,r,{get:e[r],enumerable:!0})},GR=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of HR(e))!WR.call(t,o)&&o!==r&&Dl(t,o,{get:()=>e[o],enumerable:!(n=VR(e,o))||n.enumerable});return t};var Ml=(t,e,r)=>(r=t!=null?ZR(KR(t)):{},GR(e||!t||!t.__esModule?Dl(r,"default",{value:t,enumerable:!0}):r,t));var us=B(ql=>{var Bi=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}},Ul=class extends Bi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ql.CommanderError=Bi;ql.InvalidArgumentError=Ul});var Zi=B(Bl=>{var{InvalidArgumentError:JR}=us(),Fl=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 JR(`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 YR(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Bl.Argument=Fl;Bl.humanReadableArgName=YR});var Vl=B(Zg=>{var{humanReadableArgName:XR}=Zi(),Zl=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=>XR(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(m,b){if(b){let $=`${m.padEnd(n+i)}${b}`;return r.wrap($,o-s,n+i)}return m}function c(m){return m.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(m=>a(r.argumentTerm(m),r.argumentDescription(m)));p.length>0&&(l=l.concat(["Arguments:",c(p),""]));let w=r.visibleOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));if(w.length>0&&(l=l.concat(["Options:",c(w),""])),this.showGlobalOptions){let m=r.visibleGlobalOptions(e).map(b=>a(r.optionTerm(b),r.optionDescription(b)));m.length>0&&(l=l.concat(["Global Options:",c(m),""]))}let f=r.visibleCommands(e).map(m=>a(r.subcommandTerm(m),r.subcommandDescription(m)));return f.length>0&&(l=l.concat(["Commands:",c(f),""])),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",f=new RegExp(`
9
9
  |.{1,${a-1}}([${w}]|$)|[^${w}]+?([${w}]|$)`,"g"),m=l.match(f)||[];return c+m.map((b,$)=>b===`
10
10
  `?"":($>0?u:"")+b.trimEnd()).join(`
11
- `)}};Bg.Help=Bl});var Kl=B(Vi=>{var{InvalidArgumentError:XR}=us(),Vl=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=Zg(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 XR(`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 QR(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Hl=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 QR(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Zg(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}}Vi.Option=Vl;Vi.splitOptionFlags=Zg;Vi.DualOptions=Hl});var Hg=B(Vg=>{function eE(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 tE(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=eE(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?`
11
+ `)}};Zg.Help=Zl});var Wl=B(Vi=>{var{InvalidArgumentError:QR}=us(),Hl=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=Vg(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 QR(`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 eE(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Kl=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 eE(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Vg(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}}Vi.Option=Hl;Vi.splitOptionFlags=Vg;Vi.DualOptions=Kl});var Kg=B(Hg=>{function tE(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 rE(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=tE(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]}?)`:""}Vg.suggestSimilar=tE});var Xg=B(Yg=>{var rE=cs("events").EventEmitter,Wl=cs("child_process"),Ar=cs("path"),Gl=cs("fs"),Be=cs("process"),{Argument:nE,humanReadableArgName:oE}=Zi(),{CommanderError:Jl}=us(),{Help:sE}=Zl(),{Option:Kg,splitOptionFlags:iE,DualOptions:aE}=Kl(),{suggestSimilar:Wg}=Hg(),Yl=class t extends rE{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=>Be.stdout.write(r),writeErr:r=>Be.stderr.write(r),getOutHelpWidth:()=>Be.stdout.isTTY?Be.stdout.columns:void 0,getErrHelpWidth:()=>Be.stderr.isTTY?Be.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 sE,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 nE(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 Jl(e,r,n)),Be.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 Kg(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 Kg)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=Be.argv,Be.versions&&Be.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":Be.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=Ar.resolve(u,p);if(Gl.existsSync(w))return w;if(o.includes(Ar.extname(p)))return;let f=o.find(m=>Gl.existsSync(`${w}${m}`));if(f)return`${w}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Gl.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Ar.resolve(Ar.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let p=Ar.basename(this._scriptPath,Ar.extname(this._scriptPath));p!==this._name&&(u=s(a,`${p}-${e._name}`))}i=u||i}n=o.includes(Ar.extname(i));let c;Be.platform!=="win32"?n?(r.unshift(i),r=Jg(Be.execArgv).concat(r),c=Wl.spawn(Be.argv[0],r,{stdio:"inherit"})):c=Wl.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=Jg(Be.execArgv).concat(r),c=Wl.spawn(Be.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{Be.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});let l=this._exitCallback;l?c.on("close",()=>{l(new Jl(Be.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",Be.exit.bind(Be)),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
13
+ (Did you mean ${n[0]}?)`:""}Hg.suggestSimilar=rE});var Qg=B(Xg=>{var nE=cs("events").EventEmitter,Gl=cs("child_process"),Ar=cs("path"),Jl=cs("fs"),Be=cs("process"),{Argument:oE,humanReadableArgName:sE}=Zi(),{CommanderError:Yl}=us(),{Help:iE}=Vl(),{Option:Wg,splitOptionFlags:aE,DualOptions:cE}=Wl(),{suggestSimilar:Gg}=Kg(),Xl=class t extends nE{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=>Be.stdout.write(r),writeErr:r=>Be.stderr.write(r),getOutHelpWidth:()=>Be.stdout.isTTY?Be.stdout.columns:void 0,getErrHelpWidth:()=>Be.stderr.isTTY?Be.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 iE,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 oE(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 Yl(e,r,n)),Be.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 Wg(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 Wg)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=Be.argv,Be.versions&&Be.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":Be.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=Ar.resolve(u,p);if(Jl.existsSync(w))return w;if(o.includes(Ar.extname(p)))return;let f=o.find(m=>Jl.existsSync(`${w}${m}`));if(f)return`${w}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Jl.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Ar.resolve(Ar.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let p=Ar.basename(this._scriptPath,Ar.extname(this._scriptPath));p!==this._name&&(u=s(a,`${p}-${e._name}`))}i=u||i}n=o.includes(Ar.extname(i));let c;Be.platform!=="win32"?n?(r.unshift(i),r=Yg(Be.execArgv).concat(r),c=Gl.spawn(Be.argv[0],r,{stdio:"inherit"})):c=Gl.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=Yg(Be.execArgv).concat(r),c=Gl.spawn(Be.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{Be.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});let l=this._exitCallback;l?c.on("close",()=>{l(new Yl(Be.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",Be.exit.bind(Be)),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)Be.exit(1);else{let p=new Jl(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 Gg(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),Gg(this,n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(s,e,r)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let o=n.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let o=e.find(s=>n.conflictsWith.includes(s.attributeName()));o&&this._conflictingOption(n,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],o=r,s=e.slice();function i(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){o===n&&o.push(c),o.push(...s);break}if(a&&!i(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,i(c)){let l=this._findOption(c);if(l){if(l.required){let u=s.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;s.length>0&&!i(s[0])&&(u=s.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(i(c)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(c)){r.push(c),s.length>0&&n.push(...s);break}else if(c===this._helpCommandName&&this._hasImplicitHelpCommand()){r.push(c),s.length>0&&r.push(...s);break}else if(this._defaultCommandName){n.push(c),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){o.push(c),s.length>0&&o.push(...s);break}o.push(c)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let o=this.options[n].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
18
+ - ${p}`;throw new Error(w)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Be.exit(1);else{let p=new Yl(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 Jg(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),Jg(this,n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(s,e,r)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let o=n.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let o=e.find(s=>n.conflictsWith.includes(s.attributeName()));o&&this._conflictingOption(n,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],o=r,s=e.slice();function i(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){o===n&&o.push(c),o.push(...s);break}if(a&&!i(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,i(c)){let l=this._findOption(c);if(l){if(l.required){let u=s.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;s.length>0&&!i(s[0])&&(u=s.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(i(c)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(c)){r.push(c),s.length>0&&n.push(...s);break}else if(c===this._helpCommandName&&this._hasImplicitHelpCommand()){r.push(c),s.length>0&&r.push(...s);break}else if(this._defaultCommandName){n.push(c),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){o.push(c),s.length>0&&o.push(...s);break}o.push(c)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let o=this.options[n].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
19
19
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
20
20
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
21
- `),this.outputHelp({error:!0}));let n=r||{},o=n.exitCode||1,s=n.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in Be.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()}`,Be.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new aE(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=Wg(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=Wg(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=>oE(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=Ar.basename(e,Ar.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=iE(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let r=Be.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
21
+ `),this.outputHelp({error:!0}));let n=r||{},o=n.exitCode||1,s=n.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in Be.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()}`,Be.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new cE(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=Gg(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=Gg(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=>sE(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=Ar.basename(e,Ar.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=aE(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let r=Be.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 Gg(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function Jg(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})}Yg.Command=Yl});var ry=B((tr,ty)=>{var{Argument:cE}=Zi(),{Command:Qg}=Xg(),{CommanderError:lE,InvalidArgumentError:ey}=us(),{Help:uE}=Zl(),{Option:dE}=Kl();tr=ty.exports=new Qg;tr.program=tr;tr.Command=Qg;tr.Option=dE;tr.Argument=cE;tr.Help=uE;tr.CommanderError=lE;tr.InvalidArgumentError=ey;tr.InvalidOptionArgumentError=ey});function _n(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var ds=L(()=>{});var we,Xl,H,yr,ps=L(()=>{(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})(we||(we={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Xl||(Xl={}));H=we.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yr=t=>{switch(typeof t){case"undefined":return H.undefined;case"string":return H.string;case"number":return Number.isNaN(t)?H.nan:H.number;case"boolean":return H.boolean;case"function":return H.function;case"bigint":return H.bigint;case"symbol":return H.symbol;case"object":return Array.isArray(t)?H.array:t===null?H.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?H.promise:typeof Map<"u"&&t instanceof Map?H.map:typeof Set<"u"&&t instanceof Set?H.set:typeof Date<"u"&&t instanceof Date?H.date:H.object;default:return H.unknown}}});var z,pE,St,Hi=L(()=>{ps();z=we.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"]),pE=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),St=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,we.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()}};St.create=t=>new St(t)});var hE,Cr,Ql=L(()=>{Hi();ps();hE=(t,e)=>{let r;switch(t.code){case z.invalid_type:t.received===H.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case z.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,we.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:r=`Unrecognized key(s) in object: ${we.joinValues(t.keys,", ")}`;break;case z.invalid_union:r="Invalid input";break;case z.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${we.joinValues(t.options)}`;break;case z.invalid_enum_value:r=`Invalid enum value. Expected ${we.joinValues(t.options)}, received '${t.received}'`;break;case z.invalid_arguments:r="Invalid function arguments";break;case z.invalid_return_type:r="Invalid function return type";break;case z.invalid_date:r="Invalid date";break;case z.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}"`:we.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case z.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 z.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 z.custom:r="Invalid input";break;case z.invalid_intersection_types:r="Intersection results could not be merged";break;case z.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case z.not_finite:r="Number must be finite";break;default:r=e.defaultError,we.assertNever(t)}return{message:r}},Cr=hE});function mE(t){sy=t}function lo(){return sy}var sy,Ki=L(()=>{Ql();sy=Cr});function Z(t,e){let r=lo(),n=hs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Cr?void 0:Cr].filter(o=>!!o)});t.common.issues.push(n)}var hs,fE,it,oe,vn,mt,Wi,Gi,Kr,uo,eu=L(()=>{Ki();Ql();hs=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}},fE=[];it=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 oe;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 oe;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}}},oe=Object.freeze({status:"aborted"}),vn=t=>({status:"dirty",value:t}),mt=t=>({status:"valid",value:t}),Wi=t=>t.status==="aborted",Gi=t=>t.status==="dirty",Kr=t=>t.status==="valid",uo=t=>typeof Promise<"u"&&t instanceof Promise});var iy=L(()=>{});var X,ay=L(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(X||(X={}))});function de(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 dy(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 IE(t){return new RegExp(`^${dy(t)}$`)}function py(t){let e=`${uy}T${dy(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 OE(t,e){return!!((e==="v4"||!e)&&$E.test(t)||(e==="v6"||!e)&&RE.test(t))}function NE(t,e){if(!vE.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 LE(t,e){return!!((e==="v4"||!e)&&TE.test(t)||(e==="v6"||!e)&&EE.test(t))}function jE(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 po(t){if(t instanceof Tt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=$t.create(po(n))}return new Tt({...t._def,shape:()=>e})}else return t instanceof Nr?new Nr({...t._def,type:po(t.element)}):t instanceof $t?$t.create(po(t.unwrap())):t instanceof wr?wr.create(po(t.unwrap())):t instanceof br?br.create(t.items.map(e=>po(e))):t}function ru(t,e){let r=yr(t),n=yr(e);if(t===e)return{valid:!0,data:t};if(r===H.object&&n===H.object){let o=we.objectKeys(e),s=we.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=ru(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===H.array&&n===H.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=ru(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===H.date&&n===H.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function hy(t,e){return new In({values:t,typeName:U.ZodEnum,...de(e)})}function ly(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function my(t,e={},r){return t?Gr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=ly(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=ly(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Gr.create()}var qt,cy,he,gE,yE,bE,wE,_E,vE,xE,kE,SE,tu,$E,TE,RE,EE,PE,AE,uy,CE,Wr,xn,kn,Sn,$n,ho,Tn,Rn,Gr,Or,rr,mo,Nr,Tt,En,Ir,Ji,Pn,br,Yi,fo,go,Xi,An,Cn,In,On,Jr,Ft,$t,wr,Nn,Ln,yo,zE,ms,fs,jn,DE,U,ME,fy,gy,UE,qE,yy,FE,BE,ZE,VE,HE,KE,WE,GE,JE,nu,YE,XE,QE,e0,t0,r0,n0,o0,s0,i0,a0,c0,l0,u0,d0,p0,h0,m0,f0,g0,y0,b0,w0,_0,by=L(()=>{Hi();Ki();ay();eu();ps();qt=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}},cy=(t,e)=>{if(Kr(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 St(t.common.issues);return this._error=r,this._error}}};he=class{get description(){return this._def.description}_getType(e){return yr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new it,ctx:{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(uo(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:yr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return cy(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Kr(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=>Kr(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:yr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(uo(o)?o:Promise.resolve(o));return cy(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:z.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 Ft({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 $t.create(this,this._def)}nullable(){return wr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Nr.create(this)}promise(){return Jr.create(this,this._def)}or(e){return En.create([this,e],this._def)}and(e){return Pn.create(this,e,this._def)}transform(e){return new Ft({...de(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Nn({...de(this._def),innerType:this,defaultValue:r,typeName:U.ZodDefault})}brand(){return new ms({typeName:U.ZodBranded,type:this,...de(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ln({...de(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 fs.create(this,e)}readonly(){return jn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},gE=/^c[^\s-]{8,}$/i,yE=/^[0-9a-z]+$/,bE=/^[0-9A-HJKMNP-TV-Z]{26}$/i,wE=/^[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,_E=/^[a-z0-9_-]{21}$/i,vE=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,xE=/^[-+]?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)?)??$/,kE=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,SE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",$E=/^(?:(?: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])$/,TE=/^(?:(?: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])$/,RE=/^(([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]))$/,EE=/^(([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])$/,PE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,AE=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,uy="((\\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])))",CE=new RegExp(`^${uy}$`);Wr=class t extends he{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==H.string){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_type,expected:H.string,received:s.parsedType}),oe}let n=new it,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?Z(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Z(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")kE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"email",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")tu||(tu=new RegExp(SE,"u")),tu.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"emoji",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")wE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"uuid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")_E.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"nanoid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")gE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")yE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid2",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")bE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ulid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),Z(o,{validation:"url",code:z.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"regex",code:z.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?py(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?CE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?IE(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?xE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"duration",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?OE(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ip",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?NE(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"jwt",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?LE(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cidr",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?PE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?AE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64url",code:z.invalid_string,message:s.message}),n.dirty()):we.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:z.invalid_string,...X.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...X.errToObj(e)})}url(e){return this._addCheck({kind:"url",...X.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...X.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...X.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...X.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...X.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...X.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...X.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...X.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...X.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...X.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...X.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...X.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,...X.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,...X.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...X.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...X.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...X.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...X.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...X.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...X.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...X.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...X.errToObj(r)})}nonempty(e){return this.min(1,X.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}};Wr.create=t=>new Wr({checks:[],typeName:U.ZodString,coerce:t?.coerce??!1,...de(t)});xn=class t extends he{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)!==H.number){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_type,expected:H.number,received:s.parsedType}),oe}let n,o=new it;for(let s of this._def.checks)s.kind==="int"?we.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:z.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?jE(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:z.not_finite,message:s.message}),o.dirty()):we.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,X.toString(r))}gt(e,r){return this.setLimit("min",e,!1,X.toString(r))}lte(e,r){return this.setLimit("max",e,!0,X.toString(r))}lt(e,r){return this.setLimit("max",e,!1,X.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:X.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:X.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:X.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.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"&&we.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)}};xn.create=t=>new xn({checks:[],typeName:U.ZodNumber,coerce:t?.coerce||!1,...de(t)});kn=class t extends he{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)!==H.bigint)return this._getInvalidInput(e);let n,o=new it;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):we.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Z(r,{code:z.invalid_type,expected:H.bigint,received:r.parsedType}),oe}gte(e,r){return this.setLimit("min",e,!0,X.toString(r))}gt(e,r){return this.setLimit("min",e,!1,X.toString(r))}lte(e,r){return this.setLimit("max",e,!0,X.toString(r))}lt(e,r){return this.setLimit("max",e,!1,X.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:X.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:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:X.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}};kn.create=t=>new kn({checks:[],typeName:U.ZodBigInt,coerce:t?.coerce??!1,...de(t)});Sn=class extends he{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==H.boolean){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.boolean,received:n.parsedType}),oe}return mt(e.data)}};Sn.create=t=>new Sn({typeName:U.ZodBoolean,coerce:t?.coerce||!1,...de(t)});$n=class t extends he{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==H.date){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_type,expected:H.date,received:s.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_date}),oe}let n=new it,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):we.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:X.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:X.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}};$n.create=t=>new $n({checks:[],coerce:t?.coerce||!1,typeName:U.ZodDate,...de(t)});ho=class extends he{_parse(e){if(this._getType(e)!==H.symbol){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.symbol,received:n.parsedType}),oe}return mt(e.data)}};ho.create=t=>new ho({typeName:U.ZodSymbol,...de(t)});Tn=class extends he{_parse(e){if(this._getType(e)!==H.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.undefined,received:n.parsedType}),oe}return mt(e.data)}};Tn.create=t=>new Tn({typeName:U.ZodUndefined,...de(t)});Rn=class extends he{_parse(e){if(this._getType(e)!==H.null){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.null,received:n.parsedType}),oe}return mt(e.data)}};Rn.create=t=>new Rn({typeName:U.ZodNull,...de(t)});Gr=class extends he{constructor(){super(...arguments),this._any=!0}_parse(e){return mt(e.data)}};Gr.create=t=>new Gr({typeName:U.ZodAny,...de(t)});Or=class extends he{constructor(){super(...arguments),this._unknown=!0}_parse(e){return mt(e.data)}};Or.create=t=>new Or({typeName:U.ZodUnknown,...de(t)});rr=class extends he{_parse(e){let r=this._getOrReturnCtx(e);return Z(r,{code:z.invalid_type,expected:H.never,received:r.parsedType}),oe}};rr.create=t=>new rr({typeName:U.ZodNever,...de(t)});mo=class extends he{_parse(e){if(this._getType(e)!==H.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.void,received:n.parsedType}),oe}return mt(e.data)}};mo.create=t=>new mo({typeName:U.ZodVoid,...de(t)});Nr=class t extends he{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==H.array)return Z(r,{code:z.invalid_type,expected:H.array,received:r.parsedType}),oe;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(Z(r,{code:i?z.too_big:z.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(Z(r,{code:z.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(Z(r,{code:z.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 qt(r,i,r.path,a)))).then(i=>it.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new qt(r,i,r.path,a)));return it.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:X.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:X.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:X.toString(r)}})}nonempty(e){return this.min(1,e)}};Nr.create=(t,e)=>new Nr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...de(e)});Tt=class t extends he{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=we.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==H.object){let l=this._getOrReturnCtx(e);return Z(l,{code:z.invalid_type,expected:H.object,received:l.parsedType}),oe}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof rr&&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 qt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof rr){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(Z(o,{code:z.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 qt(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=>it.mergeObjectSync(n,l)):it.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return X.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:X.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 we.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 we.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return po(this)}partial(e){let r={};for(let n of we.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 we.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof $t;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return hy(we.objectKeys(this.shape))}};Tt.create=(t,e)=>new Tt({shape:()=>t,unknownKeys:"strip",catchall:rr.create(),typeName:U.ZodObject,...de(e)});Tt.strictCreate=(t,e)=>new Tt({shape:()=>t,unknownKeys:"strict",catchall:rr.create(),typeName:U.ZodObject,...de(e)});Tt.lazycreate=(t,e)=>new Tt({shape:t,unknownKeys:"strip",catchall:rr.create(),typeName:U.ZodObject,...de(e)});En=class extends he{_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 St(a.ctx.common.issues));return Z(r,{code:z.invalid_union,unionErrors:i}),oe}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 St(c));return Z(r,{code:z.invalid_union,unionErrors:a}),oe}}get options(){return this._def.options}};En.create=(t,e)=>new En({options:t,typeName:U.ZodUnion,...de(e)});Ir=t=>t instanceof An?Ir(t.schema):t instanceof Ft?Ir(t.innerType()):t instanceof Cn?[t.value]:t instanceof In?t.options:t instanceof On?we.objectValues(t.enum):t instanceof Nn?Ir(t._def.innerType):t instanceof Tn?[void 0]:t instanceof Rn?[null]:t instanceof $t?[void 0,...Ir(t.unwrap())]:t instanceof wr?[null,...Ir(t.unwrap())]:t instanceof ms||t instanceof jn?Ir(t.unwrap()):t instanceof Ln?Ir(t._def.innerType):[],Ji=class t extends he{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==H.object)return Z(r,{code:z.invalid_type,expected:H.object,received:r.parsedType}),oe;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Z(r,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),oe)}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=Ir(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,...de(n)})}};Pn=class extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Wi(s)||Wi(i))return oe;let a=ru(s.value,i.value);return a.valid?((Gi(s)||Gi(i))&&r.dirty(),{status:r.value,value:a.data}):(Z(n,{code:z.invalid_intersection_types}),oe)};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}))}};Pn.create=(t,e,r)=>new Pn({left:t,right:e,typeName:U.ZodIntersection,...de(r)});br=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.array)return Z(n,{code:z.invalid_type,expected:H.array,received:n.parsedType}),oe;if(n.data.length<this._def.items.length)return Z(n,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;!this._def.rest&&n.data.length>this._def.items.length&&(Z(n,{code:z.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 qt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>it.mergeArray(r,i)):it.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};br.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new br({items:t,typeName:U.ZodTuple,rest:null,...de(e)})};Yi=class t extends he{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!==H.object)return Z(n,{code:z.invalid_type,expected:H.object,received:n.parsedType}),oe;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new qt(n,a,n.path,a)),value:i._parse(new qt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?it.mergeObjectAsync(r,o):it.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof he?new t({keyType:e,valueType:r,typeName:U.ZodRecord,...de(n)}):new t({keyType:Wr.create(),valueType:e,typeName:U.ZodRecord,...de(r)})}},fo=class extends he{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!==H.map)return Z(n,{code:z.invalid_type,expected:H.map,received:n.parsedType}),oe;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new qt(n,a,n.path,[l,"key"])),value:s._parse(new qt(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 oe;(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 oe;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};fo.create=(t,e,r)=>new fo({valueType:e,keyType:t,typeName:U.ZodMap,...de(r)});go=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.set)return Z(n,{code:z.invalid_type,expected:H.set,received:n.parsedType}),oe;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(Z(n,{code:z.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(Z(n,{code:z.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 oe;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 qt(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:X.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:X.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};go.create=(t,e)=>new go({valueType:t,minSize:null,maxSize:null,typeName:U.ZodSet,...de(e)});Xi=class t extends he{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==H.function)return Z(r,{code:z.invalid_type,expected:H.function,received:r.parsedType}),oe;function n(a,c){return hs({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lo(),Cr].filter(l=>!!l),issueData:{code:z.invalid_arguments,argumentsError:c}})}function o(a,c){return hs({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,lo(),Cr].filter(l=>!!l),issueData:{code:z.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Jr){let a=this;return mt(async function(...c){let l=new St([]),u=await a._def.args.parseAsync(c,s).catch(f=>{throw l.addIssue(n(c,f)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(f=>{throw l.addIssue(o(p,f)),l})})}else{let a=this;return mt(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new St([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new St([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:br.create(e).rest(Or.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||br.create([]).rest(Or.create()),returns:r||Or.create(),typeName:U.ZodFunction,...de(n)})}},An=class extends he{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})}};An.create=(t,e)=>new An({getter:t,typeName:U.ZodLazy,...de(e)});Cn=class extends he{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Z(r,{received:r.data,code:z.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}};Cn.create=(t,e)=>new Cn({value:t,typeName:U.ZodLiteral,...de(e)});In=class t extends he{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{expected:we.joinValues(n),received:r.parsedType,code:z.invalid_type}),oe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{received:r.data,code:z.invalid_enum_value,options:n}),oe}return mt(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})}};In.create=hy;On=class extends he{_parse(e){let r=we.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==H.string&&n.parsedType!==H.number){let o=we.objectValues(r);return Z(n,{expected:we.joinValues(o),received:n.parsedType,code:z.invalid_type}),oe}if(this._cache||(this._cache=new Set(we.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=we.objectValues(r);return Z(n,{received:n.data,code:z.invalid_enum_value,options:o}),oe}return mt(e.data)}get enum(){return this._def.values}};On.create=(t,e)=>new On({values:t,typeName:U.ZodNativeEnum,...de(e)});Jr=class extends he{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==H.promise&&r.common.async===!1)return Z(r,{code:z.invalid_type,expected:H.promise,received:r.parsedType}),oe;let n=r.parsedType===H.promise?r.data:Promise.resolve(r.data);return mt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Jr.create=(t,e)=>new Jr({type:t,typeName:U.ZodPromise,...de(e)});Ft=class extends he{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=>{Z(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return oe;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?oe:c.status==="dirty"?vn(c.value):r.value==="dirty"?vn(c.value):c});{if(r.value==="aborted")return oe;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?oe:a.status==="dirty"?vn(a.value):r.value==="dirty"?vn(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"?oe:(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"?oe:(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(!Kr(i))return oe;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=>Kr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):oe);we.assertNever(o)}};Ft.create=(t,e,r)=>new Ft({schema:t,typeName:U.ZodEffects,effect:e,...de(r)});Ft.createWithPreprocess=(t,e,r)=>new Ft({schema:e,effect:{type:"preprocess",transform:t},typeName:U.ZodEffects,...de(r)});$t=class extends he{_parse(e){return this._getType(e)===H.undefined?mt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$t.create=(t,e)=>new $t({innerType:t,typeName:U.ZodOptional,...de(e)});wr=class extends he{_parse(e){return this._getType(e)===H.null?mt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wr.create=(t,e)=>new wr({innerType:t,typeName:U.ZodNullable,...de(e)});Nn=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===H.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Nn.create=(t,e)=>new Nn({innerType:t,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...de(e)});Ln=class extends he{_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 uo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new St(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new St(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ln.create=(t,e)=>new Ln({innerType:t,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...de(e)});yo=class extends he{_parse(e){if(this._getType(e)!==H.nan){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.nan,received:n.parsedType}),oe}return{status:"valid",value:e.data}}};yo.create=t=>new yo({typeName:U.ZodNaN,...de(t)});zE=Symbol("zod_brand"),ms=class extends he{_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}},fs=class t extends he{_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"?oe:s.status==="dirty"?(r.dirty(),vn(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"?oe: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})}},jn=class extends he{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Kr(o)&&(o.value=Object.freeze(o.value)),o);return uo(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};jn.create=(t,e)=>new jn({innerType:t,typeName:U.ZodReadonly,...de(e)});DE={object:Tt.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={}));ME=(t,e={message:`Input not instance of ${t.name}`})=>my(r=>r instanceof t,e),fy=Wr.create,gy=xn.create,UE=yo.create,qE=kn.create,yy=Sn.create,FE=$n.create,BE=ho.create,ZE=Tn.create,VE=Rn.create,HE=Gr.create,KE=Or.create,WE=rr.create,GE=mo.create,JE=Nr.create,nu=Tt.create,YE=Tt.strictCreate,XE=En.create,QE=Ji.create,e0=Pn.create,t0=br.create,r0=Yi.create,n0=fo.create,o0=go.create,s0=Xi.create,i0=An.create,a0=Cn.create,c0=In.create,l0=On.create,u0=Jr.create,d0=Ft.create,p0=$t.create,h0=wr.create,m0=Ft.createWithPreprocess,f0=fs.create,g0=()=>fy().optional(),y0=()=>gy().optional(),b0=()=>yy().optional(),w0={string:(t=>Wr.create({...t,coerce:!0})),number:(t=>xn.create({...t,coerce:!0})),boolean:(t=>Sn.create({...t,coerce:!0})),bigint:(t=>kn.create({...t,coerce:!0})),date:(t=>$n.create({...t,coerce:!0}))},_0=oe});var P={};ls(P,{BRAND:()=>zE,DIRTY:()=>vn,EMPTY_PATH:()=>fE,INVALID:()=>oe,NEVER:()=>_0,OK:()=>mt,ParseStatus:()=>it,Schema:()=>he,ZodAny:()=>Gr,ZodArray:()=>Nr,ZodBigInt:()=>kn,ZodBoolean:()=>Sn,ZodBranded:()=>ms,ZodCatch:()=>Ln,ZodDate:()=>$n,ZodDefault:()=>Nn,ZodDiscriminatedUnion:()=>Ji,ZodEffects:()=>Ft,ZodEnum:()=>In,ZodError:()=>St,ZodFirstPartyTypeKind:()=>U,ZodFunction:()=>Xi,ZodIntersection:()=>Pn,ZodIssueCode:()=>z,ZodLazy:()=>An,ZodLiteral:()=>Cn,ZodMap:()=>fo,ZodNaN:()=>yo,ZodNativeEnum:()=>On,ZodNever:()=>rr,ZodNull:()=>Rn,ZodNullable:()=>wr,ZodNumber:()=>xn,ZodObject:()=>Tt,ZodOptional:()=>$t,ZodParsedType:()=>H,ZodPipeline:()=>fs,ZodPromise:()=>Jr,ZodReadonly:()=>jn,ZodRecord:()=>Yi,ZodSchema:()=>he,ZodSet:()=>go,ZodString:()=>Wr,ZodSymbol:()=>ho,ZodTransformer:()=>Ft,ZodTuple:()=>br,ZodType:()=>he,ZodUndefined:()=>Tn,ZodUnion:()=>En,ZodUnknown:()=>Or,ZodVoid:()=>mo,addIssueToContext:()=>Z,any:()=>HE,array:()=>JE,bigint:()=>qE,boolean:()=>yy,coerce:()=>w0,custom:()=>my,date:()=>FE,datetimeRegex:()=>py,defaultErrorMap:()=>Cr,discriminatedUnion:()=>QE,effect:()=>d0,enum:()=>c0,function:()=>s0,getErrorMap:()=>lo,getParsedType:()=>yr,instanceof:()=>ME,intersection:()=>e0,isAborted:()=>Wi,isAsync:()=>uo,isDirty:()=>Gi,isValid:()=>Kr,late:()=>DE,lazy:()=>i0,literal:()=>a0,makeIssue:()=>hs,map:()=>n0,nan:()=>UE,nativeEnum:()=>l0,never:()=>WE,null:()=>VE,nullable:()=>h0,number:()=>gy,object:()=>nu,objectUtil:()=>Xl,oboolean:()=>b0,onumber:()=>y0,optional:()=>p0,ostring:()=>g0,pipeline:()=>f0,preprocess:()=>m0,promise:()=>u0,quotelessJson:()=>pE,record:()=>r0,set:()=>o0,setErrorMap:()=>mE,strictObject:()=>YE,string:()=>fy,symbol:()=>BE,transformer:()=>d0,tuple:()=>t0,undefined:()=>ZE,union:()=>XE,unknown:()=>KE,util:()=>we,void:()=>GE});var Qi=L(()=>{Ki();eu();iy();ps();by();Hi()});var zn=L(()=>{Qi();Qi()});function ea(t){let e=ou.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function su(t,e){let r=ou.safeParse(t);if(!r.success)throw new Yr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(wy.test(e))throw new Yr('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(wy.test(n))throw new Yr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var _y,vy,ou,Yr,wy,xy=L(()=>{zn();_y=P.object({type:P.literal("connection"),source_system:P.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:P.string().min(1).max(200).optional()}),vy=P.discriminatedUnion("type",[_y]),ou=P.object({inputs:P.array(vy).optional()}).passthrough(),Yr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};wy=/\bconnection[_-]?id\b["']?\s*[:=]/i});var ta,iu=L(()=>{ta=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var au,ky,Sy=L(()=>{zn();ds();iu();au=P.object({id:P.string().min(1,"hook id must be non-empty"),recordType:P.union([P.string().min(1),P.array(P.string().min(1)).min(1),P.literal("*")]),event:P.enum(ta),source:P.string().min(1).optional(),when:P.unknown().optional(),run:P.unknown(),failClosed:P.boolean().optional(),timeoutMs:P.number().int().positive().optional(),description:P.string().optional(),systemReserved:P.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"})}),ky=_n({kind:"hook",schema:au,factoryName:"defineHook"})});var $y=L(()=>{Sy();iu()});var bo,cu=L(()=>{bo=["after_canonicalize_inbound","after_sync_success_outbound","after_save","after_delete"]});var Ty,k0,Ry,lu,Ey,Py=L(()=>{zn();ds();cu();Ty=P.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),k0=P.object({recordType:P.string().min(1,"reads[].recordType must be non-empty"),source:P.string().min(1).optional(),columns:P.array(Ty).min(1,"reads[].columns must name at least one column"),by:P.array(Ty).optional(),maxRows:P.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),Ry=P.object({source:P.string().min(1,"to.source must be non-empty"),recordType:P.string().min(1,"to.recordType must be non-empty"),process:P.string().min(1,"to.process must be non-empty when present").optional()}),lu=P.object({id:P.string().min(1,"conduit id must be non-empty"),on:P.enum(bo),from:P.object({source:P.string().min(1,"from.source must be non-empty"),recordType:P.string().min(1,"from.recordType must be non-empty"),when:P.unknown().optional()}),to:Ry.optional(),mode:P.enum(["dual-bind","one-shot"]).optional(),transform:P.unknown().optional(),sequence:P.array(P.object({to:Ry,transform:P.unknown(),awaitSource:P.boolean().optional()})).optional(),reads:P.array(k0).optional(),maxQueriesPerRun:P.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:P.unknown().optional(),cycleBudget:P.number().int().positive().optional(),conflictStrategy:P.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:P.number().int().positive().optional(),description:P.string().optional(),systemReserved:P.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((l,u)=>{typeof l.transform!="function"&&e.addIssue({code:"custom",path:["sequence",u,"transform"],message:"transform must be a function"}),r.from?.source&&l.to?.source&&r.from.source===l.to.source&&e.addIssue({code:"custom",path:["sequence",u,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,c=r.to;a?.source&&c?.source&&a.source===c.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"})}),Ey=_n({kind:"conduit",schema:lu,factoryName:"defineConduit"})});var Ay=L(()=>{Py();cu()});function Iy(t,e,r){let n=e;if((typeof n.recordType!="string"||n.recordType.length===0)&&t.addIssue({code:"custom",path:[...r,"recordType"],message:"step.recordType must be non-empty"}),n.when!==void 0&&typeof n.when!="function"&&t.addIssue({code:"custom",path:[...r,"when"],message:"when must be a function returning whether this step runs"}),n.delete!==void 0){I0(t,n,r);return}n.onRefused!==void 0&&t.addIssue({code:"custom",path:[...r,"onRefused"],message:"onRefused is only honoured on a delete step \u2014 a refused write always ends the run. Remove it, or declare a `delete` block to make this a delete step"}),typeof n.build!="function"&&t.addIssue({code:"custom",path:[...r,"build"],message:"build must be a function"});let o=n.update;if(o){for(let s of["pgRowId","externalId","expectedSyncVersion"]){let i=o[s];i!==void 0&&typeof i!="function"&&t.addIssue({code:"custom",path:[...r,"update",s],message:`update.${s} must be a function of the step context \u2014 a declaration cannot know the value until the run`})}o.step===void 0&&o.pgRowId===void 0&&o.externalId===void 0&&t.addIssue({code:"custom",path:[...r,"update"],message:"update must address a record: one of `step`, `pgRowId` or `externalId`"})}}function I0(t,e,r){e.build!==void 0&&t.addIssue({code:"custom",path:[...r,"build"],message:"a delete step has nothing to build \u2014 remove `build`, or remove `delete` to make this a write step"}),e.rollback==="undo"&&t.addIssue({code:"custom",path:[...r,"rollback"],message:"a delete cannot be undone, so a delete step is always rollback: 'keep'"});let n=e.delete??{};for(let o of["pgRowId","externalId"]){let s=n[o];s!==void 0&&typeof s!="function"&&t.addIssue({code:"custom",path:[...r,"delete",o],message:`delete.${o} must be a function of the step context \u2014 a declaration cannot know the value until the run`})}n.pgRowId===void 0&&n.externalId===void 0&&t.addIssue({code:"custom",path:[...r,"delete"],message:"delete must address a record: one of `pgRowId` or `externalId`"})}function O0(t,e,r){e.forEach===void 0&&t.addIssue({code:"custom",path:["steps",r,"forEach"],message:"a step-list entry carrying nested steps must declare forEach.input, naming the input property to repeat over"});let n=e.steps;if(!Array.isArray(n)||n.length===0){t.addIssue({code:"custom",path:["steps",r,"steps"],message:"a repeated group needs at least one step in it, or it writes nothing at all"});return}let o=new Map;n.forEach((s,i)=>{Iy(t,s,["steps",r,"steps",i]);let a=s.id;if(typeof a!="string")return;let c=o.get(a);c!==void 0?t.addIssue({code:"custom",path:["steps",r,"steps"],message:`duplicate step id '${a}' (steps ${c} and ${i}) \u2014 step ids must be unique within a repeated group`}):o.set(a,i)})}var Cy,A0,C0,uu,Oy,Ny=L(()=>{zn();ds();Cy={id:P.string().min(1,"step id must be non-empty"),recordType:P.string().min(1,"step.recordType must be non-empty").optional(),awaitSource:P.boolean().optional(),update:P.object({step:P.string().min(1,"update.step must name an earlier step").optional(),pgRowId:P.unknown().optional(),externalId:P.unknown().optional(),expectedSyncVersion:P.unknown().optional()}).optional(),when:P.unknown().optional(),rollback:P.enum(["undo","keep"]).optional(),onRefused:P.enum(["continue","stop"]).optional(),delete:P.object({pgRowId:P.unknown().optional(),externalId:P.unknown().optional(),sourceSystem:P.string().min(1,"delete.sourceSystem must name a connected system").optional()}).optional(),build:P.unknown(),description:P.string().optional()},A0=P.object(Cy),C0=P.object({...Cy,forEach:P.object({input:P.string().min(1,"forEach.input must name a property of the process input holding the array to repeat over")}).optional(),steps:P.array(A0).optional()}),uu=P.object({id:P.string().min(1,"process id must be non-empty"),input:P.object({type:P.literal("object"),properties:P.record(P.unknown()).optional(),required:P.array(P.string()).optional()}).passthrough(),steps:P.array(C0).min(1,"a process needs at least one step"),eachRow:P.object({outstanding:P.unknown(),key:P.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:P.enum(["stop","rollback"]).optional(),description:P.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(a.forEach!==void 0||a.steps!==void 0?O0(e,a,i):Iy(e,s,["steps",i]),typeof a.id=="string"){let c=o.get(a.id);c!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${c} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})});Oy=_n({kind:"process",schema:uu,factoryName:"defineProcess"})});var Ly=L(()=>{});var jy=L(()=>{Ny();Ly()});async function D0(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 oa(t,e={}){return(e.transform??D0)(t)}var du=L(()=>{});function sa(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 wo(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function ia(t){return`${wo(t.source)}${wo(t.recordType)}`}function zy(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Dy(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.currencyKey&&e.push(`currency from ${t.currencyKey}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function pu(t){let e=ia(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 Jg(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function Yg(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})}Xg.Command=Xl});var ny=B((tr,ry)=>{var{Argument:lE}=Zi(),{Command:ey}=Qg(),{CommanderError:uE,InvalidArgumentError:ty}=us(),{Help:dE}=Vl(),{Option:pE}=Wl();tr=ry.exports=new ey;tr.program=tr;tr.Command=ey;tr.Option=pE;tr.Argument=lE;tr.Help=dE;tr.CommanderError=uE;tr.InvalidArgumentError=ty;tr.InvalidOptionArgumentError=ty});function _n(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var ds=L(()=>{});var we,Ql,H,yr,ps=L(()=>{(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})(we||(we={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ql||(Ql={}));H=we.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yr=t=>{switch(typeof t){case"undefined":return H.undefined;case"string":return H.string;case"number":return Number.isNaN(t)?H.nan:H.number;case"boolean":return H.boolean;case"function":return H.function;case"bigint":return H.bigint;case"symbol":return H.symbol;case"object":return Array.isArray(t)?H.array:t===null?H.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?H.promise:typeof Map<"u"&&t instanceof Map?H.map:typeof Set<"u"&&t instanceof Set?H.set:typeof Date<"u"&&t instanceof Date?H.date:H.object;default:return H.unknown}}});var z,hE,St,Hi=L(()=>{ps();z=we.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"]),hE=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),St=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,we.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()}};St.create=t=>new St(t)});var mE,Cr,eu=L(()=>{Hi();ps();mE=(t,e)=>{let r;switch(t.code){case z.invalid_type:t.received===H.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case z.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,we.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:r=`Unrecognized key(s) in object: ${we.joinValues(t.keys,", ")}`;break;case z.invalid_union:r="Invalid input";break;case z.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${we.joinValues(t.options)}`;break;case z.invalid_enum_value:r=`Invalid enum value. Expected ${we.joinValues(t.options)}, received '${t.received}'`;break;case z.invalid_arguments:r="Invalid function arguments";break;case z.invalid_return_type:r="Invalid function return type";break;case z.invalid_date:r="Invalid date";break;case z.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}"`:we.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case z.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 z.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 z.custom:r="Invalid input";break;case z.invalid_intersection_types:r="Intersection results could not be merged";break;case z.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case z.not_finite:r="Number must be finite";break;default:r=e.defaultError,we.assertNever(t)}return{message:r}},Cr=mE});function fE(t){iy=t}function co(){return iy}var iy,Ki=L(()=>{eu();iy=Cr});function Z(t,e){let r=co(),n=hs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Cr?void 0:Cr].filter(o=>!!o)});t.common.issues.push(n)}var hs,gE,it,oe,vn,mt,Wi,Gi,Kr,lo,tu=L(()=>{Ki();eu();hs=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}},gE=[];it=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 oe;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 oe;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}}},oe=Object.freeze({status:"aborted"}),vn=t=>({status:"dirty",value:t}),mt=t=>({status:"valid",value:t}),Wi=t=>t.status==="aborted",Gi=t=>t.status==="dirty",Kr=t=>t.status==="valid",lo=t=>typeof Promise<"u"&&t instanceof Promise});var ay=L(()=>{});var X,cy=L(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(X||(X={}))});function de(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 py(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 OE(t){return new RegExp(`^${py(t)}$`)}function hy(t){let e=`${dy}T${py(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 NE(t,e){return!!((e==="v4"||!e)&&TE.test(t)||(e==="v6"||!e)&&EE.test(t))}function LE(t,e){if(!kE.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 jE(t,e){return!!((e==="v4"||!e)&&RE.test(t)||(e==="v6"||!e)&&PE.test(t))}function zE(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 uo(t){if(t instanceof Tt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=$t.create(uo(n))}return new Tt({...t._def,shape:()=>e})}else return t instanceof Nr?new Nr({...t._def,type:uo(t.element)}):t instanceof $t?$t.create(uo(t.unwrap())):t instanceof wr?wr.create(uo(t.unwrap())):t instanceof br?br.create(t.items.map(e=>uo(e))):t}function nu(t,e){let r=yr(t),n=yr(e);if(t===e)return{valid:!0,data:t};if(r===H.object&&n===H.object){let o=we.objectKeys(e),s=we.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=nu(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===H.array&&n===H.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=nu(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===H.date&&n===H.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function my(t,e){return new In({values:t,typeName:U.ZodEnum,...de(e)})}function uy(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function fy(t,e={},r){return t?Gr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=uy(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=uy(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Gr.create()}var qt,ly,he,yE,bE,wE,_E,vE,kE,xE,SE,$E,ru,TE,RE,EE,PE,AE,CE,dy,IE,Wr,kn,xn,Sn,$n,po,Tn,Rn,Gr,Or,rr,ho,Nr,Tt,En,Ir,Ji,Pn,br,Yi,mo,fo,Xi,An,Cn,In,On,Jr,Ft,$t,wr,Nn,Ln,go,DE,ms,fs,jn,ME,U,UE,gy,yy,qE,FE,by,BE,ZE,VE,HE,KE,WE,GE,JE,YE,ou,XE,QE,e0,t0,r0,n0,o0,s0,i0,a0,c0,l0,u0,d0,p0,h0,m0,f0,g0,y0,b0,w0,_0,v0,wy=L(()=>{Hi();Ki();cy();tu();ps();qt=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}},ly=(t,e)=>{if(Kr(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 St(t.common.issues);return this._error=r,this._error}}};he=class{get description(){return this._def.description}_getType(e){return yr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new it,ctx:{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(lo(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:yr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return ly(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Kr(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=>Kr(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:yr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(lo(o)?o:Promise.resolve(o));return ly(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:z.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 Ft({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 $t.create(this,this._def)}nullable(){return wr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Nr.create(this)}promise(){return Jr.create(this,this._def)}or(e){return En.create([this,e],this._def)}and(e){return Pn.create(this,e,this._def)}transform(e){return new Ft({...de(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Nn({...de(this._def),innerType:this,defaultValue:r,typeName:U.ZodDefault})}brand(){return new ms({typeName:U.ZodBranded,type:this,...de(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ln({...de(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 fs.create(this,e)}readonly(){return jn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},yE=/^c[^\s-]{8,}$/i,bE=/^[0-9a-z]+$/,wE=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_E=/^[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,vE=/^[a-z0-9_-]{21}$/i,kE=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,xE=/^[-+]?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)?)??$/,SE=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$E="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",TE=/^(?:(?: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])$/,RE=/^(?:(?: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])$/,EE=/^(([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]))$/,PE=/^(([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])$/,AE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,CE=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dy="((\\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])))",IE=new RegExp(`^${dy}$`);Wr=class t extends he{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==H.string){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_type,expected:H.string,received:s.parsedType}),oe}let n=new it,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?Z(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Z(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")SE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"email",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ru||(ru=new RegExp($E,"u")),ru.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"emoji",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")_E.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"uuid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")vE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"nanoid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")yE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")bE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid2",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")wE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ulid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),Z(o,{validation:"url",code:z.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"regex",code:z.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?hy(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?IE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?OE(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?xE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"duration",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?NE(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ip",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?LE(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"jwt",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?jE(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cidr",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?AE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?CE.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64url",code:z.invalid_string,message:s.message}),n.dirty()):we.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:z.invalid_string,...X.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...X.errToObj(e)})}url(e){return this._addCheck({kind:"url",...X.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...X.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...X.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...X.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...X.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...X.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...X.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...X.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...X.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...X.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...X.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...X.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,...X.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,...X.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...X.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...X.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...X.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...X.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...X.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...X.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...X.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...X.errToObj(r)})}nonempty(e){return this.min(1,X.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}};Wr.create=t=>new Wr({checks:[],typeName:U.ZodString,coerce:t?.coerce??!1,...de(t)});kn=class t extends he{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)!==H.number){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_type,expected:H.number,received:s.parsedType}),oe}let n,o=new it;for(let s of this._def.checks)s.kind==="int"?we.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:z.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?zE(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:z.not_finite,message:s.message}),o.dirty()):we.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,X.toString(r))}gt(e,r){return this.setLimit("min",e,!1,X.toString(r))}lte(e,r){return this.setLimit("max",e,!0,X.toString(r))}lt(e,r){return this.setLimit("max",e,!1,X.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:X.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:X.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:X.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.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"&&we.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)}};kn.create=t=>new kn({checks:[],typeName:U.ZodNumber,coerce:t?.coerce||!1,...de(t)});xn=class t extends he{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)!==H.bigint)return this._getInvalidInput(e);let n,o=new it;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):we.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Z(r,{code:z.invalid_type,expected:H.bigint,received:r.parsedType}),oe}gte(e,r){return this.setLimit("min",e,!0,X.toString(r))}gt(e,r){return this.setLimit("min",e,!1,X.toString(r))}lte(e,r){return this.setLimit("max",e,!0,X.toString(r))}lt(e,r){return this.setLimit("max",e,!1,X.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:X.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:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:X.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}};xn.create=t=>new xn({checks:[],typeName:U.ZodBigInt,coerce:t?.coerce??!1,...de(t)});Sn=class extends he{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==H.boolean){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.boolean,received:n.parsedType}),oe}return mt(e.data)}};Sn.create=t=>new Sn({typeName:U.ZodBoolean,coerce:t?.coerce||!1,...de(t)});$n=class t extends he{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==H.date){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_type,expected:H.date,received:s.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_date}),oe}let n=new it,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):we.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:X.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:X.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}};$n.create=t=>new $n({checks:[],coerce:t?.coerce||!1,typeName:U.ZodDate,...de(t)});po=class extends he{_parse(e){if(this._getType(e)!==H.symbol){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.symbol,received:n.parsedType}),oe}return mt(e.data)}};po.create=t=>new po({typeName:U.ZodSymbol,...de(t)});Tn=class extends he{_parse(e){if(this._getType(e)!==H.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.undefined,received:n.parsedType}),oe}return mt(e.data)}};Tn.create=t=>new Tn({typeName:U.ZodUndefined,...de(t)});Rn=class extends he{_parse(e){if(this._getType(e)!==H.null){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.null,received:n.parsedType}),oe}return mt(e.data)}};Rn.create=t=>new Rn({typeName:U.ZodNull,...de(t)});Gr=class extends he{constructor(){super(...arguments),this._any=!0}_parse(e){return mt(e.data)}};Gr.create=t=>new Gr({typeName:U.ZodAny,...de(t)});Or=class extends he{constructor(){super(...arguments),this._unknown=!0}_parse(e){return mt(e.data)}};Or.create=t=>new Or({typeName:U.ZodUnknown,...de(t)});rr=class extends he{_parse(e){let r=this._getOrReturnCtx(e);return Z(r,{code:z.invalid_type,expected:H.never,received:r.parsedType}),oe}};rr.create=t=>new rr({typeName:U.ZodNever,...de(t)});ho=class extends he{_parse(e){if(this._getType(e)!==H.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.void,received:n.parsedType}),oe}return mt(e.data)}};ho.create=t=>new ho({typeName:U.ZodVoid,...de(t)});Nr=class t extends he{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==H.array)return Z(r,{code:z.invalid_type,expected:H.array,received:r.parsedType}),oe;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(Z(r,{code:i?z.too_big:z.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(Z(r,{code:z.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(Z(r,{code:z.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 qt(r,i,r.path,a)))).then(i=>it.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new qt(r,i,r.path,a)));return it.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:X.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:X.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:X.toString(r)}})}nonempty(e){return this.min(1,e)}};Nr.create=(t,e)=>new Nr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...de(e)});Tt=class t extends he{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=we.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==H.object){let l=this._getOrReturnCtx(e);return Z(l,{code:z.invalid_type,expected:H.object,received:l.parsedType}),oe}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof rr&&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 qt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof rr){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(Z(o,{code:z.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 qt(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=>it.mergeObjectSync(n,l)):it.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return X.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:X.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 we.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 we.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return uo(this)}partial(e){let r={};for(let n of we.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 we.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof $t;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return my(we.objectKeys(this.shape))}};Tt.create=(t,e)=>new Tt({shape:()=>t,unknownKeys:"strip",catchall:rr.create(),typeName:U.ZodObject,...de(e)});Tt.strictCreate=(t,e)=>new Tt({shape:()=>t,unknownKeys:"strict",catchall:rr.create(),typeName:U.ZodObject,...de(e)});Tt.lazycreate=(t,e)=>new Tt({shape:t,unknownKeys:"strip",catchall:rr.create(),typeName:U.ZodObject,...de(e)});En=class extends he{_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 St(a.ctx.common.issues));return Z(r,{code:z.invalid_union,unionErrors:i}),oe}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 St(c));return Z(r,{code:z.invalid_union,unionErrors:a}),oe}}get options(){return this._def.options}};En.create=(t,e)=>new En({options:t,typeName:U.ZodUnion,...de(e)});Ir=t=>t instanceof An?Ir(t.schema):t instanceof Ft?Ir(t.innerType()):t instanceof Cn?[t.value]:t instanceof In?t.options:t instanceof On?we.objectValues(t.enum):t instanceof Nn?Ir(t._def.innerType):t instanceof Tn?[void 0]:t instanceof Rn?[null]:t instanceof $t?[void 0,...Ir(t.unwrap())]:t instanceof wr?[null,...Ir(t.unwrap())]:t instanceof ms||t instanceof jn?Ir(t.unwrap()):t instanceof Ln?Ir(t._def.innerType):[],Ji=class t extends he{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==H.object)return Z(r,{code:z.invalid_type,expected:H.object,received:r.parsedType}),oe;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Z(r,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),oe)}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=Ir(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,...de(n)})}};Pn=class extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Wi(s)||Wi(i))return oe;let a=nu(s.value,i.value);return a.valid?((Gi(s)||Gi(i))&&r.dirty(),{status:r.value,value:a.data}):(Z(n,{code:z.invalid_intersection_types}),oe)};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}))}};Pn.create=(t,e,r)=>new Pn({left:t,right:e,typeName:U.ZodIntersection,...de(r)});br=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.array)return Z(n,{code:z.invalid_type,expected:H.array,received:n.parsedType}),oe;if(n.data.length<this._def.items.length)return Z(n,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;!this._def.rest&&n.data.length>this._def.items.length&&(Z(n,{code:z.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 qt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>it.mergeArray(r,i)):it.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};br.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new br({items:t,typeName:U.ZodTuple,rest:null,...de(e)})};Yi=class t extends he{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!==H.object)return Z(n,{code:z.invalid_type,expected:H.object,received:n.parsedType}),oe;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new qt(n,a,n.path,a)),value:i._parse(new qt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?it.mergeObjectAsync(r,o):it.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof he?new t({keyType:e,valueType:r,typeName:U.ZodRecord,...de(n)}):new t({keyType:Wr.create(),valueType:e,typeName:U.ZodRecord,...de(r)})}},mo=class extends he{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!==H.map)return Z(n,{code:z.invalid_type,expected:H.map,received:n.parsedType}),oe;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new qt(n,a,n.path,[l,"key"])),value:s._parse(new qt(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 oe;(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 oe;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};mo.create=(t,e,r)=>new mo({valueType:e,keyType:t,typeName:U.ZodMap,...de(r)});fo=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.set)return Z(n,{code:z.invalid_type,expected:H.set,received:n.parsedType}),oe;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(Z(n,{code:z.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(Z(n,{code:z.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 oe;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 qt(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:X.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:X.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};fo.create=(t,e)=>new fo({valueType:t,minSize:null,maxSize:null,typeName:U.ZodSet,...de(e)});Xi=class t extends he{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==H.function)return Z(r,{code:z.invalid_type,expected:H.function,received:r.parsedType}),oe;function n(a,c){return hs({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,co(),Cr].filter(l=>!!l),issueData:{code:z.invalid_arguments,argumentsError:c}})}function o(a,c){return hs({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,co(),Cr].filter(l=>!!l),issueData:{code:z.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Jr){let a=this;return mt(async function(...c){let l=new St([]),u=await a._def.args.parseAsync(c,s).catch(f=>{throw l.addIssue(n(c,f)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(f=>{throw l.addIssue(o(p,f)),l})})}else{let a=this;return mt(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new St([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new St([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:br.create(e).rest(Or.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||br.create([]).rest(Or.create()),returns:r||Or.create(),typeName:U.ZodFunction,...de(n)})}},An=class extends he{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})}};An.create=(t,e)=>new An({getter:t,typeName:U.ZodLazy,...de(e)});Cn=class extends he{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Z(r,{received:r.data,code:z.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}};Cn.create=(t,e)=>new Cn({value:t,typeName:U.ZodLiteral,...de(e)});In=class t extends he{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{expected:we.joinValues(n),received:r.parsedType,code:z.invalid_type}),oe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{received:r.data,code:z.invalid_enum_value,options:n}),oe}return mt(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})}};In.create=my;On=class extends he{_parse(e){let r=we.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==H.string&&n.parsedType!==H.number){let o=we.objectValues(r);return Z(n,{expected:we.joinValues(o),received:n.parsedType,code:z.invalid_type}),oe}if(this._cache||(this._cache=new Set(we.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=we.objectValues(r);return Z(n,{received:n.data,code:z.invalid_enum_value,options:o}),oe}return mt(e.data)}get enum(){return this._def.values}};On.create=(t,e)=>new On({values:t,typeName:U.ZodNativeEnum,...de(e)});Jr=class extends he{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==H.promise&&r.common.async===!1)return Z(r,{code:z.invalid_type,expected:H.promise,received:r.parsedType}),oe;let n=r.parsedType===H.promise?r.data:Promise.resolve(r.data);return mt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Jr.create=(t,e)=>new Jr({type:t,typeName:U.ZodPromise,...de(e)});Ft=class extends he{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=>{Z(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return oe;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?oe:c.status==="dirty"?vn(c.value):r.value==="dirty"?vn(c.value):c});{if(r.value==="aborted")return oe;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?oe:a.status==="dirty"?vn(a.value):r.value==="dirty"?vn(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"?oe:(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"?oe:(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(!Kr(i))return oe;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=>Kr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):oe);we.assertNever(o)}};Ft.create=(t,e,r)=>new Ft({schema:t,typeName:U.ZodEffects,effect:e,...de(r)});Ft.createWithPreprocess=(t,e,r)=>new Ft({schema:e,effect:{type:"preprocess",transform:t},typeName:U.ZodEffects,...de(r)});$t=class extends he{_parse(e){return this._getType(e)===H.undefined?mt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$t.create=(t,e)=>new $t({innerType:t,typeName:U.ZodOptional,...de(e)});wr=class extends he{_parse(e){return this._getType(e)===H.null?mt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wr.create=(t,e)=>new wr({innerType:t,typeName:U.ZodNullable,...de(e)});Nn=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===H.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Nn.create=(t,e)=>new Nn({innerType:t,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...de(e)});Ln=class extends he{_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 lo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new St(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new St(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ln.create=(t,e)=>new Ln({innerType:t,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...de(e)});go=class extends he{_parse(e){if(this._getType(e)!==H.nan){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:H.nan,received:n.parsedType}),oe}return{status:"valid",value:e.data}}};go.create=t=>new go({typeName:U.ZodNaN,...de(t)});DE=Symbol("zod_brand"),ms=class extends he{_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}},fs=class t extends he{_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"?oe:s.status==="dirty"?(r.dirty(),vn(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"?oe: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})}},jn=class extends he{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Kr(o)&&(o.value=Object.freeze(o.value)),o);return lo(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};jn.create=(t,e)=>new jn({innerType:t,typeName:U.ZodReadonly,...de(e)});ME={object:Tt.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={}));UE=(t,e={message:`Input not instance of ${t.name}`})=>fy(r=>r instanceof t,e),gy=Wr.create,yy=kn.create,qE=go.create,FE=xn.create,by=Sn.create,BE=$n.create,ZE=po.create,VE=Tn.create,HE=Rn.create,KE=Gr.create,WE=Or.create,GE=rr.create,JE=ho.create,YE=Nr.create,ou=Tt.create,XE=Tt.strictCreate,QE=En.create,e0=Ji.create,t0=Pn.create,r0=br.create,n0=Yi.create,o0=mo.create,s0=fo.create,i0=Xi.create,a0=An.create,c0=Cn.create,l0=In.create,u0=On.create,d0=Jr.create,p0=Ft.create,h0=$t.create,m0=wr.create,f0=Ft.createWithPreprocess,g0=fs.create,y0=()=>gy().optional(),b0=()=>yy().optional(),w0=()=>by().optional(),_0={string:(t=>Wr.create({...t,coerce:!0})),number:(t=>kn.create({...t,coerce:!0})),boolean:(t=>Sn.create({...t,coerce:!0})),bigint:(t=>xn.create({...t,coerce:!0})),date:(t=>$n.create({...t,coerce:!0}))},v0=oe});var P={};ls(P,{BRAND:()=>DE,DIRTY:()=>vn,EMPTY_PATH:()=>gE,INVALID:()=>oe,NEVER:()=>v0,OK:()=>mt,ParseStatus:()=>it,Schema:()=>he,ZodAny:()=>Gr,ZodArray:()=>Nr,ZodBigInt:()=>xn,ZodBoolean:()=>Sn,ZodBranded:()=>ms,ZodCatch:()=>Ln,ZodDate:()=>$n,ZodDefault:()=>Nn,ZodDiscriminatedUnion:()=>Ji,ZodEffects:()=>Ft,ZodEnum:()=>In,ZodError:()=>St,ZodFirstPartyTypeKind:()=>U,ZodFunction:()=>Xi,ZodIntersection:()=>Pn,ZodIssueCode:()=>z,ZodLazy:()=>An,ZodLiteral:()=>Cn,ZodMap:()=>mo,ZodNaN:()=>go,ZodNativeEnum:()=>On,ZodNever:()=>rr,ZodNull:()=>Rn,ZodNullable:()=>wr,ZodNumber:()=>kn,ZodObject:()=>Tt,ZodOptional:()=>$t,ZodParsedType:()=>H,ZodPipeline:()=>fs,ZodPromise:()=>Jr,ZodReadonly:()=>jn,ZodRecord:()=>Yi,ZodSchema:()=>he,ZodSet:()=>fo,ZodString:()=>Wr,ZodSymbol:()=>po,ZodTransformer:()=>Ft,ZodTuple:()=>br,ZodType:()=>he,ZodUndefined:()=>Tn,ZodUnion:()=>En,ZodUnknown:()=>Or,ZodVoid:()=>ho,addIssueToContext:()=>Z,any:()=>KE,array:()=>YE,bigint:()=>FE,boolean:()=>by,coerce:()=>_0,custom:()=>fy,date:()=>BE,datetimeRegex:()=>hy,defaultErrorMap:()=>Cr,discriminatedUnion:()=>e0,effect:()=>p0,enum:()=>l0,function:()=>i0,getErrorMap:()=>co,getParsedType:()=>yr,instanceof:()=>UE,intersection:()=>t0,isAborted:()=>Wi,isAsync:()=>lo,isDirty:()=>Gi,isValid:()=>Kr,late:()=>ME,lazy:()=>a0,literal:()=>c0,makeIssue:()=>hs,map:()=>o0,nan:()=>qE,nativeEnum:()=>u0,never:()=>GE,null:()=>HE,nullable:()=>m0,number:()=>yy,object:()=>ou,objectUtil:()=>Ql,oboolean:()=>w0,onumber:()=>b0,optional:()=>h0,ostring:()=>y0,pipeline:()=>g0,preprocess:()=>f0,promise:()=>d0,quotelessJson:()=>hE,record:()=>n0,set:()=>s0,setErrorMap:()=>fE,strictObject:()=>XE,string:()=>gy,symbol:()=>ZE,transformer:()=>p0,tuple:()=>r0,undefined:()=>VE,union:()=>QE,unknown:()=>WE,util:()=>we,void:()=>JE});var Qi=L(()=>{Ki();tu();ay();ps();wy();Hi()});var zn=L(()=>{Qi();Qi()});function ea(t){let e=su.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function iu(t,e){let r=su.safeParse(t);if(!r.success)throw new Yr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(_y.test(e))throw new Yr('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(_y.test(n))throw new Yr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var vy,ky,su,Yr,_y,xy=L(()=>{zn();vy=P.object({type:P.literal("connection"),source_system:P.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:P.string().min(1).max(200).optional()}),ky=P.discriminatedUnion("type",[vy]),su=P.object({inputs:P.array(ky).optional()}).passthrough(),Yr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};_y=/\bconnection[_-]?id\b["']?\s*[:=]/i});var ta,au=L(()=>{ta=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var cu,Sy,$y=L(()=>{zn();ds();au();cu=P.object({id:P.string().min(1,"hook id must be non-empty"),recordType:P.union([P.string().min(1),P.array(P.string().min(1)).min(1),P.literal("*")]),event:P.enum(ta),source:P.string().min(1).optional(),when:P.unknown().optional(),run:P.unknown(),failClosed:P.boolean().optional(),timeoutMs:P.number().int().positive().optional(),description:P.string().optional(),systemReserved:P.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"})}),Sy=_n({kind:"hook",schema:cu,factoryName:"defineHook"})});var Ty=L(()=>{$y();au()});var yo,lu=L(()=>{yo=["after_canonicalize_inbound","after_sync_success_outbound","after_save","after_delete"]});var Ry,S0,Ey,uu,Py,Ay=L(()=>{zn();ds();lu();Ry=P.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),S0=P.object({recordType:P.string().min(1,"reads[].recordType must be non-empty"),source:P.string().min(1).optional(),columns:P.array(Ry).min(1,"reads[].columns must name at least one column"),by:P.array(Ry).optional(),maxRows:P.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),Ey=P.object({source:P.string().min(1,"to.source must be non-empty"),recordType:P.string().min(1,"to.recordType must be non-empty"),process:P.string().min(1,"to.process must be non-empty when present").optional()}),uu=P.object({id:P.string().min(1,"conduit id must be non-empty"),on:P.enum(yo),from:P.object({source:P.string().min(1,"from.source must be non-empty"),recordType:P.string().min(1,"from.recordType must be non-empty"),when:P.unknown().optional()}),to:Ey.optional(),mode:P.enum(["dual-bind","one-shot"]).optional(),transform:P.unknown().optional(),sequence:P.array(P.object({to:Ey,transform:P.unknown(),awaitSource:P.boolean().optional()})).optional(),reads:P.array(S0).optional(),maxQueriesPerRun:P.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:P.unknown().optional(),cycleBudget:P.number().int().positive().optional(),conflictStrategy:P.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:P.number().int().positive().optional(),description:P.string().optional(),systemReserved:P.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((l,u)=>{typeof l.transform!="function"&&e.addIssue({code:"custom",path:["sequence",u,"transform"],message:"transform must be a function"}),r.from?.source&&l.to?.source&&r.from.source===l.to.source&&e.addIssue({code:"custom",path:["sequence",u,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,c=r.to;a?.source&&c?.source&&a.source===c.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"})}),Py=_n({kind:"conduit",schema:uu,factoryName:"defineConduit"})});var Cy=L(()=>{Ay();lu()});function Oy(t,e,r){let n=e;if((typeof n.recordType!="string"||n.recordType.length===0)&&t.addIssue({code:"custom",path:[...r,"recordType"],message:"step.recordType must be non-empty"}),n.when!==void 0&&typeof n.when!="function"&&t.addIssue({code:"custom",path:[...r,"when"],message:"when must be a function returning whether this step runs"}),n.delete!==void 0){O0(t,n,r);return}n.onRefused!==void 0&&t.addIssue({code:"custom",path:[...r,"onRefused"],message:"onRefused is only honoured on a delete step \u2014 a refused write always ends the run. Remove it, or declare a `delete` block to make this a delete step"}),typeof n.build!="function"&&t.addIssue({code:"custom",path:[...r,"build"],message:"build must be a function"});let o=n.update;if(o){for(let s of["pgRowId","externalId","expectedSyncVersion"]){let i=o[s];i!==void 0&&typeof i!="function"&&t.addIssue({code:"custom",path:[...r,"update",s],message:`update.${s} must be a function of the step context \u2014 a declaration cannot know the value until the run`})}o.step===void 0&&o.pgRowId===void 0&&o.externalId===void 0&&t.addIssue({code:"custom",path:[...r,"update"],message:"update must address a record: one of `step`, `pgRowId` or `externalId`"})}}function O0(t,e,r){e.build!==void 0&&t.addIssue({code:"custom",path:[...r,"build"],message:"a delete step has nothing to build \u2014 remove `build`, or remove `delete` to make this a write step"}),e.rollback==="undo"&&t.addIssue({code:"custom",path:[...r,"rollback"],message:"a delete cannot be undone, so a delete step is always rollback: 'keep'"});let n=e.delete??{};for(let o of["pgRowId","externalId"]){let s=n[o];s!==void 0&&typeof s!="function"&&t.addIssue({code:"custom",path:[...r,"delete",o],message:`delete.${o} must be a function of the step context \u2014 a declaration cannot know the value until the run`})}n.pgRowId===void 0&&n.externalId===void 0&&t.addIssue({code:"custom",path:[...r,"delete"],message:"delete must address a record: one of `pgRowId` or `externalId`"})}function N0(t,e,r){e.forEach===void 0&&t.addIssue({code:"custom",path:["steps",r,"forEach"],message:"a step-list entry carrying nested steps must declare forEach.input, naming the input property to repeat over"});let n=e.steps;if(!Array.isArray(n)||n.length===0){t.addIssue({code:"custom",path:["steps",r,"steps"],message:"a repeated group needs at least one step in it, or it writes nothing at all"});return}let o=new Map;n.forEach((s,i)=>{Oy(t,s,["steps",r,"steps",i]);let a=s.id;if(typeof a!="string")return;let c=o.get(a);c!==void 0?t.addIssue({code:"custom",path:["steps",r,"steps"],message:`duplicate step id '${a}' (steps ${c} and ${i}) \u2014 step ids must be unique within a repeated group`}):o.set(a,i)})}var Iy,C0,I0,du,Ny,Ly=L(()=>{zn();ds();Iy={id:P.string().min(1,"step id must be non-empty"),recordType:P.string().min(1,"step.recordType must be non-empty").optional(),awaitSource:P.boolean().optional(),update:P.object({step:P.string().min(1,"update.step must name an earlier step").optional(),pgRowId:P.unknown().optional(),externalId:P.unknown().optional(),expectedSyncVersion:P.unknown().optional()}).optional(),when:P.unknown().optional(),rollback:P.enum(["undo","keep"]).optional(),onRefused:P.enum(["continue","stop"]).optional(),delete:P.object({pgRowId:P.unknown().optional(),externalId:P.unknown().optional(),sourceSystem:P.string().min(1,"delete.sourceSystem must name a connected system").optional()}).optional(),build:P.unknown(),description:P.string().optional()},C0=P.object(Iy),I0=P.object({...Iy,forEach:P.object({input:P.string().min(1,"forEach.input must name a property of the process input holding the array to repeat over")}).optional(),steps:P.array(C0).optional()}),du=P.object({id:P.string().min(1,"process id must be non-empty"),input:P.object({type:P.literal("object"),properties:P.record(P.unknown()).optional(),required:P.array(P.string()).optional()}).passthrough(),steps:P.array(I0).min(1,"a process needs at least one step"),eachRow:P.object({outstanding:P.unknown(),key:P.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:P.enum(["stop","rollback"]).optional(),description:P.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(a.forEach!==void 0||a.steps!==void 0?N0(e,a,i):Oy(e,s,["steps",i]),typeof a.id=="string"){let c=o.get(a.id);c!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${c} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})});Ny=_n({kind:"process",schema:du,factoryName:"defineProcess"})});var jy=L(()=>{});var zy=L(()=>{Ly();jy()});async function M0(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 oa(t,e={}){return(e.transform??M0)(t)}var pu=L(()=>{});function sa(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 bo(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function ia(t){return`${bo(t.source)}${bo(t.recordType)}`}function Dy(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function My(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.currencyKey&&e.push(`currency from ${t.currencyKey}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function hu(t){let e=ia(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=sa(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${Dy(s)} */
32
- ${zy(s.name)}${a}: ${i}${c};`});return`${n}
31
+ }`;let o=t.columns.map(s=>{let i=sa(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${My(s)} */
32
+ ${Dy(s.name)}${a}: ${i}${c};`});return`${n}
33
33
  export interface ${e} {
34
34
  ${o.join(`
35
35
  `)}
36
- }`}function My(t){return t.connected!==!1}function M0(t,e){let r=`${wo(t.source)}${wo(e.table)}`,n=`/** ${t.source}:${t.recordType} lines \u2192 turbobase.${e.table}. */`;if(e.columns.length===0)return`${n}
36
+ }`}function Uy(t){return t.connected!==!1}function U0(t,e){let r=`${bo(t.source)}${bo(e.table)}`,n=`/** ${t.source}:${t.recordType} lines \u2192 turbobase.${e.table}. */`;if(e.columns.length===0)return`${n}
37
37
  export interface ${r} {
38
38
  // no columns introspected
39
39
  [key: string]: unknown;
40
- }`;let o=e.columns.map(s=>{let i=sa(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${Dy(s)} */
41
- ${zy(s.name)}${a}: ${i}${c};`});return`${n}
40
+ }`;let o=e.columns.map(s=>{let i=sa(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${My(s)} */
41
+ ${Dy(s.name)}${a}: ${i}${c};`});return`${n}
42
42
  export interface ${r} {
43
43
  ${o.join(`
44
44
  `)}
45
- }`}function aa(t){let e=[...t.records].filter(My).sort((o,s)=>`${o.source}:${o.recordType}`.localeCompare(`${s.source}:${s.recordType}`)),r=new Set,n=[];for(let o of e){let s=ia(o);r.has(s)||(r.add(s),n.push(pu(o)));for(let i of o.lines??[]){let a=`${wo(o.source)}${wo(i.table)}`;r.has(a)||(r.add(a),n.push(M0(o,i)))}}return n.join(`
45
+ }`}function aa(t){let e=[...t.records].filter(Uy).sort((o,s)=>`${o.source}:${o.recordType}`.localeCompare(`${s.source}:${s.recordType}`)),r=new Set,n=[];for(let o of e){let s=ia(o);r.has(s)||(r.add(s),n.push(hu(o)));for(let i of o.lines??[]){let a=`${bo(o.source)}${bo(i.table)}`;r.has(a)||(r.add(a),n.push(U0(o,i)))}}return n.join(`
46
46
 
47
- `)}function Uy(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.filter(My)){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 U0(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function hu(t){let e=Uy(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` ${U0(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(`
48
- `)}var mu=L(()=>{});function q0(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function qy(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 Dn(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=q0(t.baseUrl),n=await qy(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=aa(n),s=[F0,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",hu(n)];if(!t.recordsOnly){let i=await qy(r.openapi,t.token,e),a=await oa(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
47
+ `)}function qy(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.filter(Uy)){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 q0(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function mu(t){let e=qy(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` ${q0(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(`
48
+ `)}var fu=L(()=>{});function F0(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function Fy(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 Dn(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=F0(t.baseUrl),n=await Fy(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=aa(n),s=[B0,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",mu(n)];if(!t.recordsOnly){let i=await Fy(r.openapi,t.token,e),a=await oa(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
49
49
 
50
50
  `)+`
51
- `}var F0,Fy=L(()=>{du();mu();mu();du();F0=["/**"," * 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(`
52
- `)});var fu=L(()=>{ds();xy();$y();Ay();jy();Fy()});import{homedir as B0}from"node:os";import{join as By}from"node:path";import{promises as gu}from"node:fs";function Bt(t){return t.trim().replace(/\/+$/,"")}function ca(){let t=process.env.TURBOBASE_HOME??By(B0(),".turbobase");return{dir:t,file:By(t,"credentials")}}function Zy(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function gs(){let{file:t}=ca(),e;try{let s=await gu.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))Zy(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))Zy(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:Z0(n),tenants:n}}function Z0(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 yu(t){let{dir:e,file:r}=ca();await gu.mkdir(e,{recursive:!0,mode:448}),await gu.writeFile(r,JSON.stringify(t,null,2)+`
53
- `,{mode:384})}async function Vy(t){let e=Bt(t.baseUrl),r=await gs(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await yu(r),{baseUrl:e,token:t.token,updatedAt:n}}async function nr(t){let e=await gs();if(t){let s=Bt(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 la(t){let e=Bt(t),r=await gs(),n=r.tenants[e];return n?(r.active=e,await yu(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function bu(t){let e=await gs(),r=t?Bt(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 yu(e),r}async function Lr(){let t=await gs();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var ys=L(()=>{});function _u(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function V0(t){if(t)try{return JSON.parse(t)}catch{return t}}function H0(t,e){if(!t)return null;let r=t.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-e)}function K0(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function W0(t,e){let r=H0(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=V0(n),s=_u(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??K0(n),error:i}}function G0(t){return!!(t==null||typeof t=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)||t instanceof ArrayBuffer||typeof URLSearchParams<"u"&&t instanceof URLSearchParams||typeof Blob<"u"&&t instanceof Blob)}function Hy(t){try{let e=typeof t=="string"?t:t instanceof URL?t.href:t?.url??"";return e?new URL(e).host:"the instance"}catch{return"the instance"}}function wu(t){return`${Math.round(t/1e3)}s`}function J0(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${wu(t.delayMs)} before retrying (${wu(t.remainingMs)} of the retry budget left).
54
- `)}function Y0(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${wu(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
55
- `)}function ua(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(l=>new Promise(u=>setTimeout(u,l))),s=e.now??(()=>Date.now()),i=e.onWait??J0,a=e.onGiveUp??Y0;return async(l,u)=>{let p=s(),w=0;for(;;){let f=await t(l,u);if(f.status!==503||u&&!G0(u.body))return f;let m=r-(s()-p),{maintenance:b,delayMs:$,error:R}=await W0(f,s());if(!b)return f;if(m<=0)return w>0&&a({waitedMs:s()-p,attempts:w,host:Hy(l),error:R}),f;let A=$??n;A=Math.min(Math.max(A,1e3),12e4),A=Math.min(A,m),w+=1,i({attempt:w,delayMs:A,remainingMs:m,host:Hy(l),error:R}),await o(A)}}}var vu=L(()=>{});function Ky(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t;if(typeof e.message=="string"&&e.message.trim())return e.message.trim();let r=typeof e.error=="string"?e.error.trim():"",n=typeof e.reason=="string"?e.reason.trim():"";return n?r?`${r}: ${n}`:n:r}function X0(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function eP(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.error=="string"&&typeof e.reason=="string"&&e.reason.trim()!==""}function Wy(t){let e=Ky(t);return typeof t=="string"&&X0(e)?Q0:eP(t)?e.slice(0,rP):e.slice(0,tP)}function Gy(t,e){return _u(t,e)}function Jy(t){return t instanceof se&&Gy(t.status,t.body)}function oP(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Yy(t){return t.replace(/\/+$/,"")}function xu(t=process.env){let e=(t[_o]??"").trim(),r=(t[da]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function ku(t){let e;try{e=new URL(t)}catch{return`${_o} 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:`${_o} 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 se,Q0,tP,rP,nP,K,_o,da,bs,or=L(()=>{vu();se=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};Q0="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";tP=200,rP=2e3;nP="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";K=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Yy(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=e.retry===!1?r:ua(r,e.retry??{})}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){if(oP()){let l=Ky(a);throw new se(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}if(Gy(s.status,a))throw new se(nP,s.status,a);let c=Wy(a);throw new se(`${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"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}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}:{})}extensionDisable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/disable`,{})}extensionEnable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/enable`,{})}extensionRemove(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/remove`,{})}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 processes(){return(await this.request("GET","/v1/processes")).processes??[]}async processRuns(e){return(await this.request("GET",`/v1/processes/${encodeURIComponent(e)}/runs`)).runs??[]}async processRun(e){return this.request("GET",`/v1/processes/runs/${encodeURIComponent(e)}`)}async invokeProcess(e,r,n="async"){let o=n==="sync"?"?mode=sync":"";return this.request("POST",`/v1/processes/${encodeURIComponent(e)}${o}`,r)}async settleRow(e,r){return this.request("POST",`/v1/data/${encodeURIComponent(e)}/settle`,{pgRowId:r})}async cancelProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/cancel`)}async rollbackProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/rollback`)}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}`:""}`)}appSkillsPush(e,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...r],dryRun: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??[],...e.roles!==void 0?{roles:e.roles}:{},labels:e.labels??[],...e.app?{app:e.app}:{}})}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})}async relationshipsList(e){let r=e?`?source=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/relationships${r}`)).relations??[]}relationshipRefresh(e,r){return this.request("PATCH",`/v1/relationships/${encodeURIComponent(e)}`,r)}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`)}},_o="TURBOBASE_REGISTRY_URL",da="TURBOBASE_REGISTRY_TOKEN";bs=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Yy(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=Wy(a);throw new se(`${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}:{}})}}});import{existsSync as sP,statSync as iP}from"node:fs";import{resolve as pa,sep as Xy}from"node:path";function Qy(t){if(cP.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function uP(t,e,r){let n=pa(e,r),o=pa(t);if(n!==o&&!n.startsWith(o+Xy))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+Xy)&&sP(i)&&iP(i).isFile())return i;return null}function eb(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Qy(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=uP(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||pP(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:lP,loader:"js"}))}}}function pP(t){let e=t.startsWith("node:")?t.slice(5):t;return dP.has(e.split("/")[0])}function tb(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 rb(){try{return(await import("esbuild")).build}catch(t){throw tb("esbuild",t)}}async function hP(){try{return(await import("isolated-vm")).default}catch(t){throw tb("isolated-vm",t)}}async function fa(t,e={}){let r=await rb(),n=e.resolveDir?pa(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[eb(n)]})}catch(s){let a=s.errors?.map(c=>c.text).filter(Boolean).join("; ");throw new ha(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function Su(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await rb(),n=pa(e),o=eb(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},c=>c.kind==="entry-point"?null:Qy(c.path)?{path:c.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let l=a.errors?.map(u=>u.text).filter(Boolean).join("; ");throw new ha(l||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function ws(t,e,r={}){let n=r.timeoutMs??ma,o=r.memoryLimitMb??aP,s=r.member??"run",i={patches:[],logs:[]},a=await hP(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,p=new a.Callback(q=>{let Y=JSON.parse(String(q));i.rejection||(i.rejection=Y)}),w=new a.Callback(q=>{i.patches.push(JSON.parse(String(q)))}),f=new a.Callback(q=>{let Y=JSON.parse(String(q));i.logs.push(Y)}),m=new a.Callback(q=>{i.result=JSON.parse(String(q))}),b=r.query,$=new a.Reference(async q=>{if(!b)throw new Error("ctx.query is not available in this context");return JSON.stringify(await b(String(q)))});await u.set("__tb_reject",p),await u.set("__tb_patch",w),await u.set("__tb_log",f),await u.set("__tb_result",m),await u.set("__tb_query",$),await u.set("__tb_ctx_json",JSON.stringify(mP(e)));let R=gP(t,s,r.stepIndex??0,r.stepPath??[r.stepIndex??0],!!r.query),O=await(await c.compileScript(R)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!O}:{effects:i}}finally{c.isDisposed||c.dispose()}}function mP(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,materialized:t.materialized??null,process:t.process??null}}function fP(t){return`
51
+ `}var B0,By=L(()=>{pu();fu();fu();pu();B0=["/**"," * 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(`
52
+ `)});var gu=L(()=>{ds();xy();Ty();Cy();zy();By()});import{homedir as Z0}from"node:os";import{join as Zy}from"node:path";import{promises as yu}from"node:fs";function Bt(t){return t.trim().replace(/\/+$/,"")}function ca(){let t=process.env.TURBOBASE_HOME??Zy(Z0(),".turbobase");return{dir:t,file:Zy(t,"credentials")}}function Vy(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function gs(){let{file:t}=ca(),e;try{let s=await yu.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))Vy(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))Vy(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:V0(n),tenants:n}}function V0(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 bu(t){let{dir:e,file:r}=ca();await yu.mkdir(e,{recursive:!0,mode:448}),await yu.writeFile(r,JSON.stringify(t,null,2)+`
53
+ `,{mode:384})}async function Hy(t){let e=Bt(t.baseUrl),r=await gs(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await bu(r),{baseUrl:e,token:t.token,updatedAt:n}}async function nr(t){let e=await gs();if(t){let s=Bt(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 la(t){let e=Bt(t),r=await gs(),n=r.tenants[e];return n?(r.active=e,await bu(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function wu(t){let e=await gs(),r=t?Bt(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 bu(e),r}async function Lr(){let t=await gs();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var ys=L(()=>{});function vu(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function H0(t){if(t)try{return JSON.parse(t)}catch{return t}}function K0(t,e){if(!t)return null;let r=t.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-e)}function W0(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function G0(t,e){let r=K0(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=H0(n),s=vu(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??W0(n),error:i}}function J0(t){return!!(t==null||typeof t=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)||t instanceof ArrayBuffer||typeof URLSearchParams<"u"&&t instanceof URLSearchParams||typeof Blob<"u"&&t instanceof Blob)}function Ky(t){try{let e=typeof t=="string"?t:t instanceof URL?t.href:t?.url??"";return e?new URL(e).host:"the instance"}catch{return"the instance"}}function _u(t){return`${Math.round(t/1e3)}s`}function Y0(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${_u(t.delayMs)} before retrying (${_u(t.remainingMs)} of the retry budget left).
54
+ `)}function X0(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${_u(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
55
+ `)}function ua(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(l=>new Promise(u=>setTimeout(u,l))),s=e.now??(()=>Date.now()),i=e.onWait??Y0,a=e.onGiveUp??X0;return async(l,u)=>{let p=s(),w=0;for(;;){let f=await t(l,u);if(f.status!==503||u&&!J0(u.body))return f;let m=r-(s()-p),{maintenance:b,delayMs:$,error:R}=await G0(f,s());if(!b)return f;if(m<=0)return w>0&&a({waitedMs:s()-p,attempts:w,host:Ky(l),error:R}),f;let A=$??n;A=Math.min(Math.max(A,1e3),12e4),A=Math.min(A,m),w+=1,i({attempt:w,delayMs:A,remainingMs:m,host:Ky(l),error:R}),await o(A)}}}var ku=L(()=>{});function Wy(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t;if(typeof e.message=="string"&&e.message.trim())return e.message.trim();let r=typeof e.error=="string"?e.error.trim():"",n=typeof e.reason=="string"?e.reason.trim():"";return n?r?`${r}: ${n}`:n:r}function Q0(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function tP(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.error=="string"&&typeof e.reason=="string"&&e.reason.trim()!==""}function Gy(t){let e=Wy(t);return typeof t=="string"&&Q0(e)?eP:tP(t)?e.slice(0,nP):e.slice(0,rP)}function Jy(t,e){return vu(t,e)}function Yy(t){return t instanceof se&&Jy(t.status,t.body)}function sP(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Xy(t){return t.replace(/\/+$/,"")}function xu(t=process.env){let e=(t[wo]??"").trim(),r=(t[da]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function Su(t){let e;try{e=new URL(t)}catch{return`${wo} 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:`${wo} 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 se,eP,rP,nP,oP,K,wo,da,bs,or=L(()=>{ku();se=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};eP="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";rP=200,nP=2e3;oP="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";K=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Xy(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=e.retry===!1?r:ua(r,e.retry??{})}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){if(sP()){let l=Wy(a);throw new se(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}if(Jy(s.status,a))throw new se(oP,s.status,a);let c=Gy(a);throw new se(`${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"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}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}:{})}extensionDisable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/disable`,{})}extensionEnable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/enable`,{})}extensionRemove(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/remove`,{})}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 processes(){return(await this.request("GET","/v1/processes")).processes??[]}async processRuns(e){return(await this.request("GET",`/v1/processes/${encodeURIComponent(e)}/runs`)).runs??[]}async processRun(e){return this.request("GET",`/v1/processes/runs/${encodeURIComponent(e)}`)}async invokeProcess(e,r,n="async"){let o=n==="sync"?"?mode=sync":"";return this.request("POST",`/v1/processes/${encodeURIComponent(e)}${o}`,r)}async settleRow(e,r){return this.request("POST",`/v1/data/${encodeURIComponent(e)}/settle`,{pgRowId:r})}async cancelProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/cancel`)}async rollbackProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/rollback`)}async resumeProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/resume`)}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}`:""}`)}appSkillsPush(e,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...r],dryRun: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??[],...e.roles!==void 0?{roles:e.roles}:{},labels:e.labels??[],...e.app?{app:e.app}:{}})}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})}async relationshipsList(e){let r=e?`?source=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/relationships${r}`)).relations??[]}relationshipRefresh(e,r){return this.request("PATCH",`/v1/relationships/${encodeURIComponent(e)}`,r)}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`)}},wo="TURBOBASE_REGISTRY_URL",da="TURBOBASE_REGISTRY_TOKEN";bs=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Xy(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=Gy(a);throw new se(`${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}:{}})}}});import{existsSync as iP,statSync as aP}from"node:fs";import{resolve as pa,sep as Qy}from"node:path";function eb(t){if(lP.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function dP(t,e,r){let n=pa(e,r),o=pa(t);if(n!==o&&!n.startsWith(o+Qy))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+Qy)&&iP(i)&&aP(i).isFile())return i;return null}function tb(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(eb(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=dP(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||hP(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:uP,loader:"js"}))}}}function hP(t){let e=t.startsWith("node:")?t.slice(5):t;return pP.has(e.split("/")[0])}function rb(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 nb(){try{return(await import("esbuild")).build}catch(t){throw rb("esbuild",t)}}async function mP(){try{return(await import("isolated-vm")).default}catch(t){throw rb("isolated-vm",t)}}async function fa(t,e={}){let r=await nb(),n=e.resolveDir?pa(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[tb(n)]})}catch(s){let a=s.errors?.map(c=>c.text).filter(Boolean).join("; ");throw new ha(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function $u(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await nb(),n=pa(e),o=tb(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},c=>c.kind==="entry-point"?null:eb(c.path)?{path:c.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let l=a.errors?.map(u=>u.text).filter(Boolean).join("; ");throw new ha(l||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function ws(t,e,r={}){let n=r.timeoutMs??ma,o=r.memoryLimitMb??cP,s=r.member??"run",i={patches:[],logs:[]},a=await mP(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,p=new a.Callback(q=>{let J=JSON.parse(String(q));i.rejection||(i.rejection=J)}),w=new a.Callback(q=>{i.patches.push(JSON.parse(String(q)))}),f=new a.Callback(q=>{let J=JSON.parse(String(q));i.logs.push(J)}),m=new a.Callback(q=>{i.result=JSON.parse(String(q))}),b=r.query,$=new a.Reference(async q=>{if(!b)throw new Error("ctx.query is not available in this context");return JSON.stringify(await b(String(q)))});await u.set("__tb_reject",p),await u.set("__tb_patch",w),await u.set("__tb_log",f),await u.set("__tb_result",m),await u.set("__tb_query",$),await u.set("__tb_ctx_json",JSON.stringify(fP(e)));let R=yP(t,s,r.stepIndex??0,r.stepPath??[r.stepIndex??0],!!r.query),O=await(await c.compileScript(R)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!O}:{effects:i}}finally{c.isDisposed||c.dispose()}}function fP(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,materialized:t.materialized??null,process:t.process??null}}function gP(t){return`
56
56
  "use strict";
57
57
  (async () => {
58
58
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -75,7 +75,7 @@ ${o.join(`
75
75
  __tb_result(JSON.stringify(out == null ? null : String(out)));
76
76
  return undefined;
77
77
  })()
78
- `}function gP(t,e,r,n,o=!1){return e==="build"?bP(t,n):e==="delete"?wP(t,n):e==="prompt"?yP(t,n):e==="outstanding"?fP(t):`
78
+ `}function yP(t,e,r,n,o=!1){return e==="build"?wP(t,n):e==="delete"?_P(t,n):e==="prompt"?bP(t,n):e==="outstanding"?gP(t):`
79
79
  "use strict";
80
80
  (async () => {
81
81
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -163,7 +163,7 @@ ${o.join(`
163
163
  ${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":e==="idempotencyKey"?"__tb_result(JSON.stringify(out == null ? null : String(out)));":""}
164
164
  return ${e==="when"?"out":"undefined"};
165
165
  })()
166
- `}function yP(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
166
+ `}function bP(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
167
167
  "use strict";
168
168
  (async () => {
169
169
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -208,7 +208,7 @@ ${o.join(`
208
208
  __tb_result(String(out == null ? '' : out));
209
209
  return undefined;
210
210
  })()
211
- `}function bP(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
211
+ `}function wP(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
212
212
  "use strict";
213
213
  (async () => {
214
214
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -279,7 +279,7 @@ ${o.join(`
279
279
  __tb_result(JSON.stringify({ declined: out == null, address: address, write: out == null ? null : out }));
280
280
  return undefined;
281
281
  })()
282
- `}function wP(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
282
+ `}function _P(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
283
283
  "use strict";
284
284
  (async () => {
285
285
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -338,12 +338,12 @@ ${o.join(`
338
338
  __tb_result(JSON.stringify({ declined: false, address: address }));
339
339
  return undefined;
340
340
  })()
341
- `}var ma,aP,cP,lP,ha,dP,ga=L(()=>{ma=200,aP=16,cP=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@/sync/processes","@/sync/processes/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit","@turbobase/extensions/process"]);lP=`
341
+ `}var ma,cP,lP,uP,ha,pP,ga=L(()=>{ma=200,cP=16,lP=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@/sync/processes","@/sync/processes/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit","@turbobase/extensions/process"]);uP=`
342
342
  export const defineHook = (def) => def;
343
343
  export const defineConduit = (def) => def;
344
344
  export const defineProcess = (def) => def;
345
345
  export default defineHook;
346
- `;ha=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};dP=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 $u}from"node:fs";import{join as _P}from"node:path";function vP(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 xP(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await ws(t,vP(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 ya(t,e,r={}){let n=await fa(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await xP(n,e[s],`sample[${s}]`));return o}async function _s(t){let e;try{e=await $u.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 $u.readFile(_P(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 vs(t){return $u.readFile(t,"utf8")}var Tu=L(()=>{ga()});function Et(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function yA(t){let e=t.recordType;if(!e)throw new Pt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
346
+ `;ha=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};pP=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 Tu}from"node:fs";import{join as vP}from"node:path";function kP(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 xP(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await ws(t,kP(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 ya(t,e,r={}){let n=await fa(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await xP(n,e[s],`sample[${s}]`));return o}async function _s(t){let e;try{e=await Tu.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 Tu.readFile(vP(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 vs(t){return Tu.readFile(t,"utf8")}var Ru=L(()=>{ga()});function Et(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function bA(t){let e=t.recordType;if(!e)throw new Pt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
347
347
  source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
348
348
  run: (ctx) => {
349
349
  // Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
@@ -381,7 +381,7 @@ export default defineHook<Record<string, unknown>>({
381
381
  recordType: ${JSON.stringify(e)},
382
382
  event: ${JSON.stringify(r)},${s}${i}
383
383
  });
384
- `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function bA(t){let e=t.recordType;if(!e)throw new Pt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Pt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Pt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Pt(`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??`${Et(r)}2${Et(n)}:${Et(e)}`,c=`/**
384
+ `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function wA(t){let e=t.recordType;if(!e)throw new Pt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Pt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Pt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Pt(`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??`${Et(r)}2${Et(n)}:${Et(e)}`,c=`/**
385
385
  * ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
386
386
  *
387
387
  * Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
@@ -424,7 +424,7 @@ export default defineConduit<Record<string, unknown>>({
424
424
  },
425
425
  idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
426
426
  });
427
- `;return{relativePath:`conduits/${Et(r)}-${Et(e)}-to-${Et(n)}-${Et(o)}.ts`,content:c}}function wA(t){let e=t.recordType;if(!e)throw new Pt("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Pt(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${Et(e)}-then-${Et(r)}`:Et(e),s=t.id??`custom:process:${o}`,i=t.description??(r?`Raise a ${e}, wait for the source, then raise a ${r}.`:`Raise a ${e}.`),a=r?`
427
+ `;return{relativePath:`conduits/${Et(r)}-${Et(e)}-to-${Et(n)}-${Et(o)}.ts`,content:c}}function _A(t){let e=t.recordType;if(!e)throw new Pt("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Pt(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${Et(e)}-then-${Et(r)}`:Et(e),s=t.id??`custom:process:${o}`,i=t.description??(r?`Raise a ${e}, wait for the source, then raise a ${r}.`:`Raise a ${e}.`),a=r?`
428
428
  {
429
429
  id: ${JSON.stringify(Et(r))},
430
430
  recordType: ${JSON.stringify(r)},
@@ -477,7 +477,7 @@ export default defineProcess({
477
477
  ],
478
478
  onFailure: ${JSON.stringify(n)},
479
479
  });
480
- `;return{relativePath:`processes/${o}.ts`,content:c}}function _r(t,e){let r=_A[t];if(!r)throw new Pt(`unknown extension kind '${t}'. Scaffoldable kinds: ${Mb.join(", ")}.`);return r(e)}var Mb,Pt,_A,ka=L(()=>{Mb=["hook","conduit","process"];Pt=class extends Error{};_A={hook:yA,conduit:bA,process:wA}});var Xu,Qu=L(()=>{Xu=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function KI(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 WI(t){return __[KI(t)%__.length]}function GI(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 v_(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function x_(t,e){let[r,n]=WI(t),o=v_(GI(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${v_(e)}">
480
+ `;return{relativePath:`processes/${o}.ts`,content:c}}function _r(t,e){let r=vA[t];if(!r)throw new Pt(`unknown extension kind '${t}'. Scaffoldable kinds: ${Ub.join(", ")}.`);return r(e)}var Ub,Pt,vA,xa=L(()=>{Ub=["hook","conduit","process"];Pt=class extends Error{};vA={hook:bA,conduit:wA,process:_A}});var Qu,ed=L(()=>{Qu=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function WI(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 GI(t){return v_[WI(t)%v_.length]}function JI(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 k_(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function x_(t,e){let[r,n]=GI(t),o=k_(JI(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${k_(e)}">
481
481
  <defs>
482
482
  <linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
483
483
  <stop offset="0" stop-color="${r}"/>
@@ -487,9 +487,9 @@ export default defineProcess({
487
487
  <rect width="64" height="64" rx="14" fill="url(#tile)"/>
488
488
  <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>
489
489
  </svg>
490
- `}var __,k_=L(()=>{__=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Z_={};ls(Z_,{CN_UTIL:()=>N_,CODE_STANDARDS:()=>ir,CODE_STANDARDS_BASELINE:()=>P_,CODE_STANDARDS_JSON:()=>R_,COMPONENTS_JSON:()=>O_,KNIP_JSON:()=>E_,MAIN_TSX:()=>j_,OXFMT_CONFIG:()=>T_,OXLINTRC_JSON:()=>$_,STYLES_CSS:()=>z_,TSCONFIG:()=>I_,TURBOBASE_CLIENT:()=>S_,UI_BADGE:()=>U_,UI_BUTTON:()=>D_,UI_CARD:()=>M_,UI_INPUT:()=>F_,UI_LABEL:()=>B_,UI_TABLE:()=>q_,indexHtml:()=>L_,instanceOriginFromEnv:()=>oO,packageJson:()=>A_,scaffoldAppFiles:()=>iO,starterApp:()=>aO,viteConfig:()=>C_});function XI(t,e){let r=t.trim();if(r.length<=e)return r;let n=r.slice(0,e);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function QI(t){let e={name:XI(t.title,YI)},r=(t.description??"").trim().slice(0,JI);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Xu},JSON.stringify(e,null,2)+`
491
- `}function A_(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:eO,check:`${ir.bin} check`,fix:`${ir.bin} fix`},dependencies:{react:"^19.2.0","react-dom":"^19.2.0","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":"^19.2.0","@types/react-dom":"^19.2.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",[ir.pkg]:ir.range}},null,2)}
492
- `}function nO(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 oO(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function C_(t,e={}){let r=nO(e.instanceOrigin);return`import { defineConfig } from 'vite';
490
+ `}var v_,S_=L(()=>{v_=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var V_={};ls(V_,{CN_UTIL:()=>L_,CODE_STANDARDS:()=>ir,CODE_STANDARDS_BASELINE:()=>A_,CODE_STANDARDS_JSON:()=>E_,COMPONENTS_JSON:()=>N_,KNIP_JSON:()=>P_,MAIN_TSX:()=>z_,OXFMT_CONFIG:()=>R_,OXLINTRC_JSON:()=>T_,STYLES_CSS:()=>D_,TSCONFIG:()=>O_,TURBOBASE_CLIENT:()=>$_,UI_BADGE:()=>q_,UI_BUTTON:()=>M_,UI_CARD:()=>U_,UI_INPUT:()=>B_,UI_LABEL:()=>Z_,UI_TABLE:()=>F_,indexHtml:()=>j_,instanceOriginFromEnv:()=>sO,packageJson:()=>C_,scaffoldAppFiles:()=>aO,starterApp:()=>cO,viteConfig:()=>I_});function QI(t,e){let r=t.trim();if(r.length<=e)return r;let n=r.slice(0,e);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function eO(t){let e={name:QI(t.title,XI)},r=(t.description??"").trim().slice(0,YI);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Qu},JSON.stringify(e,null,2)+`
491
+ `}function C_(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:tO,check:`${ir.bin} check`,fix:`${ir.bin} fix`},dependencies:{react:"^19.2.0","react-dom":"^19.2.0","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":"^19.2.0","@types/react-dom":"^19.2.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",[ir.pkg]:ir.range}},null,2)}
492
+ `}function oO(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 sO(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function I_(t,e={}){let r=oO(e.instanceOrigin);return`import { defineConfig } from 'vite';
493
493
  import { fileURLToPath, URL } from 'node:url';
494
494
  import react from '@vitejs/plugin-react';
495
495
  // Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
@@ -508,8 +508,8 @@ import tailwindcss from '@tailwindcss/vite';
508
508
  // you sign in, and the cookies land on localhost:3000. Override the targets
509
509
  // with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
510
510
  // them at boot; restart the dev server after changing one).
511
- const TENANT = process.env.SUPABASE_URL || '${r??tO}'; // /rest + the Realtime WS
512
- const API = process.env.TURBOBASE_API_URL || '${r??rO}'; // /v1, /auth, /login, /_app
511
+ const TENANT = process.env.SUPABASE_URL || '${r??rO}'; // /rest + the Realtime WS
512
+ const API = process.env.TURBOBASE_API_URL || '${r??nO}'; // /v1, /auth, /login, /_app
513
513
 
514
514
  // Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
515
515
  // this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
@@ -547,7 +547,7 @@ export default defineConfig({
547
547
  },
548
548
  build: { outDir: 'dist' },
549
549
  });
550
- `}function L_(t){return`<!doctype html>
550
+ `}function j_(t){return`<!doctype html>
551
551
  <html lang="en">
552
552
  <head>
553
553
  <meta charset="UTF-8" />
@@ -560,7 +560,7 @@ export default defineConfig({
560
560
  <script type="module" src="/src/main.tsx"></script>
561
561
  </body>
562
562
  </html>
563
- `}function iO(t){return{"package.json":A_(t.slug),"vite.config.ts":C_(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":sO,"tsconfig.json":I_,".oxlintrc.json":$_,"oxfmt.config.ts":T_,"code-standards.json":R_,[ir.baseline]:P_,"knip.json":E_,"index.html":L_(t.title),"public/turbobase.json":QI(t),"public/favicon.svg":x_(t.slug,t.title),"src/main.tsx":j_,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":S_,"src/styles.css":z_,"components.json":O_,"src/lib/utils.ts":N_,"src/components/ui/button.tsx":D_,"src/components/ui/card.tsx":M_,"src/components/ui/badge.tsx":U_,"src/components/ui/table.tsx":q_,"src/components/ui/input.tsx":F_,"src/components/ui/label.tsx":B_,"README.md":`# ${t.title}
563
+ `}function aO(t){return{"package.json":C_(t.slug),"vite.config.ts":I_(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":iO,"tsconfig.json":O_,".oxlintrc.json":T_,"oxfmt.config.ts":R_,"code-standards.json":E_,[ir.baseline]:A_,"knip.json":P_,"index.html":j_(t.title),"public/turbobase.json":eO(t),"public/favicon.svg":x_(t.slug,t.title),"src/main.tsx":z_,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":$_,"src/styles.css":D_,"components.json":N_,"src/lib/utils.ts":L_,"src/components/ui/button.tsx":M_,"src/components/ui/card.tsx":U_,"src/components/ui/badge.tsx":q_,"src/components/ui/table.tsx":F_,"src/components/ui/input.tsx":B_,"src/components/ui/label.tsx":Z_,"README.md":`# ${t.title}
564
564
 
565
565
  \`\`\`sh
566
566
  npm install
@@ -583,7 +583,7 @@ every read comes back "permission denied", which looks like an RLS problem.
583
583
 
584
584
  \`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
585
585
  live access token and is gitignored \u2014 keep it that way.
586
- `}}function aO(t){return`import React from 'react';
586
+ `}}function cO(t){return`import React from 'react';
587
587
  import { Loader2, Trash2 } from 'lucide-react';
588
588
 
589
589
  import { select, write, del } from '@/lib/turbobase';
@@ -808,7 +808,7 @@ export default function App() {
808
808
  </main>
809
809
  );
810
810
  }
811
- `}var JI,YI,S_,Is,eO,ir,$_,T_,R_,E_,P_,tO,rO,sO,I_,O_,N_,j_,z_,D_,M_,U_,q_,F_,B_,V_=L(()=>{k_();Qu();JI=200,YI=60;S_=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
811
+ `}var YI,XI,$_,Is,tO,ir,T_,R_,E_,P_,A_,rO,nO,iO,O_,N_,L_,z_,D_,M_,U_,q_,F_,B_,Z_,H_=L(()=>{S_();ed();YI=200,XI=60;$_=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
812
812
  // Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
813
813
  // A cold first paint that fans out many reads should use batch() \u2014 ONE request
814
814
  // that multiplexes them, sidestepping the per-request rate limiter.
@@ -1355,6 +1355,13 @@ export interface BatchResult<T = unknown> {
1355
1355
  * (\`{ query, count: 'exact' }\`) to know how far. A sub-query whose own
1356
1356
  * \`limit\` is 1000 or less can never carry it. */
1357
1357
  truncated?: true;
1358
+ /** \`true\` when the instance ran out of time for the WHOLE batch before this
1359
+ * sub-query started, so it was never sent: \`ok\` is false and \`status\` is 504,
1360
+ * the same as a read that timed out, and this is how you tell the two apart.
1361
+ * Absent \u2014 never \`false\` \u2014 on every other result, so the check is
1362
+ * \`if (r.notRun)\`. Ask again for just these queries; re-sending the whole
1363
+ * batch re-runs the ones that came back and re-enters the same queue. */
1364
+ notRun?: true;
1358
1365
  }
1359
1366
 
1360
1367
  /** One element of the list you pass batch(): the same path-and-query string you
@@ -1484,6 +1491,7 @@ async function batchChunk<T>(queries: BatchQuery[]): Promise<BatchResult<T>[]> {
1484
1491
  contentRange?: string | null;
1485
1492
  stitched?: { aliases: string[]; truncated: string[] };
1486
1493
  truncated?: true;
1494
+ notRun?: true;
1487
1495
  }[];
1488
1496
  };
1489
1497
  // \`ok\` \u2014 not \`status === 200\` \u2014 is what decides success, and a counted
@@ -1509,6 +1517,11 @@ async function batchChunk<T>(queries: BatchQuery[]): Promise<BatchResult<T>[]> {
1509
1517
  status: r.status,
1510
1518
  count: r.count ?? null,
1511
1519
  contentRange: r.contentRange ?? null,
1520
+ // Only when the instance set it, for the reason the happy arm gives
1521
+ // about \`truncated\`: a \`notRun: undefined\` key would make
1522
+ // \`'notRun' in r\` true on every sub-query that was tried and failed,
1523
+ // which is the one distinction this field exists to draw.
1524
+ ...(r.notRun ? { notRun: true as const } : {}),
1512
1525
  error:
1513
1526
  typeof r.body === 'object' && r.body && 'error' in r.body
1514
1527
  ? String((r.body as { error: unknown }).error)
@@ -2106,14 +2119,32 @@ export async function rollbackProcessRun(
2106
2119
  if (!res.ok) throw await writeError(res, 'process run');
2107
2120
  return (await res.json()) as { runId: string; state: string; queued: boolean };
2108
2121
  }
2109
- `,Is="src/types.ts",eO=`turbobase project types -o ${Is} || node -e "if(require('node:fs').existsSync('${Is}')){console.error('turbobase: could not refresh ${Is} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${Is} 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 ${Is}');process.exit(1)}"`,ir={pkg:"@turbobase/code-standards",range:"^0.1.0",bin:"code-standards",oxlintProfile:"./node_modules/@turbobase/code-standards/oxlint/react.json",oxfmtConfig:"@turbobase/code-standards/oxfmt",ignore:["src/types.ts","src/lib/turbobase.ts","dist/**",".claude/**","node_modules/**"],baseline:"code-standards.baseline.json"},$_=`${JSON.stringify({extends:[ir.oxlintProfile],ignorePatterns:[...ir.ignore]},null,2)}
2110
- `,T_=`// The house format, from ${ir.pkg}. Re-exported rather than copied,
2122
+
2123
+ /** Carry on a run that STOPPED waiting on the connected system: the same run picks
2124
+ * up at the step it stopped on, waits again for the answer that was missing, and
2125
+ * runs the rest \u2014 so nothing it already wrote is written again. Offer this instead
2126
+ * of invoking the process a second time, which starts a NEW run and creates the
2127
+ * first records over. Queued \u2014 watch the run until it reads \`committed\` with
2128
+ * \`outstanding: 0\`. Only a run that ended \`committed\` with work outstanding can
2129
+ * be resumed; anything else answers 409 (\`process_run_not_resumable\`, naming the
2130
+ * state), and an \`eachRow\` process answers 409 too \u2014 invoke it again instead. */
2131
+ export async function resumeProcessRun(
2132
+ runId: string,
2133
+ ): Promise<{ runId: string; state: string; queued: boolean }> {
2134
+ const res = await req(\`/v1/processes/runs/\${encodeURIComponent(runId)}/resume\`, {
2135
+ method: 'POST',
2136
+ });
2137
+ if (!res.ok) throw await writeError(res, 'process run');
2138
+ return (await res.json()) as { runId: string; state: string; queued: boolean };
2139
+ }
2140
+ `,Is="src/types.ts",tO=`turbobase project types -o ${Is} || node -e "if(require('node:fs').existsSync('${Is}')){console.error('turbobase: could not refresh ${Is} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${Is} 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 ${Is}');process.exit(1)}"`,ir={pkg:"@turbobase/code-standards",range:"^0.1.0",bin:"code-standards",oxlintProfile:"./node_modules/@turbobase/code-standards/oxlint/react.json",oxfmtConfig:"@turbobase/code-standards/oxfmt",ignore:["src/types.ts","src/lib/turbobase.ts","dist/**",".claude/**","node_modules/**"],baseline:"code-standards.baseline.json"},T_=`${JSON.stringify({extends:[ir.oxlintProfile],ignorePatterns:[...ir.ignore]},null,2)}
2141
+ `,R_=`// The house format, from ${ir.pkg}. Re-exported rather than copied,
2111
2142
  // so a new version of the package is the only change a format update needs.
2112
2143
  export { default } from '${ir.oxfmtConfig}';
2113
- `,R_=`${JSON.stringify({units:["."],ignore:[...ir.ignore]},null,2)}
2114
- `,E_=`${JSON.stringify({$schema:"https://unpkg.com/knip@6/schema.json",entry:["{hooks,conduits,processes}/**/*.{ts,js}","oxfmt.config.ts"],ignoreDependencies:["@turbobase/extensions"],ignoreExportsUsedInFile:!0,include:["files","dependencies","unlisted","exports","types","duplicates"]},null,2)}
2115
- `,P_=`${JSON.stringify({version:1,findings:{},duplicates:{}},null," ")}
2116
- `;tO="http://localhost:54331",rO="http://localhost:4100";sO=`node_modules/
2144
+ `,E_=`${JSON.stringify({units:["."],ignore:[...ir.ignore]},null,2)}
2145
+ `,P_=`${JSON.stringify({$schema:"https://unpkg.com/knip@6/schema.json",entry:["{hooks,conduits,processes}/**/*.{ts,js}","oxfmt.config.ts"],ignoreDependencies:["@turbobase/extensions"],ignoreExportsUsedInFile:!0,include:["files","dependencies","unlisted","exports","types","duplicates"]},null,2)}
2146
+ `,A_=`${JSON.stringify({version:1,findings:{},duplicates:{}},null," ")}
2147
+ `;rO="http://localhost:54331",nO="http://localhost:4100";iO=`node_modules/
2117
2148
  dist/
2118
2149
  build/
2119
2150
 
@@ -2125,9 +2156,9 @@ build/
2125
2156
  !.env.example
2126
2157
 
2127
2158
  .DS_Store
2128
- `,I_=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
2129
- `,O_=`${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)}
2130
- `,N_=`import { clsx, type ClassValue } from 'clsx';
2159
+ `,O_=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
2160
+ `,N_=`${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)}
2161
+ `,L_=`import { clsx, type ClassValue } from 'clsx';
2131
2162
  import { twMerge } from 'tailwind-merge';
2132
2163
 
2133
2164
  /**
@@ -2141,7 +2172,7 @@ import { twMerge } from 'tailwind-merge';
2141
2172
  export function cn(...inputs: ClassValue[]) {
2142
2173
  return twMerge(clsx(inputs));
2143
2174
  }
2144
- `;j_=`import React from 'react';
2175
+ `;z_=`import React from 'react';
2145
2176
  import { createRoot } from 'react-dom/client';
2146
2177
  import App from './App';
2147
2178
  import './styles.css';
@@ -2151,7 +2182,7 @@ createRoot(document.getElementById('root')!).render(
2151
2182
  <App />
2152
2183
  </React.StrictMode>,
2153
2184
  );
2154
- `,z_=`@import 'tailwindcss';
2185
+ `,D_=`@import 'tailwindcss';
2155
2186
  @import 'tw-animate-css';
2156
2187
 
2157
2188
  /* Inter, self-hosted \u2014 the design system's font.
@@ -2239,7 +2270,7 @@ createRoot(document.getElementById('root')!).render(
2239
2270
  transition-duration: 0.01ms !important;
2240
2271
  }
2241
2272
  }
2242
- `,D_=`import * as React from 'react';
2273
+ `,M_=`import * as React from 'react';
2243
2274
  import { cva, type VariantProps } from 'class-variance-authority';
2244
2275
 
2245
2276
  import { cn } from '@/lib/utils';
@@ -2279,7 +2310,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
2279
2310
  Button.displayName = 'Button';
2280
2311
 
2281
2312
  export { Button, buttonVariants };
2282
- `,M_=`import * as React from 'react';
2313
+ `,U_=`import * as React from 'react';
2283
2314
 
2284
2315
  import { cn } from '@/lib/utils';
2285
2316
 
@@ -2317,7 +2348,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
2317
2348
  CardContent.displayName = 'CardContent';
2318
2349
 
2319
2350
  export { Card, CardHeader, CardTitle, CardDescription, CardContent };
2320
- `,U_=`import * as React from 'react';
2351
+ `,q_=`import * as React from 'react';
2321
2352
  import { cva, type VariantProps } from 'class-variance-authority';
2322
2353
 
2323
2354
  import { cn } from '@/lib/utils';
@@ -2352,7 +2383,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
2352
2383
  }
2353
2384
 
2354
2385
  export { Badge, badgeVariants };
2355
- `,q_=`import * as React from 'react';
2386
+ `,F_=`import * as React from 'react';
2356
2387
 
2357
2388
  import { cn } from '@/lib/utils';
2358
2389
 
@@ -2411,7 +2442,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
2411
2442
  TableCell.displayName = 'TableCell';
2412
2443
 
2413
2444
  export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
2414
- `,F_=`import * as React from 'react';
2445
+ `,B_=`import * as React from 'react';
2415
2446
 
2416
2447
  import { cn } from '@/lib/utils';
2417
2448
 
@@ -2431,7 +2462,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
2431
2462
  Input.displayName = 'Input';
2432
2463
 
2433
2464
  export { Input };
2434
- `,B_=`import * as React from 'react';
2465
+ `,Z_=`import * as React from 'react';
2435
2466
 
2436
2467
  import { cn } from '@/lib/utils';
2437
2468
 
@@ -2448,9 +2479,9 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
2448
2479
  Label.displayName = 'Label';
2449
2480
 
2450
2481
  export { Label };
2451
- `});var Os=L(()=>{Qi()});function N(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 Dt(t){return t&&Object.assign(Da,t),Da}var lO,Mr,Da,Io=L(()=>{lO=Object.freeze({status:"aborted"});Mr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Da={}});var _e={};ls(_e,{BIGINT_FORMAT_RANGES:()=>K_,Class:()=>pd,NUMBER_FORMAT_RANGES:()=>wd,aborted:()=>Fn,allowsEval:()=>gd,assert:()=>mO,assertEqual:()=>uO,assertIs:()=>pO,assertNever:()=>hO,assertNotEqual:()=>dO,assignProp:()=>fd,cached:()=>js,captureStackTrace:()=>Ua,cleanEnum:()=>RO,cleanRegex:()=>Ds,clone:()=>Mt,createTransparentProxy:()=>_O,defineLazy:()=>Le,esc:()=>qn,escapeRegex:()=>rn,extend:()=>kO,finalizeIssue:()=>ar,floatSafeRemainder:()=>md,getElementAtPath:()=>fO,getEnumValues:()=>Ls,getLengthableOrigin:()=>Ms,getParsedType:()=>wO,getSizableOrigin:()=>W_,isObject:()=>Oo,isPlainObject:()=>No,issue:()=>_d,joinValues:()=>Ma,jsonStringifyReplacer:()=>hd,merge:()=>SO,normalizeParams:()=>ae,nullish:()=>zs,numKeys:()=>bO,omit:()=>xO,optionalKeys:()=>bd,partial:()=>$O,pick:()=>vO,prefixIssues:()=>vr,primitiveTypes:()=>H_,promiseAllObject:()=>gO,propertyKeyTypes:()=>yd,randomString:()=>yO,required:()=>TO,stringifyPrimitive:()=>qa,unwrapMessage:()=>Ns});function uO(t){return t}function dO(t){return t}function pO(t){}function hO(t){throw new Error}function mO(t){}function Ls(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 Ma(t,e="|"){return t.map(r=>qa(r)).join(e)}function hd(t,e){return typeof e=="bigint"?e.toString():e}function js(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function zs(t){return t==null}function Ds(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function md(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 Le(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 fd(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function fO(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function gO(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 yO(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function qn(t){return JSON.stringify(t)}function Oo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function No(t){if(Oo(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Oo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function bO(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function rn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ae(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 _O(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 qa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function bd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function vO(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 Mt(t,{...t._zod.def,shape:r,checks:[]})}function xO(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 Mt(t,{...t._zod.def,shape:r,checks:[]})}function kO(t,e){if(!No(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 fd(this,"shape",n),n},checks:[]};return Mt(t,r)}function SO(t,e){return Mt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return fd(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function $O(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 Mt(e,{...e._zod.def,shape:o,checks:[]})}function TO(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 Mt(e,{...e._zod.def,shape:o,checks:[]})}function Fn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function vr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ns(t){return typeof t=="string"?t:t?.message}function ar(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Ns(t.inst?._zod.def?.error?.(t))??Ns(e?.error?.(t))??Ns(r.customError?.(t))??Ns(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function W_(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ms(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _d(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function RO(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ua,gd,wO,yd,H_,wd,K_,pd,xr=L(()=>{Ua=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};gd=js(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});wO=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}`)}},yd=new Set(["string","number","symbol"]),H_=new Set(["string","number","bigint","boolean","symbol","undefined"]);wd={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]},K_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};pd=class{constructor(...e){}}});function vd(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 xd(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 G_,Fa,Us,kd=L(()=>{Io();xr();G_=(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,hd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Fa=N("$ZodError",G_),Us=N("$ZodError",G_,{Parent:Error})});var Sd,$d,Td,Rd,Ed,Bn,Pd,Zn,Ad=L(()=>{Io();kd();xr();Sd=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 Mr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ar(c,s,Dt())));throw Ua(a,o?.callee),a}return i.value},$d=Sd(Us),Td=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=>ar(c,s,Dt())));throw Ua(a,o?.callee),a}return i.value},Rd=Td(Us),Ed=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 Mr;return s.issues.length?{success:!1,error:new(t??Fa)(s.issues.map(i=>ar(i,o,Dt())))}:{success:!0,data:s.value}},Bn=Ed(Us),Pd=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=>ar(i,o,Dt())))}:{success:!0,data:s.value}},Zn=Pd(Us)});function sv(){return new RegExp(PO,"u")}function fv(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 gv(t){return new RegExp(`^${fv(t)}$`)}function yv(t){let e=fv({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(`^${hv}T(?:${n})$`)}var J_,Y_,X_,Q_,ev,tv,rv,nv,Cd,ov,PO,iv,av,cv,lv,uv,Id,dv,pv,hv,mv,bv,wv,_v,vv,xv,kv,Sv,Za=L(()=>{J_=/^[cC][^\s-]{8,}$/,Y_=/^[0-9a-z]+$/,X_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Q_=/^[0-9a-vA-V]{20}$/,ev=/^[A-Za-z0-9]{27}$/,tv=/^[a-zA-Z0-9_-]{21}$/,rv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,nv=/^([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})$/,Cd=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)$/,ov=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,PO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";iv=/^(?:(?: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])$/,av=/^(([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})$/,cv=/^((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])$/,lv=/^(([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])$/,uv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Id=/^[A-Za-z0-9_-]*$/,dv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,pv=/^\+(?:[0-9]){6,14}[0-9]$/,hv="(?:(?:\\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])))",mv=new RegExp(`^${hv}$`);bv=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},wv=/^\d+$/,_v=/^-?\d+(?:\.\d+)?/i,vv=/true|false/i,xv=/null/i,kv=/^[^A-Z]*$/,Sv=/^[^a-z]*$/});var lt,$v,Od,Nd,Tv,Rv,Ev,Pv,Av,qs,Cv,Iv,Ov,Nv,Lv,jv,zv,Va=L(()=>{Io();Za();xr();lt=N("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),$v={number:"number",bigint:"bigint",object:"date"},Od=N("$ZodCheckLessThan",(t,e)=>{lt.init(t,e);let r=$v[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})}}),Nd=N("$ZodCheckGreaterThan",(t,e)=>{lt.init(t,e);let r=$v[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})}}),Tv=N("$ZodCheckMultipleOf",(t,e)=>{lt.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):md(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})}}),Rv=N("$ZodCheckNumberFormat",(t,e)=>{lt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=wd[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=wv)}),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})}}),Ev=N("$ZodCheckMaxLength",(t,e)=>{var r;lt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!zs(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=Ms(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Pv=N("$ZodCheckMinLength",(t,e)=>{var r;lt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!zs(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=Ms(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Av=N("$ZodCheckLengthEquals",(t,e)=>{var r;lt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!zs(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=Ms(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})}}),qs=N("$ZodCheckStringFormat",(t,e)=>{var r,n;lt.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=()=>{})}),Cv=N("$ZodCheckRegex",(t,e)=>{qs.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})}}),Iv=N("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=kv),qs.init(t,e)}),Ov=N("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Sv),qs.init(t,e)}),Nv=N("$ZodCheckIncludes",(t,e)=>{lt.init(t,e);let r=rn(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})}}),Lv=N("$ZodCheckStartsWith",(t,e)=>{lt.init(t,e);let r=new RegExp(`^${rn(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})}}),jv=N("$ZodCheckEndsWith",(t,e)=>{lt.init(t,e);let r=new RegExp(`.*${rn(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})}}),zv=N("$ZodCheckOverwrite",(t,e)=>{lt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Ha,Ld=L(()=>{Ha=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(`
2482
+ `});var Os=L(()=>{Qi()});function N(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 Dt(t){return t&&Object.assign(Da,t),Da}var uO,Mr,Da,Co=L(()=>{uO=Object.freeze({status:"aborted"});Mr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Da={}});var _e={};ls(_e,{BIGINT_FORMAT_RANGES:()=>W_,Class:()=>hd,NUMBER_FORMAT_RANGES:()=>_d,aborted:()=>Fn,allowsEval:()=>yd,assert:()=>fO,assertEqual:()=>dO,assertIs:()=>hO,assertNever:()=>mO,assertNotEqual:()=>pO,assignProp:()=>gd,cached:()=>js,captureStackTrace:()=>Ua,cleanEnum:()=>EO,cleanRegex:()=>Ds,clone:()=>Mt,createTransparentProxy:()=>vO,defineLazy:()=>Le,esc:()=>qn,escapeRegex:()=>rn,extend:()=>SO,finalizeIssue:()=>ar,floatSafeRemainder:()=>fd,getElementAtPath:()=>gO,getEnumValues:()=>Ls,getLengthableOrigin:()=>Ms,getParsedType:()=>_O,getSizableOrigin:()=>G_,isObject:()=>Io,isPlainObject:()=>Oo,issue:()=>vd,joinValues:()=>Ma,jsonStringifyReplacer:()=>md,merge:()=>$O,normalizeParams:()=>ae,nullish:()=>zs,numKeys:()=>wO,omit:()=>xO,optionalKeys:()=>wd,partial:()=>TO,pick:()=>kO,prefixIssues:()=>vr,primitiveTypes:()=>K_,promiseAllObject:()=>yO,propertyKeyTypes:()=>bd,randomString:()=>bO,required:()=>RO,stringifyPrimitive:()=>qa,unwrapMessage:()=>Ns});function dO(t){return t}function pO(t){return t}function hO(t){}function mO(t){throw new Error}function fO(t){}function Ls(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 Ma(t,e="|"){return t.map(r=>qa(r)).join(e)}function md(t,e){return typeof e=="bigint"?e.toString():e}function js(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function zs(t){return t==null}function Ds(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function fd(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 Le(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 gd(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function gO(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function yO(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 bO(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function qn(t){return JSON.stringify(t)}function Io(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Oo(t){if(Io(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Io(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function wO(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function rn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ae(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 vO(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 qa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function wd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function kO(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 Mt(t,{...t._zod.def,shape:r,checks:[]})}function xO(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 Mt(t,{...t._zod.def,shape:r,checks:[]})}function SO(t,e){if(!Oo(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 gd(this,"shape",n),n},checks:[]};return Mt(t,r)}function $O(t,e){return Mt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return gd(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function TO(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 Mt(e,{...e._zod.def,shape:o,checks:[]})}function RO(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 Mt(e,{...e._zod.def,shape:o,checks:[]})}function Fn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function vr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ns(t){return typeof t=="string"?t:t?.message}function ar(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Ns(t.inst?._zod.def?.error?.(t))??Ns(e?.error?.(t))??Ns(r.customError?.(t))??Ns(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function G_(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ms(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function vd(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function EO(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ua,yd,_O,bd,K_,_d,W_,hd,kr=L(()=>{Ua=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};yd=js(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});_O=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}`)}},bd=new Set(["string","number","symbol"]),K_=new Set(["string","number","bigint","boolean","symbol","undefined"]);_d={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]},W_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};hd=class{constructor(...e){}}});function kd(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 xd(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 J_,Fa,Us,Sd=L(()=>{Co();kr();J_=(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,md,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Fa=N("$ZodError",J_),Us=N("$ZodError",J_,{Parent:Error})});var $d,Td,Rd,Ed,Pd,Bn,Ad,Zn,Cd=L(()=>{Co();Sd();kr();$d=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 Mr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ar(c,s,Dt())));throw Ua(a,o?.callee),a}return i.value},Td=$d(Us),Rd=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=>ar(c,s,Dt())));throw Ua(a,o?.callee),a}return i.value},Ed=Rd(Us),Pd=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 Mr;return s.issues.length?{success:!1,error:new(t??Fa)(s.issues.map(i=>ar(i,o,Dt())))}:{success:!0,data:s.value}},Bn=Pd(Us),Ad=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=>ar(i,o,Dt())))}:{success:!0,data:s.value}},Zn=Ad(Us)});function iv(){return new RegExp(AO,"u")}function gv(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 yv(t){return new RegExp(`^${gv(t)}$`)}function bv(t){let e=gv({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(`^${mv}T(?:${n})$`)}var Y_,X_,Q_,ev,tv,rv,nv,ov,Id,sv,AO,av,cv,lv,uv,dv,Od,pv,hv,mv,fv,wv,_v,vv,kv,xv,Sv,$v,Za=L(()=>{Y_=/^[cC][^\s-]{8,}$/,X_=/^[0-9a-z]+$/,Q_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ev=/^[0-9a-vA-V]{20}$/,tv=/^[A-Za-z0-9]{27}$/,rv=/^[a-zA-Z0-9_-]{21}$/,nv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ov=/^([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})$/,Id=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)$/,sv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,AO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";av=/^(?:(?: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])$/,cv=/^(([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})$/,lv=/^((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])$/,uv=/^(([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])$/,dv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Od=/^[A-Za-z0-9_-]*$/,pv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,hv=/^\+(?:[0-9]){6,14}[0-9]$/,mv="(?:(?:\\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])))",fv=new RegExp(`^${mv}$`);wv=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},_v=/^\d+$/,vv=/^-?\d+(?:\.\d+)?/i,kv=/true|false/i,xv=/null/i,Sv=/^[^A-Z]*$/,$v=/^[^a-z]*$/});var lt,Tv,Nd,Ld,Rv,Ev,Pv,Av,Cv,qs,Iv,Ov,Nv,Lv,jv,zv,Dv,Va=L(()=>{Co();Za();kr();lt=N("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Tv={number:"number",bigint:"bigint",object:"date"},Nd=N("$ZodCheckLessThan",(t,e)=>{lt.init(t,e);let r=Tv[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})}}),Ld=N("$ZodCheckGreaterThan",(t,e)=>{lt.init(t,e);let r=Tv[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})}}),Rv=N("$ZodCheckMultipleOf",(t,e)=>{lt.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):fd(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})}}),Ev=N("$ZodCheckNumberFormat",(t,e)=>{lt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=_d[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=_v)}),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})}}),Pv=N("$ZodCheckMaxLength",(t,e)=>{var r;lt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!zs(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=Ms(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Av=N("$ZodCheckMinLength",(t,e)=>{var r;lt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!zs(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=Ms(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Cv=N("$ZodCheckLengthEquals",(t,e)=>{var r;lt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!zs(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=Ms(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})}}),qs=N("$ZodCheckStringFormat",(t,e)=>{var r,n;lt.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=()=>{})}),Iv=N("$ZodCheckRegex",(t,e)=>{qs.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})}}),Ov=N("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Sv),qs.init(t,e)}),Nv=N("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=$v),qs.init(t,e)}),Lv=N("$ZodCheckIncludes",(t,e)=>{lt.init(t,e);let r=rn(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})}}),jv=N("$ZodCheckStartsWith",(t,e)=>{lt.init(t,e);let r=new RegExp(`^${rn(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})}}),zv=N("$ZodCheckEndsWith",(t,e)=>{lt.init(t,e);let r=new RegExp(`.*${rn(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})}}),Dv=N("$ZodCheckOverwrite",(t,e)=>{lt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Ha,jd=L(()=>{Ha=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(`
2452
2483
  `).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(`
2453
- `))}}});var Mv,jd=L(()=>{Mv={major:4,minor:0,patch:0}});function Qv(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function AO(t){if(!Id.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Qv(r)}function CO(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 Uv(t,e,r){t.issues.length&&e.issues.push(...vr(r,t.issues)),e.value[r]=t.value}function Ka(t,e,r){t.issues.length&&e.issues.push(...vr(r,t.issues)),e.value[r]=t.value}function qv(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(...vr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Fv(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=>ar(s,n,Dt())))}),e}function zd(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(No(t)&&No(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=zd(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=zd(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 Bv(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Fn(t))return t;let n=zd(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 Zv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Vv(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 Hv(t,e,r){return Fn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Kv(t){return t.value=Object.freeze(t.value),t}function Wv(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(_d(o))}}var Ae,Fs,je,Dd,Md,Ud,qd,Fd,Bd,Zd,Vd,Hd,Kd,Wd,Gv,Jv,Yv,Xv,Gd,Jd,Yd,Xd,Qd,ep,tp,rp,Wa,np,op,sp,ip,ap,cp,Ga,Ja,lp,up,dp,pp,hp,mp,fp,gp,yp,bp,wp,_p,vp,xp,kp,ex=L(()=>{Va();Io();Ld();Ad();Za();xr();jd();xr();Ae=N("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Mv;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=Fn(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 Mr;if(l||w instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await w,s.issues.length!==p&&(c||(c=Fn(s,p)))});else{if(s.issues.length===p)continue;c||(c=Fn(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 Mr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Bn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Zn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Fs=N("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??bv(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}}),je=N("$ZodStringFormat",(t,e)=>{qs.init(t,e),Fs.init(t,e)}),Dd=N("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=nv),je.init(t,e)}),Md=N("$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=Cd(n))}else e.pattern??(e.pattern=Cd());je.init(t,e)}),Ud=N("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=ov),je.init(t,e)}),qd=N("$ZodURL",(t,e)=>{je.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:dv.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})}}}),Fd=N("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=sv()),je.init(t,e)}),Bd=N("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=tv),je.init(t,e)}),Zd=N("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=J_),je.init(t,e)}),Vd=N("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Y_),je.init(t,e)}),Hd=N("$ZodULID",(t,e)=>{e.pattern??(e.pattern=X_),je.init(t,e)}),Kd=N("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Q_),je.init(t,e)}),Wd=N("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=ev),je.init(t,e)}),Gv=N("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=yv(e)),je.init(t,e)}),Jv=N("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=mv),je.init(t,e)}),Yv=N("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=gv(e)),je.init(t,e)}),Xv=N("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=rv),je.init(t,e)}),Gd=N("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=iv),je.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Jd=N("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=av),je.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})}}}),Yd=N("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=cv),je.init(t,e)}),Xd=N("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=lv),je.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})}}});Qd=N("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=uv),je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Qv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});ep=N("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Id),je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{AO(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),tp=N("$ZodE164",(t,e)=>{e.pattern??(e.pattern=pv),je.init(t,e)});rp=N("$ZodJWT",(t,e)=>{je.init(t,e),t._zod.check=r=>{CO(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Wa=N("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??_v,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}}),np=N("$ZodNumber",(t,e)=>{Rv.init(t,e),Wa.init(t,e)}),op=N("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=vv,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}}),sp=N("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=xv,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}}),ip=N("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),ap=N("$ZodNever",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});cp=N("$ZodArray",(t,e)=>{Ae.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=>Uv(l,r,i))):Uv(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Ga=N("$ZodObject",(t,e)=>{Ae.init(t,e);let r=js(()=>{let p=Object.keys(e.shape);for(let f of p)if(!(e.shape[f]instanceof Ae))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let w=bd(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(w)}});Le(t._zod,"propValues",()=>{let p=e.shape,w={};for(let f in p){let m=p[f]._zod;if(m.values){w[f]??(w[f]=new Set);for(let b of m.values)w[f].add(b)}}return w});let n=p=>{let w=new Ha(["shape","payload","ctx"]),f=r.value,m=A=>{let O=qn(A);return`shape[${O}]._zod.run({ value: input[${O}], issues: [] }, ctx)`};w.write("const input = payload.value;");let b=Object.create(null),$=0;for(let A of f.keys)b[A]=`key_${$++}`;w.write("const newResult = {}");for(let A of f.keys)if(f.optionalKeys.has(A)){let O=b[A];w.write(`const ${O} = ${m(A)};`);let q=qn(A);w.write(`
2484
+ `))}}});var Uv,zd=L(()=>{Uv={major:4,minor:0,patch:0}});function ek(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function CO(t){if(!Od.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return ek(r)}function IO(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 qv(t,e,r){t.issues.length&&e.issues.push(...vr(r,t.issues)),e.value[r]=t.value}function Ka(t,e,r){t.issues.length&&e.issues.push(...vr(r,t.issues)),e.value[r]=t.value}function Fv(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(...vr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Bv(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=>ar(s,n,Dt())))}),e}function Dd(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(Oo(t)&&Oo(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=Dd(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=Dd(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 Zv(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Fn(t))return t;let n=Dd(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 Vv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Hv(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 Kv(t,e,r){return Fn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Wv(t){return t.value=Object.freeze(t.value),t}function Gv(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(vd(o))}}var Ae,Fs,je,Md,Ud,qd,Fd,Bd,Zd,Vd,Hd,Kd,Wd,Gd,Jv,Yv,Xv,Qv,Jd,Yd,Xd,Qd,ep,tp,rp,np,Wa,op,sp,ip,ap,cp,lp,Ga,Ja,up,dp,pp,hp,mp,fp,gp,yp,bp,wp,_p,vp,kp,xp,Sp,tk=L(()=>{Va();Co();jd();Cd();Za();kr();zd();kr();Ae=N("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Uv;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=Fn(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 Mr;if(l||w instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await w,s.issues.length!==p&&(c||(c=Fn(s,p)))});else{if(s.issues.length===p)continue;c||(c=Fn(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 Mr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Bn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Zn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Fs=N("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??wv(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}}),je=N("$ZodStringFormat",(t,e)=>{qs.init(t,e),Fs.init(t,e)}),Md=N("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=ov),je.init(t,e)}),Ud=N("$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=Id(n))}else e.pattern??(e.pattern=Id());je.init(t,e)}),qd=N("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=sv),je.init(t,e)}),Fd=N("$ZodURL",(t,e)=>{je.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:pv.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})}}}),Bd=N("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=iv()),je.init(t,e)}),Zd=N("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=rv),je.init(t,e)}),Vd=N("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Y_),je.init(t,e)}),Hd=N("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=X_),je.init(t,e)}),Kd=N("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Q_),je.init(t,e)}),Wd=N("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ev),je.init(t,e)}),Gd=N("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=tv),je.init(t,e)}),Jv=N("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=bv(e)),je.init(t,e)}),Yv=N("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=fv),je.init(t,e)}),Xv=N("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=yv(e)),je.init(t,e)}),Qv=N("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=nv),je.init(t,e)}),Jd=N("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=av),je.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Yd=N("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=cv),je.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})}}}),Xd=N("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=lv),je.init(t,e)}),Qd=N("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=uv),je.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})}}});ep=N("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=dv),je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{ek(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});tp=N("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Od),je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{CO(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),rp=N("$ZodE164",(t,e)=>{e.pattern??(e.pattern=hv),je.init(t,e)});np=N("$ZodJWT",(t,e)=>{je.init(t,e),t._zod.check=r=>{IO(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Wa=N("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??vv,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}}),op=N("$ZodNumber",(t,e)=>{Ev.init(t,e),Wa.init(t,e)}),sp=N("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=kv,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}}),ip=N("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=xv,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}}),ap=N("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),cp=N("$ZodNever",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});lp=N("$ZodArray",(t,e)=>{Ae.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=>qv(l,r,i))):qv(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Ga=N("$ZodObject",(t,e)=>{Ae.init(t,e);let r=js(()=>{let p=Object.keys(e.shape);for(let f of p)if(!(e.shape[f]instanceof Ae))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let w=wd(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(w)}});Le(t._zod,"propValues",()=>{let p=e.shape,w={};for(let f in p){let m=p[f]._zod;if(m.values){w[f]??(w[f]=new Set);for(let b of m.values)w[f].add(b)}}return w});let n=p=>{let w=new Ha(["shape","payload","ctx"]),f=r.value,m=A=>{let O=qn(A);return`shape[${O}]._zod.run({ value: input[${O}], issues: [] }, ctx)`};w.write("const input = payload.value;");let b=Object.create(null),$=0;for(let A of f.keys)b[A]=`key_${$++}`;w.write("const newResult = {}");for(let A of f.keys)if(f.optionalKeys.has(A)){let O=b[A];w.write(`const ${O} = ${m(A)};`);let q=qn(A);w.write(`
2454
2485
  if (${O}.issues.length) {
2455
2486
  if (input[${q}] === undefined) {
2456
2487
  if (${q} in input) {
@@ -2473,57 +2504,57 @@ export { Label };
2473
2504
  if (${O}.issues.length) payload.issues = payload.issues.concat(${O}.issues.map(iss => ({
2474
2505
  ...iss,
2475
2506
  path: iss.path ? [${qn(A)}, ...iss.path] : [${qn(A)}]
2476
- })));`),w.write(`newResult[${qn(A)}] = ${O}.value`)}w.write("payload.value = newResult;"),w.write("return payload;");let R=w.compile();return(A,O)=>R(p,A,O)},o,s=Oo,i=!Da.jitless,c=i&&gd.value,l=e.catchall,u;t._zod.parse=(p,w)=>{u??(u=r.value);let f=p.value;if(!s(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),p;let m=[];if(i&&c&&w?.async===!1&&w.jitless!==!0)o||(o=n(e.shape)),p=o(p,w);else{p.value={};let O=u.shape;for(let q of u.keys){let Y=O[q],De=Y._zod.run({value:f[q],issues:[]},w),Qe=Y._zod.optin==="optional"&&Y._zod.optout==="optional";De instanceof Promise?m.push(De.then(zt=>Qe?qv(zt,p,q,f):Ka(zt,p,q))):Qe?qv(De,p,q,f):Ka(De,p,q)}}if(!l)return m.length?Promise.all(m).then(()=>p):p;let b=[],$=u.keySet,R=l._zod,A=R.def.type;for(let O of Object.keys(f)){if($.has(O))continue;if(A==="never"){b.push(O);continue}let q=R.run({value:f[O],issues:[]},w);q instanceof Promise?m.push(q.then(Y=>Ka(Y,p,O))):Ka(q,p,O)}return b.length&&p.issues.push({code:"unrecognized_keys",keys:b,input:f,inst:t}),m.length?Promise.all(m).then(()=>p):p}});Ja=N("$ZodUnion",(t,e)=>{Ae.init(t,e),Le(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Le(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Le(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Le(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=>Ds(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=>Fv(i,r,t,n)):Fv(s,r,t,n)}}),lp=N("$ZodDiscriminatedUnion",(t,e)=>{Ja.init(t,e);let r=t._zod.parse;Le(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=js(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Oo(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),up=N("$ZodIntersection",(t,e)=>{Ae.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])=>Bv(r,c,l)):Bv(r,s,i)}});dp=N("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!No(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(...vr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...vr(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=>ar(l,n,Dt())),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(...vr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...vr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),pp=N("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=Ls(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>yd.has(typeof n)).map(n=>typeof n=="string"?rn(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}}),hp=N("$ZodLiteral",(t,e)=>{Ae.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?rn(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}}),mp=N("$ZodTransform",(t,e)=>{Ae.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 Mr;return r.value=o,r}}),fp=N("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Le(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Le(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ds(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)}),gp=N("$ZodNullable",(t,e)=>{Ae.init(t,e),Le(t._zod,"optin",()=>e.innerType._zod.optin),Le(t._zod,"optout",()=>e.innerType._zod.optout),Le(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ds(r.source)}|null)$`):void 0}),Le(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)}),yp=N("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Le(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=>Zv(s,e)):Zv(o,e)}});bp=N("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Le(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))}),wp=N("$ZodNonOptional",(t,e)=>{Ae.init(t,e),Le(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=>Vv(s,t)):Vv(o,t)}});_p=N("$ZodCatch",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Le(t._zod,"optout",()=>e.innerType._zod.optout),Le(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=>ar(i,n,Dt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>ar(s,n,Dt()))},input:r.value}),r.issues=[]),r)}}),vp=N("$ZodPipe",(t,e)=>{Ae.init(t,e),Le(t._zod,"values",()=>e.in._zod.values),Le(t._zod,"optin",()=>e.in._zod.optin),Le(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=>Hv(s,e,n)):Hv(o,e,n)}});xp=N("$ZodReadonly",(t,e)=>{Ae.init(t,e),Le(t._zod,"propValues",()=>e.innerType._zod.propValues),Le(t._zod,"values",()=>e.innerType._zod.values),Le(t._zod,"optin",()=>e.innerType._zod.optin),Le(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(Kv):Kv(o)}});kp=N("$ZodCustom",(t,e)=>{lt.init(t,e),Ae.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=>Wv(s,r,n,t));Wv(o,r,n,t)}})});function tx(){return{localeError:OO()}}var IO,OO,rx=L(()=>{xr();IO=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},OO=()=>{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 ${IO(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${qa(n.values[0])}`:`Invalid option: expected one of ${Ma(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":""}: ${Ma(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 Ya=L(()=>{});function nx(){return new Bs}var Bs,nn,$p=L(()=>{Bs=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)}};nn=nx()});function Tp(t,e){return new t({type:"string",...ae(e)})}function Rp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ae(e)})}function Xa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ae(e)})}function Ep(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ae(e)})}function Pp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ae(e)})}function Ap(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ae(e)})}function Cp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ae(e)})}function Ip(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ae(e)})}function Op(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ae(e)})}function Np(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ae(e)})}function Lp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ae(e)})}function jp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ae(e)})}function zp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ae(e)})}function Dp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ae(e)})}function Mp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ae(e)})}function Up(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ae(e)})}function qp(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ae(e)})}function Fp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ae(e)})}function Bp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ae(e)})}function Zp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ae(e)})}function Vp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ae(e)})}function Hp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ae(e)})}function Kp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ae(e)})}function ox(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ae(e)})}function sx(t,e){return new t({type:"string",format:"date",check:"string_format",...ae(e)})}function ix(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ae(e)})}function ax(t,e){return new t({type:"string",format:"duration",check:"string_format",...ae(e)})}function Wp(t,e){return new t({type:"number",checks:[],...ae(e)})}function Gp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ae(e)})}function Jp(t,e){return new t({type:"boolean",...ae(e)})}function Yp(t,e){return new t({type:"null",...ae(e)})}function Xp(t){return new t({type:"unknown"})}function Qp(t,e){return new t({type:"never",...ae(e)})}function Qa(t,e){return new Od({check:"less_than",...ae(e),value:t,inclusive:!1})}function Zs(t,e){return new Od({check:"less_than",...ae(e),value:t,inclusive:!0})}function ec(t,e){return new Nd({check:"greater_than",...ae(e),value:t,inclusive:!1})}function Vs(t,e){return new Nd({check:"greater_than",...ae(e),value:t,inclusive:!0})}function tc(t,e){return new Tv({check:"multiple_of",...ae(e),value:t})}function rc(t,e){return new Ev({check:"max_length",...ae(e),maximum:t})}function Lo(t,e){return new Pv({check:"min_length",...ae(e),minimum:t})}function nc(t,e){return new Av({check:"length_equals",...ae(e),length:t})}function eh(t,e){return new Cv({check:"string_format",format:"regex",...ae(e),pattern:t})}function th(t){return new Iv({check:"string_format",format:"lowercase",...ae(t)})}function rh(t){return new Ov({check:"string_format",format:"uppercase",...ae(t)})}function nh(t,e){return new Nv({check:"string_format",format:"includes",...ae(e),includes:t})}function oh(t,e){return new Lv({check:"string_format",format:"starts_with",...ae(e),prefix:t})}function sh(t,e){return new jv({check:"string_format",format:"ends_with",...ae(e),suffix:t})}function Vn(t){return new zv({check:"overwrite",tx:t})}function ih(t){return Vn(e=>e.normalize(t))}function ah(){return Vn(t=>t.trim())}function ch(){return Vn(t=>t.toLowerCase())}function lh(){return Vn(t=>t.toUpperCase())}function cx(t,e,r){return new t({type:"array",element:e,...ae(r)})}function uh(t,e,r){let n=ae(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function dh(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ae(r)})}var lx=L(()=>{Va();xr()});var ux=L(()=>{});function ph(t,e){if(t instanceof Bs){let n=new oc(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 oc(e);return r.process(t),r.emit(t,e)}function et(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 et(o.element,r);case"object":{for(let s in o.shape)if(et(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(et(s,r))return!0;return!1}case"intersection":return et(o.left,r)||et(o.right,r);case"tuple":{for(let s of o.items)if(et(s,r))return!0;return!!(o.rest&&et(o.rest,r))}case"record":return et(o.keyType,r)||et(o.valueType,r);case"map":return et(o.keyType,r)||et(o.valueType,r);case"set":return et(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return et(o.innerType,r);case"lazy":return et(o.getter(),r);case"default":return et(o.innerType,r);case"prefault":return et(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return et(o.in,r)||et(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var oc,dx=L(()=>{$p();xr();oc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??nn,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 f=a.schema;switch(o.type){case"string":{let m=f;m.type="string";let{minimum:b,maximum:$,format:R,patterns:A,contentEncoding:O}=e._zod.bag;if(typeof b=="number"&&(m.minLength=b),typeof $=="number"&&(m.maxLength=$),R&&(m.format=s[R]??R,m.format===""&&delete m.format),O&&(m.contentEncoding=O),A&&A.size>0){let q=[...A];q.length===1?m.pattern=q[0].source:q.length>1&&(a.schema.allOf=[...q.map(Y=>({...this.target==="draft-7"?{type:"string"}:{},pattern:Y.source}))])}break}case"number":{let m=f,{minimum:b,maximum:$,format:R,multipleOf:A,exclusiveMaximum:O,exclusiveMinimum:q}=e._zod.bag;typeof R=="string"&&R.includes("int")?m.type="integer":m.type="number",typeof q=="number"&&(m.exclusiveMinimum=q),typeof b=="number"&&(m.minimum=b,typeof q=="number"&&(q>=b?delete m.minimum:delete m.exclusiveMinimum)),typeof O=="number"&&(m.exclusiveMaximum=O),typeof $=="number"&&(m.maximum=$,typeof O=="number"&&(O<=$?delete m.maximum:delete m.exclusiveMaximum)),typeof A=="number"&&(m.multipleOf=A);break}case"boolean":{let m=f;m.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":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=f,{minimum:b,maximum:$}=e._zod.bag;typeof b=="number"&&(m.minItems=b),typeof $=="number"&&(m.maxItems=$),m.type="array",m.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let b=o.shape;for(let A in b)m.properties[A]=this.process(b[A],{...p,path:[...p.path,"properties",A]});let $=new Set(Object.keys(b)),R=new Set([...$].filter(A=>{let O=o.shape[A]._zod;return this.io==="input"?O.optin===void 0:O.optout===void 0}));R.size>0&&(m.required=Array.from(R)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=o.options.map((b,$)=>this.process(b,{...p,path:[...p.path,"anyOf",$]}));break}case"intersection":{let m=f,b=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),$=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),R=O=>"allOf"in O&&Object.keys(O).length===1,A=[...R(b)?b.allOf:[b],...R($)?$.allOf:[$]];m.allOf=A;break}case"tuple":{let m=f;m.type="array";let b=o.items.map((A,O)=>this.process(A,{...p,path:[...p.path,"prefixItems",O]}));if(this.target==="draft-2020-12"?m.prefixItems=b:m.items=b,o.rest){let A=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?m.items=A:m.additionalItems=A}o.rest&&(m.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:$,maximum:R}=e._zod.bag;typeof $=="number"&&(m.minItems=$),typeof R=="number"&&(m.maxItems=R);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),m.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 m=f,b=Ls(o.entries);b.every($=>typeof $=="number")&&(m.type="number"),b.every($=>typeof $=="string")&&(m.type="string"),m.enum=b;break}case"literal":{let m=f,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];m.type=$===null?"null":typeof $,m.const=$}else b.every($=>typeof $=="number")&&(m.type="number"),b.every($=>typeof $=="string")&&(m.type="string"),b.every($=>typeof $=="boolean")&&(m.type="string"),b.every($=>$===null)&&(m.type="null"),m.enum=b;break}case"file":{let m=f,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:$,maximum:R,mime:A}=e._zod.bag;$!==void 0&&(b.minLength=$),R!==void 0&&(b.maxLength=R),A?A.length===1?(b.contentMediaType=A[0],Object.assign(m,b)):m.anyOf=A.map(O=>({...b,contentMediaType:O})):Object.assign(m,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,p);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=f,b=e._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=b.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,p),a.ref=m;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,f.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 m=e._zod.innerType;this.process(m,p),a.ref=m;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"&&et(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??(A=>A);if(b)return{ref:$(b)};let R=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=R,{defId:R,ref:`${$("__shared")}#/${p}/${R}`}}if(u[1]===o)return{ref:"#"};let f=`#/${p}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:w,defId:f}=s(u);p.def={...p.schema},f&&(p.defId=f);let m=p.schema;for(let b in m)delete m[b];m.$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>
2507
+ })));`),w.write(`newResult[${qn(A)}] = ${O}.value`)}w.write("payload.value = newResult;"),w.write("return payload;");let R=w.compile();return(A,O)=>R(p,A,O)},o,s=Io,i=!Da.jitless,c=i&&yd.value,l=e.catchall,u;t._zod.parse=(p,w)=>{u??(u=r.value);let f=p.value;if(!s(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),p;let m=[];if(i&&c&&w?.async===!1&&w.jitless!==!0)o||(o=n(e.shape)),p=o(p,w);else{p.value={};let O=u.shape;for(let q of u.keys){let J=O[q],De=J._zod.run({value:f[q],issues:[]},w),Qe=J._zod.optin==="optional"&&J._zod.optout==="optional";De instanceof Promise?m.push(De.then(zt=>Qe?Fv(zt,p,q,f):Ka(zt,p,q))):Qe?Fv(De,p,q,f):Ka(De,p,q)}}if(!l)return m.length?Promise.all(m).then(()=>p):p;let b=[],$=u.keySet,R=l._zod,A=R.def.type;for(let O of Object.keys(f)){if($.has(O))continue;if(A==="never"){b.push(O);continue}let q=R.run({value:f[O],issues:[]},w);q instanceof Promise?m.push(q.then(J=>Ka(J,p,O))):Ka(q,p,O)}return b.length&&p.issues.push({code:"unrecognized_keys",keys:b,input:f,inst:t}),m.length?Promise.all(m).then(()=>p):p}});Ja=N("$ZodUnion",(t,e)=>{Ae.init(t,e),Le(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Le(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Le(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Le(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=>Ds(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=>Bv(i,r,t,n)):Bv(s,r,t,n)}}),up=N("$ZodDiscriminatedUnion",(t,e)=>{Ja.init(t,e);let r=t._zod.parse;Le(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=js(()=>{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(!Io(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)}}),dp=N("$ZodIntersection",(t,e)=>{Ae.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])=>Zv(r,c,l)):Zv(r,s,i)}});pp=N("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Oo(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(...vr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...vr(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=>ar(l,n,Dt())),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(...vr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...vr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),hp=N("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=Ls(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>bd.has(typeof n)).map(n=>typeof n=="string"?rn(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}}),mp=N("$ZodLiteral",(t,e)=>{Ae.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?rn(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}}),fp=N("$ZodTransform",(t,e)=>{Ae.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 Mr;return r.value=o,r}}),gp=N("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Le(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Le(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ds(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)}),yp=N("$ZodNullable",(t,e)=>{Ae.init(t,e),Le(t._zod,"optin",()=>e.innerType._zod.optin),Le(t._zod,"optout",()=>e.innerType._zod.optout),Le(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ds(r.source)}|null)$`):void 0}),Le(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)}),bp=N("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Le(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=>Vv(s,e)):Vv(o,e)}});wp=N("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Le(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))}),_p=N("$ZodNonOptional",(t,e)=>{Ae.init(t,e),Le(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=>Hv(s,t)):Hv(o,t)}});vp=N("$ZodCatch",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Le(t._zod,"optout",()=>e.innerType._zod.optout),Le(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=>ar(i,n,Dt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>ar(s,n,Dt()))},input:r.value}),r.issues=[]),r)}}),kp=N("$ZodPipe",(t,e)=>{Ae.init(t,e),Le(t._zod,"values",()=>e.in._zod.values),Le(t._zod,"optin",()=>e.in._zod.optin),Le(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=>Kv(s,e,n)):Kv(o,e,n)}});xp=N("$ZodReadonly",(t,e)=>{Ae.init(t,e),Le(t._zod,"propValues",()=>e.innerType._zod.propValues),Le(t._zod,"values",()=>e.innerType._zod.values),Le(t._zod,"optin",()=>e.innerType._zod.optin),Le(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(Wv):Wv(o)}});Sp=N("$ZodCustom",(t,e)=>{lt.init(t,e),Ae.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=>Gv(s,r,n,t));Gv(o,r,n,t)}})});function rk(){return{localeError:NO()}}var OO,NO,nk=L(()=>{kr();OO=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},NO=()=>{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 ${OO(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${qa(n.values[0])}`:`Invalid option: expected one of ${Ma(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":""}: ${Ma(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 Ya=L(()=>{});function ok(){return new Bs}var Bs,nn,Tp=L(()=>{Bs=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)}};nn=ok()});function Rp(t,e){return new t({type:"string",...ae(e)})}function Ep(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ae(e)})}function Xa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ae(e)})}function Pp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ae(e)})}function Ap(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ae(e)})}function Cp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ae(e)})}function Ip(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ae(e)})}function Op(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ae(e)})}function Np(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ae(e)})}function Lp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ae(e)})}function jp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ae(e)})}function zp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ae(e)})}function Dp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ae(e)})}function Mp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ae(e)})}function Up(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ae(e)})}function qp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ae(e)})}function Fp(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ae(e)})}function Bp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ae(e)})}function Zp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ae(e)})}function Vp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ae(e)})}function Hp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ae(e)})}function Kp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ae(e)})}function Wp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ae(e)})}function sk(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ae(e)})}function ik(t,e){return new t({type:"string",format:"date",check:"string_format",...ae(e)})}function ak(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ae(e)})}function ck(t,e){return new t({type:"string",format:"duration",check:"string_format",...ae(e)})}function Gp(t,e){return new t({type:"number",checks:[],...ae(e)})}function Jp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ae(e)})}function Yp(t,e){return new t({type:"boolean",...ae(e)})}function Xp(t,e){return new t({type:"null",...ae(e)})}function Qp(t){return new t({type:"unknown"})}function eh(t,e){return new t({type:"never",...ae(e)})}function Qa(t,e){return new Nd({check:"less_than",...ae(e),value:t,inclusive:!1})}function Zs(t,e){return new Nd({check:"less_than",...ae(e),value:t,inclusive:!0})}function ec(t,e){return new Ld({check:"greater_than",...ae(e),value:t,inclusive:!1})}function Vs(t,e){return new Ld({check:"greater_than",...ae(e),value:t,inclusive:!0})}function tc(t,e){return new Rv({check:"multiple_of",...ae(e),value:t})}function rc(t,e){return new Pv({check:"max_length",...ae(e),maximum:t})}function No(t,e){return new Av({check:"min_length",...ae(e),minimum:t})}function nc(t,e){return new Cv({check:"length_equals",...ae(e),length:t})}function th(t,e){return new Iv({check:"string_format",format:"regex",...ae(e),pattern:t})}function rh(t){return new Ov({check:"string_format",format:"lowercase",...ae(t)})}function nh(t){return new Nv({check:"string_format",format:"uppercase",...ae(t)})}function oh(t,e){return new Lv({check:"string_format",format:"includes",...ae(e),includes:t})}function sh(t,e){return new jv({check:"string_format",format:"starts_with",...ae(e),prefix:t})}function ih(t,e){return new zv({check:"string_format",format:"ends_with",...ae(e),suffix:t})}function Vn(t){return new Dv({check:"overwrite",tx:t})}function ah(t){return Vn(e=>e.normalize(t))}function ch(){return Vn(t=>t.trim())}function lh(){return Vn(t=>t.toLowerCase())}function uh(){return Vn(t=>t.toUpperCase())}function lk(t,e,r){return new t({type:"array",element:e,...ae(r)})}function dh(t,e,r){let n=ae(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function ph(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ae(r)})}var uk=L(()=>{Va();kr()});var dk=L(()=>{});function hh(t,e){if(t instanceof Bs){let n=new oc(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 oc(e);return r.process(t),r.emit(t,e)}function et(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 et(o.element,r);case"object":{for(let s in o.shape)if(et(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(et(s,r))return!0;return!1}case"intersection":return et(o.left,r)||et(o.right,r);case"tuple":{for(let s of o.items)if(et(s,r))return!0;return!!(o.rest&&et(o.rest,r))}case"record":return et(o.keyType,r)||et(o.valueType,r);case"map":return et(o.keyType,r)||et(o.valueType,r);case"set":return et(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return et(o.innerType,r);case"lazy":return et(o.getter(),r);case"default":return et(o.innerType,r);case"prefault":return et(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return et(o.in,r)||et(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var oc,pk=L(()=>{Tp();kr();oc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??nn,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 f=a.schema;switch(o.type){case"string":{let m=f;m.type="string";let{minimum:b,maximum:$,format:R,patterns:A,contentEncoding:O}=e._zod.bag;if(typeof b=="number"&&(m.minLength=b),typeof $=="number"&&(m.maxLength=$),R&&(m.format=s[R]??R,m.format===""&&delete m.format),O&&(m.contentEncoding=O),A&&A.size>0){let q=[...A];q.length===1?m.pattern=q[0].source:q.length>1&&(a.schema.allOf=[...q.map(J=>({...this.target==="draft-7"?{type:"string"}:{},pattern:J.source}))])}break}case"number":{let m=f,{minimum:b,maximum:$,format:R,multipleOf:A,exclusiveMaximum:O,exclusiveMinimum:q}=e._zod.bag;typeof R=="string"&&R.includes("int")?m.type="integer":m.type="number",typeof q=="number"&&(m.exclusiveMinimum=q),typeof b=="number"&&(m.minimum=b,typeof q=="number"&&(q>=b?delete m.minimum:delete m.exclusiveMinimum)),typeof O=="number"&&(m.exclusiveMaximum=O),typeof $=="number"&&(m.maximum=$,typeof O=="number"&&(O<=$?delete m.maximum:delete m.exclusiveMaximum)),typeof A=="number"&&(m.multipleOf=A);break}case"boolean":{let m=f;m.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":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=f,{minimum:b,maximum:$}=e._zod.bag;typeof b=="number"&&(m.minItems=b),typeof $=="number"&&(m.maxItems=$),m.type="array",m.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let b=o.shape;for(let A in b)m.properties[A]=this.process(b[A],{...p,path:[...p.path,"properties",A]});let $=new Set(Object.keys(b)),R=new Set([...$].filter(A=>{let O=o.shape[A]._zod;return this.io==="input"?O.optin===void 0:O.optout===void 0}));R.size>0&&(m.required=Array.from(R)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=o.options.map((b,$)=>this.process(b,{...p,path:[...p.path,"anyOf",$]}));break}case"intersection":{let m=f,b=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),$=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),R=O=>"allOf"in O&&Object.keys(O).length===1,A=[...R(b)?b.allOf:[b],...R($)?$.allOf:[$]];m.allOf=A;break}case"tuple":{let m=f;m.type="array";let b=o.items.map((A,O)=>this.process(A,{...p,path:[...p.path,"prefixItems",O]}));if(this.target==="draft-2020-12"?m.prefixItems=b:m.items=b,o.rest){let A=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?m.items=A:m.additionalItems=A}o.rest&&(m.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:$,maximum:R}=e._zod.bag;typeof $=="number"&&(m.minItems=$),typeof R=="number"&&(m.maxItems=R);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),m.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 m=f,b=Ls(o.entries);b.every($=>typeof $=="number")&&(m.type="number"),b.every($=>typeof $=="string")&&(m.type="string"),m.enum=b;break}case"literal":{let m=f,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];m.type=$===null?"null":typeof $,m.const=$}else b.every($=>typeof $=="number")&&(m.type="number"),b.every($=>typeof $=="string")&&(m.type="string"),b.every($=>typeof $=="boolean")&&(m.type="string"),b.every($=>$===null)&&(m.type="null"),m.enum=b;break}case"file":{let m=f,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:$,maximum:R,mime:A}=e._zod.bag;$!==void 0&&(b.minLength=$),R!==void 0&&(b.maxLength=R),A?A.length===1?(b.contentMediaType=A[0],Object.assign(m,b)):m.anyOf=A.map(O=>({...b,contentMediaType:O})):Object.assign(m,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,p);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=f,b=e._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=b.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,p),a.ref=m;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,f.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 m=e._zod.innerType;this.process(m,p),a.ref=m;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"&&et(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??(A=>A);if(b)return{ref:$(b)};let R=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=R,{defId:R,ref:`${$("__shared")}#/${p}/${R}`}}if(u[1]===o)return{ref:"#"};let f=`#/${p}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:w,defId:f}=s(u);p.def={...p.schema},f&&(p.defId=f);let m=p.schema;for(let b in m)delete m[b];m.$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>
2477
2508
 
2478
- 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 f=n.external.registry.get(u[0])?.id;if(e!==u[0]&&f){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),f=w.def??w.schema,m={...f};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"?(f.allOf=f.allOf??[],f.allOf.push($)):(Object.assign(f,$),Object.assign(f,m))}w.isParent||this.override({zodSchema:u,jsonSchema:f,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 px=L(()=>{});var wt=L(()=>{Io();Ad();kd();ex();Va();jd();xr();Za();Ya();$p();Ld();ux();lx();dx();px()});var hh=L(()=>{wt()});function mh(t,e){let r={type:"object",get shape(){return _e.assignProp(this,"shape",{...t}),this.shape},..._e.normalizeParams(e)};return new fN(r)}var mN,fN,hx=L(()=>{wt();wt();hh();mN=N("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ae.init(t,e),t.def=e,t.parse=(r,n)=>$d(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Bn(t,r,n),t.parseAsync=async(r,n)=>Rd(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Zn(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)=>Mt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),fN=N("ZodMiniObject",(t,e)=>{Ga.init(t,e),mN.init(t,e),_e.defineLazy(t,"shape",()=>e.shape)})});var mx=L(()=>{});var fx=L(()=>{});var gx=L(()=>{});var yx=L(()=>{wt();hh();hx();mx();wt();Ya();fx();gx()});var bx=L(()=>{yx()});var fh=L(()=>{bx()});function kr(t){return!!t._zod}function Kn(t){let e=Object.values(t);if(e.length===0)return mh({});let r=e.every(kr),n=e.every(o=>!kr(o));if(r)return mh(t);if(n)return nu(t);throw new Error("Mixed Zod versions detected in object shape.")}function on(t,e){return kr(t)?Bn(t,e):t.safeParse(e)}async function sc(t,e){return kr(t)?await Zn(t,e):await t.safeParseAsync(e)}function sn(t){if(!t)return;let e;if(kr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function jo(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 Kn(t)}}if(kr(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 bN(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ic(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 ${bN(e.path)}`:e.message).join(`
2479
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function _x(t){return t.description}function vx(t){if(kr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function zo(t){if(kr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Hs=L(()=>{Os();fh()});var gh=L(()=>{wt()});var Ks={};ls(Ks,{ZodISODate:()=>kx,ZodISODateTime:()=>xx,ZodISODuration:()=>$x,ZodISOTime:()=>Sx,date:()=>bh,datetime:()=>yh,duration:()=>_h,time:()=>wh});function yh(t){return ox(xx,t)}function bh(t){return sx(kx,t)}function wh(t){return ix(Sx,t)}function _h(t){return ax($x,t)}var xx,kx,Sx,$x,vh=L(()=>{wt();xh();xx=N("ZodISODateTime",(t,e)=>{Gv.init(t,e),Ze.init(t,e)});kx=N("ZodISODate",(t,e)=>{Jv.init(t,e),Ze.init(t,e)});Sx=N("ZodISOTime",(t,e)=>{Yv.init(t,e),Ze.init(t,e)});$x=N("ZodISODuration",(t,e)=>{Xv.init(t,e),Ze.init(t,e)})});var Tx,UH,Ws,kh=L(()=>{wt();wt();Tx=(t,e)=>{Fa.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>xd(t,r)},flatten:{value:r=>vd(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},UH=N("ZodError",Tx),Ws=N("ZodError",Tx,{Parent:Error})});var Rx,Ex,Px,Ax,Sh=L(()=>{wt();kh();Rx=Sd(Ws),Ex=Td(Ws),Px=Ed(Ws),Ax=Pd(Ws)});function C(t){return Tp(TN,t)}function Pe(t){return Wp(Lx,t)}function Ix(t){return Gp(ZN,t)}function st(t){return Jp(VN,t)}function jx(t){return Yp(HN,t)}function Ve(){return Xp(KN)}function GN(t){return Qp(WN,t)}function ve(t,e){return cx(JN,t,e)}function W(t,e){let r={type:"object",get shape(){return _e.assignProp(this,"shape",{...t}),this.shape},..._e.normalizeParams(e)};return new zx(r)}function _t(t,e){return new zx({type:"object",get shape(){return _e.assignProp(this,"shape",{...t}),this.shape},catchall:Ve(),..._e.normalizeParams(e)})}function Me(t,e){return new Dx({type:"union",options:t,..._e.normalizeParams(e)})}function Rh(t,e,r){return new YN({type:"union",options:e,discriminator:t,..._e.normalizeParams(r)})}function cc(t,e){return new XN({type:"intersection",left:t,right:e})}function ze(t,e,r){return new QN({type:"record",keyType:t,valueType:e,..._e.normalizeParams(r)})}function At(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new $h({type:"enum",entries:r,..._e.normalizeParams(e)})}function ee(t,e){return new eL({type:"literal",values:Array.isArray(t)?t:[t],..._e.normalizeParams(e)})}function Mx(t){return new tL({type:"transform",transform:t})}function He(t){return new Ux({type:"optional",innerType:t})}function Ox(t){return new rL({type:"nullable",innerType:t})}function oL(t,e){return new nL({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function iL(t,e){return new sL({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function aL(t,e){return new qx({type:"nonoptional",innerType:t,..._e.normalizeParams(e)})}function lL(t,e){return new cL({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Th(t,e){return new uL({type:"pipe",in:t,out:e})}function pL(t){return new dL({type:"readonly",innerType:t})}function hL(t){let e=new lt({check:"custom"});return e._zod.check=t,e}function Bx(t,e){return uh(Fx,t??(()=>!0),e)}function mL(t,e={}){return dh(Fx,t,e)}function fL(t){let e=hL(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(_e.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(_e.issue(o))}},t(r.value,r)));return e}function Eh(t,e){return Th(Mx(t),e)}var We,Nx,TN,Ze,RN,Cx,ac,EN,PN,AN,CN,IN,ON,NN,LN,jN,zN,DN,MN,UN,qN,FN,BN,Lx,ZN,VN,HN,KN,WN,JN,zx,Dx,YN,XN,QN,$h,eL,tL,Ux,rL,nL,sL,qx,cL,uL,dL,Fx,xh=L(()=>{wt();wt();gh();vh();Sh();We=N("ZodType",(t,e)=>(Ae.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)=>Mt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Rx(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Px(t,r,n),t.parseAsync=async(r,n)=>Ex(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ax(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(mL(r,n)),t.superRefine=r=>t.check(fL(r)),t.overwrite=r=>t.check(Vn(r)),t.optional=()=>He(t),t.nullable=()=>Ox(t),t.nullish=()=>He(Ox(t)),t.nonoptional=r=>aL(t,r),t.array=()=>ve(t),t.or=r=>Me([t,r]),t.and=r=>cc(t,r),t.transform=r=>Th(t,Mx(r)),t.default=r=>oL(t,r),t.prefault=r=>iL(t,r),t.catch=r=>lL(t,r),t.pipe=r=>Th(t,r),t.readonly=()=>pL(t),t.describe=r=>{let n=t.clone();return nn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return nn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return nn.get(t);let n=t.clone();return nn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Nx=N("_ZodString",(t,e)=>{Fs.init(t,e),We.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(eh(...n)),t.includes=(...n)=>t.check(nh(...n)),t.startsWith=(...n)=>t.check(oh(...n)),t.endsWith=(...n)=>t.check(sh(...n)),t.min=(...n)=>t.check(Lo(...n)),t.max=(...n)=>t.check(rc(...n)),t.length=(...n)=>t.check(nc(...n)),t.nonempty=(...n)=>t.check(Lo(1,...n)),t.lowercase=n=>t.check(th(n)),t.uppercase=n=>t.check(rh(n)),t.trim=()=>t.check(ah()),t.normalize=(...n)=>t.check(ih(...n)),t.toLowerCase=()=>t.check(ch()),t.toUpperCase=()=>t.check(lh())}),TN=N("ZodString",(t,e)=>{Fs.init(t,e),Nx.init(t,e),t.email=r=>t.check(Rp(RN,r)),t.url=r=>t.check(Ip(EN,r)),t.jwt=r=>t.check(Kp(BN,r)),t.emoji=r=>t.check(Op(PN,r)),t.guid=r=>t.check(Xa(Cx,r)),t.uuid=r=>t.check(Ep(ac,r)),t.uuidv4=r=>t.check(Pp(ac,r)),t.uuidv6=r=>t.check(Ap(ac,r)),t.uuidv7=r=>t.check(Cp(ac,r)),t.nanoid=r=>t.check(Np(AN,r)),t.guid=r=>t.check(Xa(Cx,r)),t.cuid=r=>t.check(Lp(CN,r)),t.cuid2=r=>t.check(jp(IN,r)),t.ulid=r=>t.check(zp(ON,r)),t.base64=r=>t.check(Zp(UN,r)),t.base64url=r=>t.check(Vp(qN,r)),t.xid=r=>t.check(Dp(NN,r)),t.ksuid=r=>t.check(Mp(LN,r)),t.ipv4=r=>t.check(Up(jN,r)),t.ipv6=r=>t.check(qp(zN,r)),t.cidrv4=r=>t.check(Fp(DN,r)),t.cidrv6=r=>t.check(Bp(MN,r)),t.e164=r=>t.check(Hp(FN,r)),t.datetime=r=>t.check(yh(r)),t.date=r=>t.check(bh(r)),t.time=r=>t.check(wh(r)),t.duration=r=>t.check(_h(r))});Ze=N("ZodStringFormat",(t,e)=>{je.init(t,e),Nx.init(t,e)}),RN=N("ZodEmail",(t,e)=>{Ud.init(t,e),Ze.init(t,e)}),Cx=N("ZodGUID",(t,e)=>{Dd.init(t,e),Ze.init(t,e)}),ac=N("ZodUUID",(t,e)=>{Md.init(t,e),Ze.init(t,e)}),EN=N("ZodURL",(t,e)=>{qd.init(t,e),Ze.init(t,e)}),PN=N("ZodEmoji",(t,e)=>{Fd.init(t,e),Ze.init(t,e)}),AN=N("ZodNanoID",(t,e)=>{Bd.init(t,e),Ze.init(t,e)}),CN=N("ZodCUID",(t,e)=>{Zd.init(t,e),Ze.init(t,e)}),IN=N("ZodCUID2",(t,e)=>{Vd.init(t,e),Ze.init(t,e)}),ON=N("ZodULID",(t,e)=>{Hd.init(t,e),Ze.init(t,e)}),NN=N("ZodXID",(t,e)=>{Kd.init(t,e),Ze.init(t,e)}),LN=N("ZodKSUID",(t,e)=>{Wd.init(t,e),Ze.init(t,e)}),jN=N("ZodIPv4",(t,e)=>{Gd.init(t,e),Ze.init(t,e)}),zN=N("ZodIPv6",(t,e)=>{Jd.init(t,e),Ze.init(t,e)}),DN=N("ZodCIDRv4",(t,e)=>{Yd.init(t,e),Ze.init(t,e)}),MN=N("ZodCIDRv6",(t,e)=>{Xd.init(t,e),Ze.init(t,e)}),UN=N("ZodBase64",(t,e)=>{Qd.init(t,e),Ze.init(t,e)}),qN=N("ZodBase64URL",(t,e)=>{ep.init(t,e),Ze.init(t,e)}),FN=N("ZodE164",(t,e)=>{tp.init(t,e),Ze.init(t,e)}),BN=N("ZodJWT",(t,e)=>{rp.init(t,e),Ze.init(t,e)}),Lx=N("ZodNumber",(t,e)=>{Wa.init(t,e),We.init(t,e),t.gt=(n,o)=>t.check(ec(n,o)),t.gte=(n,o)=>t.check(Vs(n,o)),t.min=(n,o)=>t.check(Vs(n,o)),t.lt=(n,o)=>t.check(Qa(n,o)),t.lte=(n,o)=>t.check(Zs(n,o)),t.max=(n,o)=>t.check(Zs(n,o)),t.int=n=>t.check(Ix(n)),t.safe=n=>t.check(Ix(n)),t.positive=n=>t.check(ec(0,n)),t.nonnegative=n=>t.check(Vs(0,n)),t.negative=n=>t.check(Qa(0,n)),t.nonpositive=n=>t.check(Zs(0,n)),t.multipleOf=(n,o)=>t.check(tc(n,o)),t.step=(n,o)=>t.check(tc(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});ZN=N("ZodNumberFormat",(t,e)=>{np.init(t,e),Lx.init(t,e)});VN=N("ZodBoolean",(t,e)=>{op.init(t,e),We.init(t,e)});HN=N("ZodNull",(t,e)=>{sp.init(t,e),We.init(t,e)});KN=N("ZodUnknown",(t,e)=>{ip.init(t,e),We.init(t,e)});WN=N("ZodNever",(t,e)=>{ap.init(t,e),We.init(t,e)});JN=N("ZodArray",(t,e)=>{cp.init(t,e),We.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Lo(r,n)),t.nonempty=r=>t.check(Lo(1,r)),t.max=(r,n)=>t.check(rc(r,n)),t.length=(r,n)=>t.check(nc(r,n)),t.unwrap=()=>t.element});zx=N("ZodObject",(t,e)=>{Ga.init(t,e),We.init(t,e),_e.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>At(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ve()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ve()}),t.strict=()=>t.clone({...t._zod.def,catchall:GN()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>_e.extend(t,r),t.merge=r=>_e.merge(t,r),t.pick=r=>_e.pick(t,r),t.omit=r=>_e.omit(t,r),t.partial=(...r)=>_e.partial(Ux,t,r[0]),t.required=(...r)=>_e.required(qx,t,r[0])});Dx=N("ZodUnion",(t,e)=>{Ja.init(t,e),We.init(t,e),t.options=e.options});YN=N("ZodDiscriminatedUnion",(t,e)=>{Dx.init(t,e),lp.init(t,e)});XN=N("ZodIntersection",(t,e)=>{up.init(t,e),We.init(t,e)});QN=N("ZodRecord",(t,e)=>{dp.init(t,e),We.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});$h=N("ZodEnum",(t,e)=>{pp.init(t,e),We.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 $h({...e,checks:[],..._e.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 $h({...e,checks:[],..._e.normalizeParams(o),entries:s})}});eL=N("ZodLiteral",(t,e)=>{hp.init(t,e),We.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]}})});tL=N("ZodTransform",(t,e)=>{mp.init(t,e),We.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(_e.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(_e.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Ux=N("ZodOptional",(t,e)=>{fp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});rL=N("ZodNullable",(t,e)=>{gp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});nL=N("ZodDefault",(t,e)=>{yp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});sL=N("ZodPrefault",(t,e)=>{bp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});qx=N("ZodNonOptional",(t,e)=>{wp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});cL=N("ZodCatch",(t,e)=>{_p.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});uL=N("ZodPipe",(t,e)=>{vp.init(t,e),We.init(t,e),t.in=e.in,t.out=e.out});dL=N("ZodReadonly",(t,e)=>{xp.init(t,e),We.init(t,e)});Fx=N("ZodCustom",(t,e)=>{kp.init(t,e),We.init(t,e)})});var Zx=L(()=>{});var Vx=L(()=>{});var Hx=L(()=>{wt();xh();gh();kh();Sh();Zx();wt();rx();Ya();vh();Vx();Dt(tx())});var Kx=L(()=>{Hx()});var Wx=L(()=>{Kx()});function dk(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function pk(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ah,Gx,an,uc,tt,Jx,Yx,r9,bL,wL,Ch,Ut,Gs,Xx,ut,Wt,Gt,dt,dc,Qx,Ih,ek,tk,Oh,Js,Q,Nh,rk,nk,n9,pc,_L,hc,vL,Ys,Do,ok,xL,kL,SL,$L,TL,RL,Lh,EL,PL,jh,mc,AL,CL,fc,IL,Xs,Qs,OL,ei,Mo,NL,ti,gc,yc,bc,o9,wc,_c,vc,sk,ik,ak,zh,ck,ri,Uo,lk,LL,xc,jL,kc,zL,Dh,DL,Sc,ML,UL,qL,FL,BL,ZL,VL,HL,KL,WL,$c,GL,JL,Tc,Mh,Uh,qh,YL,XL,QL,Fh,ej,tj,rj,nj,oj,uk,Rc,sj,Ec,s9,ij,qo,aj,i9,ni,cj,Bh,lj,uj,dj,pj,hj,mj,fj,lc,gj,yj,bj,oi,Zh,wj,_j,vj,xj,kj,Sj,$j,Tj,Rj,Ej,Pj,Aj,Cj,Ij,Oj,Nj,Lj,jj,Fo,zj,Dj,Mj,Pc,Uj,qj,Fj,Vh,Bj,a9,c9,l9,u9,d9,p9,J,Ph,Bo=L(()=>{Wx();Ah="2025-11-25",Gx=[Ah,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],an="io.modelcontextprotocol/related-task",uc="2.0",tt=Bx(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Jx=Me([C(),Pe().int()]),Yx=C(),r9=_t({ttl:Pe().optional(),pollInterval:Pe().optional()}),bL=W({ttl:Pe().optional()}),wL=W({taskId:C()}),Ch=_t({progressToken:Jx.optional(),[an]:wL.optional()}),Ut=W({_meta:Ch.optional()}),Gs=Ut.extend({task:bL.optional()}),Xx=t=>Gs.safeParse(t).success,ut=W({method:C(),params:Ut.loose().optional()}),Wt=W({_meta:Ch.optional()}),Gt=W({method:C(),params:Wt.loose().optional()}),dt=_t({_meta:Ch.optional()}),dc=Me([C(),Pe().int()]),Qx=W({jsonrpc:ee(uc),id:dc,...ut.shape}).strict(),Ih=t=>Qx.safeParse(t).success,ek=W({jsonrpc:ee(uc),...Gt.shape}).strict(),tk=t=>ek.safeParse(t).success,Oh=W({jsonrpc:ee(uc),id:dc,result:dt}).strict(),Js=t=>Oh.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"})(Q||(Q={}));Nh=W({jsonrpc:ee(uc),id:dc.optional(),error:W({code:Pe().int(),message:C(),data:Ve().optional()})}).strict(),rk=t=>Nh.safeParse(t).success,nk=Me([Qx,ek,Oh,Nh]),n9=Me([Oh,Nh]),pc=dt.strict(),_L=Wt.extend({requestId:dc.optional(),reason:C().optional()}),hc=Gt.extend({method:ee("notifications/cancelled"),params:_L}),vL=W({src:C(),mimeType:C().optional(),sizes:ve(C()).optional(),theme:At(["light","dark"]).optional()}),Ys=W({icons:ve(vL).optional()}),Do=W({name:C(),title:C().optional()}),ok=Do.extend({...Do.shape,...Ys.shape,version:C(),websiteUrl:C().optional(),description:C().optional()}),xL=cc(W({applyDefaults:st().optional()}),ze(C(),Ve())),kL=Eh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,cc(W({form:xL.optional(),url:tt.optional()}),ze(C(),Ve()).optional())),SL=_t({list:tt.optional(),cancel:tt.optional(),requests:_t({sampling:_t({createMessage:tt.optional()}).optional(),elicitation:_t({create:tt.optional()}).optional()}).optional()}),$L=_t({list:tt.optional(),cancel:tt.optional(),requests:_t({tools:_t({call:tt.optional()}).optional()}).optional()}),TL=W({experimental:ze(C(),tt).optional(),sampling:W({context:tt.optional(),tools:tt.optional()}).optional(),elicitation:kL.optional(),roots:W({listChanged:st().optional()}).optional(),tasks:SL.optional(),extensions:ze(C(),tt).optional()}),RL=Ut.extend({protocolVersion:C(),capabilities:TL,clientInfo:ok}),Lh=ut.extend({method:ee("initialize"),params:RL}),EL=W({experimental:ze(C(),tt).optional(),logging:tt.optional(),completions:tt.optional(),prompts:W({listChanged:st().optional()}).optional(),resources:W({subscribe:st().optional(),listChanged:st().optional()}).optional(),tools:W({listChanged:st().optional()}).optional(),tasks:$L.optional(),extensions:ze(C(),tt).optional()}),PL=dt.extend({protocolVersion:C(),capabilities:EL,serverInfo:ok,instructions:C().optional()}),jh=Gt.extend({method:ee("notifications/initialized"),params:Wt.optional()}),mc=ut.extend({method:ee("ping"),params:Ut.optional()}),AL=W({progress:Pe(),total:He(Pe()),message:He(C())}),CL=W({...Wt.shape,...AL.shape,progressToken:Jx}),fc=Gt.extend({method:ee("notifications/progress"),params:CL}),IL=Ut.extend({cursor:Yx.optional()}),Xs=ut.extend({params:IL.optional()}),Qs=dt.extend({nextCursor:Yx.optional()}),OL=At(["working","input_required","completed","failed","cancelled"]),ei=W({taskId:C(),status:OL,ttl:Me([Pe(),jx()]),createdAt:C(),lastUpdatedAt:C(),pollInterval:He(Pe()),statusMessage:He(C())}),Mo=dt.extend({task:ei}),NL=Wt.merge(ei),ti=Gt.extend({method:ee("notifications/tasks/status"),params:NL}),gc=ut.extend({method:ee("tasks/get"),params:Ut.extend({taskId:C()})}),yc=dt.merge(ei),bc=ut.extend({method:ee("tasks/result"),params:Ut.extend({taskId:C()})}),o9=dt.loose(),wc=Xs.extend({method:ee("tasks/list")}),_c=Qs.extend({tasks:ve(ei)}),vc=ut.extend({method:ee("tasks/cancel"),params:Ut.extend({taskId:C()})}),sk=dt.merge(ei),ik=W({uri:C(),mimeType:He(C()),_meta:ze(C(),Ve()).optional()}),ak=ik.extend({text:C()}),zh=C().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ck=ik.extend({blob:zh}),ri=At(["user","assistant"]),Uo=W({audience:ve(ri).optional(),priority:Pe().min(0).max(1).optional(),lastModified:Ks.datetime({offset:!0}).optional()}),lk=W({...Do.shape,...Ys.shape,uri:C(),description:He(C()),mimeType:He(C()),size:He(Pe()),annotations:Uo.optional(),_meta:He(_t({}))}),LL=W({...Do.shape,...Ys.shape,uriTemplate:C(),description:He(C()),mimeType:He(C()),annotations:Uo.optional(),_meta:He(_t({}))}),xc=Xs.extend({method:ee("resources/list")}),jL=Qs.extend({resources:ve(lk)}),kc=Xs.extend({method:ee("resources/templates/list")}),zL=Qs.extend({resourceTemplates:ve(LL)}),Dh=Ut.extend({uri:C()}),DL=Dh,Sc=ut.extend({method:ee("resources/read"),params:DL}),ML=dt.extend({contents:ve(Me([ak,ck]))}),UL=Gt.extend({method:ee("notifications/resources/list_changed"),params:Wt.optional()}),qL=Dh,FL=ut.extend({method:ee("resources/subscribe"),params:qL}),BL=Dh,ZL=ut.extend({method:ee("resources/unsubscribe"),params:BL}),VL=Wt.extend({uri:C()}),HL=Gt.extend({method:ee("notifications/resources/updated"),params:VL}),KL=W({name:C(),description:He(C()),required:He(st())}),WL=W({...Do.shape,...Ys.shape,description:He(C()),arguments:He(ve(KL)),_meta:He(_t({}))}),$c=Xs.extend({method:ee("prompts/list")}),GL=Qs.extend({prompts:ve(WL)}),JL=Ut.extend({name:C(),arguments:ze(C(),C()).optional()}),Tc=ut.extend({method:ee("prompts/get"),params:JL}),Mh=W({type:ee("text"),text:C(),annotations:Uo.optional(),_meta:ze(C(),Ve()).optional()}),Uh=W({type:ee("image"),data:zh,mimeType:C(),annotations:Uo.optional(),_meta:ze(C(),Ve()).optional()}),qh=W({type:ee("audio"),data:zh,mimeType:C(),annotations:Uo.optional(),_meta:ze(C(),Ve()).optional()}),YL=W({type:ee("tool_use"),name:C(),id:C(),input:ze(C(),Ve()),_meta:ze(C(),Ve()).optional()}),XL=W({type:ee("resource"),resource:Me([ak,ck]),annotations:Uo.optional(),_meta:ze(C(),Ve()).optional()}),QL=lk.extend({type:ee("resource_link")}),Fh=Me([Mh,Uh,qh,QL,XL]),ej=W({role:ri,content:Fh}),tj=dt.extend({description:C().optional(),messages:ve(ej)}),rj=Gt.extend({method:ee("notifications/prompts/list_changed"),params:Wt.optional()}),nj=W({title:C().optional(),readOnlyHint:st().optional(),destructiveHint:st().optional(),idempotentHint:st().optional(),openWorldHint:st().optional()}),oj=W({taskSupport:At(["required","optional","forbidden"]).optional()}),uk=W({...Do.shape,...Ys.shape,description:C().optional(),inputSchema:W({type:ee("object"),properties:ze(C(),tt).optional(),required:ve(C()).optional()}).catchall(Ve()),outputSchema:W({type:ee("object"),properties:ze(C(),tt).optional(),required:ve(C()).optional()}).catchall(Ve()).optional(),annotations:nj.optional(),execution:oj.optional(),_meta:ze(C(),Ve()).optional()}),Rc=Xs.extend({method:ee("tools/list")}),sj=Qs.extend({tools:ve(uk)}),Ec=dt.extend({content:ve(Fh).default([]),structuredContent:ze(C(),Ve()).optional(),isError:st().optional()}),s9=Ec.or(dt.extend({toolResult:Ve()})),ij=Gs.extend({name:C(),arguments:ze(C(),Ve()).optional()}),qo=ut.extend({method:ee("tools/call"),params:ij}),aj=Gt.extend({method:ee("notifications/tools/list_changed"),params:Wt.optional()}),i9=W({autoRefresh:st().default(!0),debounceMs:Pe().int().nonnegative().default(300)}),ni=At(["debug","info","notice","warning","error","critical","alert","emergency"]),cj=Ut.extend({level:ni}),Bh=ut.extend({method:ee("logging/setLevel"),params:cj}),lj=Wt.extend({level:ni,logger:C().optional(),data:Ve()}),uj=Gt.extend({method:ee("notifications/message"),params:lj}),dj=W({name:C().optional()}),pj=W({hints:ve(dj).optional(),costPriority:Pe().min(0).max(1).optional(),speedPriority:Pe().min(0).max(1).optional(),intelligencePriority:Pe().min(0).max(1).optional()}),hj=W({mode:At(["auto","required","none"]).optional()}),mj=W({type:ee("tool_result"),toolUseId:C().describe("The unique identifier for the corresponding tool call."),content:ve(Fh).default([]),structuredContent:W({}).loose().optional(),isError:st().optional(),_meta:ze(C(),Ve()).optional()}),fj=Rh("type",[Mh,Uh,qh]),lc=Rh("type",[Mh,Uh,qh,YL,mj]),gj=W({role:ri,content:Me([lc,ve(lc)]),_meta:ze(C(),Ve()).optional()}),yj=Gs.extend({messages:ve(gj),modelPreferences:pj.optional(),systemPrompt:C().optional(),includeContext:At(["none","thisServer","allServers"]).optional(),temperature:Pe().optional(),maxTokens:Pe().int(),stopSequences:ve(C()).optional(),metadata:tt.optional(),tools:ve(uk).optional(),toolChoice:hj.optional()}),bj=ut.extend({method:ee("sampling/createMessage"),params:yj}),oi=dt.extend({model:C(),stopReason:He(At(["endTurn","stopSequence","maxTokens"]).or(C())),role:ri,content:fj}),Zh=dt.extend({model:C(),stopReason:He(At(["endTurn","stopSequence","maxTokens","toolUse"]).or(C())),role:ri,content:Me([lc,ve(lc)])}),wj=W({type:ee("boolean"),title:C().optional(),description:C().optional(),default:st().optional()}),_j=W({type:ee("string"),title:C().optional(),description:C().optional(),minLength:Pe().optional(),maxLength:Pe().optional(),format:At(["email","uri","date","date-time"]).optional(),default:C().optional()}),vj=W({type:At(["number","integer"]),title:C().optional(),description:C().optional(),minimum:Pe().optional(),maximum:Pe().optional(),default:Pe().optional()}),xj=W({type:ee("string"),title:C().optional(),description:C().optional(),enum:ve(C()),default:C().optional()}),kj=W({type:ee("string"),title:C().optional(),description:C().optional(),oneOf:ve(W({const:C(),title:C()})),default:C().optional()}),Sj=W({type:ee("string"),title:C().optional(),description:C().optional(),enum:ve(C()),enumNames:ve(C()).optional(),default:C().optional()}),$j=Me([xj,kj]),Tj=W({type:ee("array"),title:C().optional(),description:C().optional(),minItems:Pe().optional(),maxItems:Pe().optional(),items:W({type:ee("string"),enum:ve(C())}),default:ve(C()).optional()}),Rj=W({type:ee("array"),title:C().optional(),description:C().optional(),minItems:Pe().optional(),maxItems:Pe().optional(),items:W({anyOf:ve(W({const:C(),title:C()}))}),default:ve(C()).optional()}),Ej=Me([Tj,Rj]),Pj=Me([Sj,$j,Ej]),Aj=Me([Pj,wj,_j,vj]),Cj=Gs.extend({mode:ee("form").optional(),message:C(),requestedSchema:W({type:ee("object"),properties:ze(C(),Aj),required:ve(C()).optional()})}),Ij=Gs.extend({mode:ee("url"),message:C(),elicitationId:C(),url:C().url()}),Oj=Me([Cj,Ij]),Nj=ut.extend({method:ee("elicitation/create"),params:Oj}),Lj=Wt.extend({elicitationId:C()}),jj=Gt.extend({method:ee("notifications/elicitation/complete"),params:Lj}),Fo=dt.extend({action:At(["accept","decline","cancel"]),content:Eh(t=>t===null?void 0:t,ze(C(),Me([C(),Pe(),st(),ve(C())])).optional())}),zj=W({type:ee("ref/resource"),uri:C()}),Dj=W({type:ee("ref/prompt"),name:C()}),Mj=Ut.extend({ref:Me([Dj,zj]),argument:W({name:C(),value:C()}),context:W({arguments:ze(C(),C()).optional()}).optional()}),Pc=ut.extend({method:ee("completion/complete"),params:Mj});Uj=dt.extend({completion:_t({values:ve(C()).max(100),total:He(Pe().int()),hasMore:He(st())})}),qj=W({uri:C().startsWith("file://"),name:C().optional(),_meta:ze(C(),Ve()).optional()}),Fj=ut.extend({method:ee("roots/list"),params:Ut.optional()}),Vh=dt.extend({roots:ve(qj)}),Bj=Gt.extend({method:ee("notifications/roots/list_changed"),params:Wt.optional()}),a9=Me([mc,Lh,Pc,Bh,Tc,$c,xc,kc,Sc,FL,ZL,qo,Rc,gc,bc,wc,vc]),c9=Me([hc,fc,jh,Bj,ti]),l9=Me([pc,oi,Zh,Fo,Vh,yc,_c,Mo]),u9=Me([mc,bj,Nj,Fj,gc,bc,wc,vc]),d9=Me([hc,fc,uj,HL,UL,aj,rj,ti,jj]),p9=Me([pc,PL,Uj,tj,GL,jL,zL,ML,Ec,sj,yc,_c,Mo]),J=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===Q.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ph(o.elicitations,r)}return new t(e,r,n)}},Ph=class extends J{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Q.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function cn(t){return t==="completed"||t==="failed"||t==="cancelled"}var hk=L(()=>{});var fk,mk,gk,Ac=L(()=>{fk=Symbol("Let zodToJsonSchema decide on which parser to use"),mk={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"},gk=t=>typeof t=="string"?{...mk,name:t}:{...mk,...t}});var yk,Hh=L(()=>{Ac();yk=t=>{let e=gk(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 Kh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,o){t[e]=r,Kh(t,e,n,o)}var ln=L(()=>{});var Cc,Ic=L(()=>{Cc=(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 Ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Cc(e,t.currentPath):e.join("/")}}var Jt=L(()=>{Ic()});function bk(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==U.ZodAny&&(r.items=ce(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&xe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(r,"minItems",t.exactLength.value,t.exactLength.message,e),xe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Wh=L(()=>{Os();ln();Xe()});function wk(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?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var Gh=L(()=>{ln()});function _k(){return{type:"boolean"}}var Jh=L(()=>{});function Oc(t,e){return ce(t.type._def,e)}var Nc=L(()=>{Xe()});var vk,Yh=L(()=>{Xe();vk=(t,e)=>ce(t.innerType._def,e)});function Xh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Xh(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 Zj(t,e)}}var Zj,Qh=L(()=>{ln();Zj=(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":xe(r,"minimum",n.value,n.message,e);break;case"max":xe(r,"maximum",n.value,n.message,e);break}return r}});function xk(t,e){return{...ce(t.innerType._def,e),default:t.defaultValue()}}var em=L(()=>{Xe()});function kk(t,e){return e.effectStrategy==="input"?ce(t.schema._def,e):Ke(e)}var tm=L(()=>{Xe();Jt()});function Sk(t){return{type:"string",enum:Array.from(t.values)}}var rm=L(()=>{});function $k(t,e){let r=[ce(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ce(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(Vj(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 Vj,nm=L(()=>{Xe();Vj=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Tk(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 om=L(()=>{});function Lc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":xe(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":lr(r,"email",n.message,e);break;case"format:idn-email":lr(r,"idn-email",n.message,e);break;case"pattern:zod":vt(r,cr.email,n.message,e);break}break;case"url":lr(r,"uri",n.message,e);break;case"uuid":lr(r,"uuid",n.message,e);break;case"regex":vt(r,n.regex,n.message,e);break;case"cuid":vt(r,cr.cuid,n.message,e);break;case"cuid2":vt(r,cr.cuid2,n.message,e);break;case"startsWith":vt(r,RegExp(`^${im(n.value,e)}`),n.message,e);break;case"endsWith":vt(r,RegExp(`${im(n.value,e)}$`),n.message,e);break;case"datetime":lr(r,"date-time",n.message,e);break;case"date":lr(r,"date",n.message,e);break;case"time":lr(r,"time",n.message,e);break;case"duration":lr(r,"duration",n.message,e);break;case"length":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{vt(r,RegExp(im(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&lr(r,"ipv4",n.message,e),n.version!=="v4"&&lr(r,"ipv6",n.message,e);break}case"base64url":vt(r,cr.base64url,n.message,e);break;case"jwt":vt(r,cr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&vt(r,cr.ipv4Cidr,n.message,e),n.version!=="v4"&&vt(r,cr.ipv6Cidr,n.message,e);break}case"emoji":vt(r,cr.emoji(),n.message,e);break;case"ulid":{vt(r,cr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{lr(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{vt(r,cr.base64,n.message,e);break}}break}case"nanoid":vt(r,cr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function im(t,e){return e.patternStrategy==="escape"?Kj(t):t}function Kj(t){let e="";for(let r=0;r<t.length;r++)Hj.has(t[r])||(e+="\\"),e+=t[r];return e}function lr(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}}})):xe(t,"format",e,r,n)}function vt(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:Rk(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",Rk(e,n),r,n)}function Rk(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
2509
+ 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 f=n.external.registry.get(u[0])?.id;if(e!==u[0]&&f){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),f=w.def??w.schema,m={...f};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"?(f.allOf=f.allOf??[],f.allOf.push($)):(Object.assign(f,$),Object.assign(f,m))}w.isParent||this.override({zodSchema:u,jsonSchema:f,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 hk=L(()=>{});var wt=L(()=>{Co();Cd();Sd();tk();Va();zd();kr();Za();Ya();Tp();jd();dk();uk();pk();hk()});var mh=L(()=>{wt()});function fh(t,e){let r={type:"object",get shape(){return _e.assignProp(this,"shape",{...t}),this.shape},..._e.normalizeParams(e)};return new gN(r)}var fN,gN,mk=L(()=>{wt();wt();mh();fN=N("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ae.init(t,e),t.def=e,t.parse=(r,n)=>Td(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Bn(t,r,n),t.parseAsync=async(r,n)=>Ed(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Zn(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)=>Mt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),gN=N("ZodMiniObject",(t,e)=>{Ga.init(t,e),fN.init(t,e),_e.defineLazy(t,"shape",()=>e.shape)})});var fk=L(()=>{});var gk=L(()=>{});var yk=L(()=>{});var bk=L(()=>{wt();mh();mk();fk();wt();Ya();gk();yk()});var wk=L(()=>{bk()});var gh=L(()=>{wk()});function xr(t){return!!t._zod}function Kn(t){let e=Object.values(t);if(e.length===0)return fh({});let r=e.every(xr),n=e.every(o=>!xr(o));if(r)return fh(t);if(n)return ou(t);throw new Error("Mixed Zod versions detected in object shape.")}function on(t,e){return xr(t)?Bn(t,e):t.safeParse(e)}async function sc(t,e){return xr(t)?await Zn(t,e):await t.safeParseAsync(e)}function sn(t){if(!t)return;let e;if(xr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Lo(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 Kn(t)}}if(xr(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 wN(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ic(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 ${wN(e.path)}`:e.message).join(`
2510
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function vk(t){return t.description}function kk(t){if(xr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function jo(t){if(xr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Hs=L(()=>{Os();gh()});var yh=L(()=>{wt()});var Ks={};ls(Ks,{ZodISODate:()=>Sk,ZodISODateTime:()=>xk,ZodISODuration:()=>Tk,ZodISOTime:()=>$k,date:()=>wh,datetime:()=>bh,duration:()=>vh,time:()=>_h});function bh(t){return sk(xk,t)}function wh(t){return ik(Sk,t)}function _h(t){return ak($k,t)}function vh(t){return ck(Tk,t)}var xk,Sk,$k,Tk,kh=L(()=>{wt();xh();xk=N("ZodISODateTime",(t,e)=>{Jv.init(t,e),Ze.init(t,e)});Sk=N("ZodISODate",(t,e)=>{Yv.init(t,e),Ze.init(t,e)});$k=N("ZodISOTime",(t,e)=>{Xv.init(t,e),Ze.init(t,e)});Tk=N("ZodISODuration",(t,e)=>{Qv.init(t,e),Ze.init(t,e)})});var Rk,qH,Ws,Sh=L(()=>{wt();wt();Rk=(t,e)=>{Fa.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>xd(t,r)},flatten:{value:r=>kd(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},qH=N("ZodError",Rk),Ws=N("ZodError",Rk,{Parent:Error})});var Ek,Pk,Ak,Ck,$h=L(()=>{wt();Sh();Ek=$d(Ws),Pk=Rd(Ws),Ak=Pd(Ws),Ck=Ad(Ws)});function C(t){return Rp(RN,t)}function Pe(t){return Gp(jk,t)}function Ok(t){return Jp(VN,t)}function st(t){return Yp(HN,t)}function zk(t){return Xp(KN,t)}function Ve(){return Qp(WN)}function JN(t){return eh(GN,t)}function ve(t,e){return lk(YN,t,e)}function W(t,e){let r={type:"object",get shape(){return _e.assignProp(this,"shape",{...t}),this.shape},..._e.normalizeParams(e)};return new Dk(r)}function _t(t,e){return new Dk({type:"object",get shape(){return _e.assignProp(this,"shape",{...t}),this.shape},catchall:Ve(),..._e.normalizeParams(e)})}function Me(t,e){return new Mk({type:"union",options:t,..._e.normalizeParams(e)})}function Eh(t,e,r){return new XN({type:"union",options:e,discriminator:t,..._e.normalizeParams(r)})}function cc(t,e){return new QN({type:"intersection",left:t,right:e})}function ze(t,e,r){return new eL({type:"record",keyType:t,valueType:e,..._e.normalizeParams(r)})}function At(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Th({type:"enum",entries:r,..._e.normalizeParams(e)})}function ee(t,e){return new tL({type:"literal",values:Array.isArray(t)?t:[t],..._e.normalizeParams(e)})}function Uk(t){return new rL({type:"transform",transform:t})}function He(t){return new qk({type:"optional",innerType:t})}function Nk(t){return new nL({type:"nullable",innerType:t})}function sL(t,e){return new oL({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function aL(t,e){return new iL({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function cL(t,e){return new Fk({type:"nonoptional",innerType:t,..._e.normalizeParams(e)})}function uL(t,e){return new lL({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Rh(t,e){return new dL({type:"pipe",in:t,out:e})}function hL(t){return new pL({type:"readonly",innerType:t})}function mL(t){let e=new lt({check:"custom"});return e._zod.check=t,e}function Zk(t,e){return dh(Bk,t??(()=>!0),e)}function fL(t,e={}){return ph(Bk,t,e)}function gL(t){let e=mL(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(_e.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(_e.issue(o))}},t(r.value,r)));return e}function Ph(t,e){return Rh(Uk(t),e)}var We,Lk,RN,Ze,EN,Ik,ac,PN,AN,CN,IN,ON,NN,LN,jN,zN,DN,MN,UN,qN,FN,BN,ZN,jk,VN,HN,KN,WN,GN,YN,Dk,Mk,XN,QN,eL,Th,tL,rL,qk,nL,oL,iL,Fk,lL,dL,pL,Bk,xh=L(()=>{wt();wt();yh();kh();$h();We=N("ZodType",(t,e)=>(Ae.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)=>Mt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Ek(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Ak(t,r,n),t.parseAsync=async(r,n)=>Pk(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ck(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(fL(r,n)),t.superRefine=r=>t.check(gL(r)),t.overwrite=r=>t.check(Vn(r)),t.optional=()=>He(t),t.nullable=()=>Nk(t),t.nullish=()=>He(Nk(t)),t.nonoptional=r=>cL(t,r),t.array=()=>ve(t),t.or=r=>Me([t,r]),t.and=r=>cc(t,r),t.transform=r=>Rh(t,Uk(r)),t.default=r=>sL(t,r),t.prefault=r=>aL(t,r),t.catch=r=>uL(t,r),t.pipe=r=>Rh(t,r),t.readonly=()=>hL(t),t.describe=r=>{let n=t.clone();return nn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return nn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return nn.get(t);let n=t.clone();return nn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Lk=N("_ZodString",(t,e)=>{Fs.init(t,e),We.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(th(...n)),t.includes=(...n)=>t.check(oh(...n)),t.startsWith=(...n)=>t.check(sh(...n)),t.endsWith=(...n)=>t.check(ih(...n)),t.min=(...n)=>t.check(No(...n)),t.max=(...n)=>t.check(rc(...n)),t.length=(...n)=>t.check(nc(...n)),t.nonempty=(...n)=>t.check(No(1,...n)),t.lowercase=n=>t.check(rh(n)),t.uppercase=n=>t.check(nh(n)),t.trim=()=>t.check(ch()),t.normalize=(...n)=>t.check(ah(...n)),t.toLowerCase=()=>t.check(lh()),t.toUpperCase=()=>t.check(uh())}),RN=N("ZodString",(t,e)=>{Fs.init(t,e),Lk.init(t,e),t.email=r=>t.check(Ep(EN,r)),t.url=r=>t.check(Op(PN,r)),t.jwt=r=>t.check(Wp(ZN,r)),t.emoji=r=>t.check(Np(AN,r)),t.guid=r=>t.check(Xa(Ik,r)),t.uuid=r=>t.check(Pp(ac,r)),t.uuidv4=r=>t.check(Ap(ac,r)),t.uuidv6=r=>t.check(Cp(ac,r)),t.uuidv7=r=>t.check(Ip(ac,r)),t.nanoid=r=>t.check(Lp(CN,r)),t.guid=r=>t.check(Xa(Ik,r)),t.cuid=r=>t.check(jp(IN,r)),t.cuid2=r=>t.check(zp(ON,r)),t.ulid=r=>t.check(Dp(NN,r)),t.base64=r=>t.check(Vp(qN,r)),t.base64url=r=>t.check(Hp(FN,r)),t.xid=r=>t.check(Mp(LN,r)),t.ksuid=r=>t.check(Up(jN,r)),t.ipv4=r=>t.check(qp(zN,r)),t.ipv6=r=>t.check(Fp(DN,r)),t.cidrv4=r=>t.check(Bp(MN,r)),t.cidrv6=r=>t.check(Zp(UN,r)),t.e164=r=>t.check(Kp(BN,r)),t.datetime=r=>t.check(bh(r)),t.date=r=>t.check(wh(r)),t.time=r=>t.check(_h(r)),t.duration=r=>t.check(vh(r))});Ze=N("ZodStringFormat",(t,e)=>{je.init(t,e),Lk.init(t,e)}),EN=N("ZodEmail",(t,e)=>{qd.init(t,e),Ze.init(t,e)}),Ik=N("ZodGUID",(t,e)=>{Md.init(t,e),Ze.init(t,e)}),ac=N("ZodUUID",(t,e)=>{Ud.init(t,e),Ze.init(t,e)}),PN=N("ZodURL",(t,e)=>{Fd.init(t,e),Ze.init(t,e)}),AN=N("ZodEmoji",(t,e)=>{Bd.init(t,e),Ze.init(t,e)}),CN=N("ZodNanoID",(t,e)=>{Zd.init(t,e),Ze.init(t,e)}),IN=N("ZodCUID",(t,e)=>{Vd.init(t,e),Ze.init(t,e)}),ON=N("ZodCUID2",(t,e)=>{Hd.init(t,e),Ze.init(t,e)}),NN=N("ZodULID",(t,e)=>{Kd.init(t,e),Ze.init(t,e)}),LN=N("ZodXID",(t,e)=>{Wd.init(t,e),Ze.init(t,e)}),jN=N("ZodKSUID",(t,e)=>{Gd.init(t,e),Ze.init(t,e)}),zN=N("ZodIPv4",(t,e)=>{Jd.init(t,e),Ze.init(t,e)}),DN=N("ZodIPv6",(t,e)=>{Yd.init(t,e),Ze.init(t,e)}),MN=N("ZodCIDRv4",(t,e)=>{Xd.init(t,e),Ze.init(t,e)}),UN=N("ZodCIDRv6",(t,e)=>{Qd.init(t,e),Ze.init(t,e)}),qN=N("ZodBase64",(t,e)=>{ep.init(t,e),Ze.init(t,e)}),FN=N("ZodBase64URL",(t,e)=>{tp.init(t,e),Ze.init(t,e)}),BN=N("ZodE164",(t,e)=>{rp.init(t,e),Ze.init(t,e)}),ZN=N("ZodJWT",(t,e)=>{np.init(t,e),Ze.init(t,e)}),jk=N("ZodNumber",(t,e)=>{Wa.init(t,e),We.init(t,e),t.gt=(n,o)=>t.check(ec(n,o)),t.gte=(n,o)=>t.check(Vs(n,o)),t.min=(n,o)=>t.check(Vs(n,o)),t.lt=(n,o)=>t.check(Qa(n,o)),t.lte=(n,o)=>t.check(Zs(n,o)),t.max=(n,o)=>t.check(Zs(n,o)),t.int=n=>t.check(Ok(n)),t.safe=n=>t.check(Ok(n)),t.positive=n=>t.check(ec(0,n)),t.nonnegative=n=>t.check(Vs(0,n)),t.negative=n=>t.check(Qa(0,n)),t.nonpositive=n=>t.check(Zs(0,n)),t.multipleOf=(n,o)=>t.check(tc(n,o)),t.step=(n,o)=>t.check(tc(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});VN=N("ZodNumberFormat",(t,e)=>{op.init(t,e),jk.init(t,e)});HN=N("ZodBoolean",(t,e)=>{sp.init(t,e),We.init(t,e)});KN=N("ZodNull",(t,e)=>{ip.init(t,e),We.init(t,e)});WN=N("ZodUnknown",(t,e)=>{ap.init(t,e),We.init(t,e)});GN=N("ZodNever",(t,e)=>{cp.init(t,e),We.init(t,e)});YN=N("ZodArray",(t,e)=>{lp.init(t,e),We.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(No(r,n)),t.nonempty=r=>t.check(No(1,r)),t.max=(r,n)=>t.check(rc(r,n)),t.length=(r,n)=>t.check(nc(r,n)),t.unwrap=()=>t.element});Dk=N("ZodObject",(t,e)=>{Ga.init(t,e),We.init(t,e),_e.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>At(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ve()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ve()}),t.strict=()=>t.clone({...t._zod.def,catchall:JN()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>_e.extend(t,r),t.merge=r=>_e.merge(t,r),t.pick=r=>_e.pick(t,r),t.omit=r=>_e.omit(t,r),t.partial=(...r)=>_e.partial(qk,t,r[0]),t.required=(...r)=>_e.required(Fk,t,r[0])});Mk=N("ZodUnion",(t,e)=>{Ja.init(t,e),We.init(t,e),t.options=e.options});XN=N("ZodDiscriminatedUnion",(t,e)=>{Mk.init(t,e),up.init(t,e)});QN=N("ZodIntersection",(t,e)=>{dp.init(t,e),We.init(t,e)});eL=N("ZodRecord",(t,e)=>{pp.init(t,e),We.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Th=N("ZodEnum",(t,e)=>{hp.init(t,e),We.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 Th({...e,checks:[],..._e.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 Th({...e,checks:[],..._e.normalizeParams(o),entries:s})}});tL=N("ZodLiteral",(t,e)=>{mp.init(t,e),We.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]}})});rL=N("ZodTransform",(t,e)=>{fp.init(t,e),We.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(_e.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(_e.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});qk=N("ZodOptional",(t,e)=>{gp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});nL=N("ZodNullable",(t,e)=>{yp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});oL=N("ZodDefault",(t,e)=>{bp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});iL=N("ZodPrefault",(t,e)=>{wp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});Fk=N("ZodNonOptional",(t,e)=>{_p.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});lL=N("ZodCatch",(t,e)=>{vp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});dL=N("ZodPipe",(t,e)=>{kp.init(t,e),We.init(t,e),t.in=e.in,t.out=e.out});pL=N("ZodReadonly",(t,e)=>{xp.init(t,e),We.init(t,e)});Bk=N("ZodCustom",(t,e)=>{Sp.init(t,e),We.init(t,e)})});var Vk=L(()=>{});var Hk=L(()=>{});var Kk=L(()=>{wt();xh();yh();Sh();$h();Vk();wt();nk();Ya();kh();Hk();Dt(rk())});var Wk=L(()=>{Kk()});var Gk=L(()=>{Wk()});function px(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function hx(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ch,Jk,an,uc,tt,Yk,Xk,n9,wL,_L,Ih,Ut,Gs,Qk,ut,Wt,Gt,dt,dc,ex,Oh,tx,rx,Nh,Js,Q,Lh,nx,ox,o9,pc,vL,hc,kL,Ys,zo,sx,xL,SL,$L,TL,RL,EL,jh,PL,AL,zh,mc,CL,IL,fc,OL,Xs,Qs,NL,ei,Do,LL,ti,gc,yc,bc,s9,wc,_c,vc,ix,ax,cx,Dh,lx,ri,Mo,ux,jL,kc,zL,xc,DL,Mh,ML,Sc,UL,qL,FL,BL,ZL,VL,HL,KL,WL,GL,$c,JL,YL,Tc,Uh,qh,Fh,XL,QL,ej,Bh,tj,rj,nj,oj,sj,dx,Rc,ij,Ec,i9,aj,Uo,cj,a9,ni,lj,Zh,uj,dj,pj,hj,mj,fj,gj,lc,yj,bj,wj,oi,Vh,_j,vj,kj,xj,Sj,$j,Tj,Rj,Ej,Pj,Aj,Cj,Ij,Oj,Nj,Lj,jj,zj,qo,Dj,Mj,Uj,Pc,qj,Fj,Bj,Hh,Zj,c9,l9,u9,d9,p9,h9,G,Ah,Fo=L(()=>{Gk();Ch="2025-11-25",Jk=[Ch,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],an="io.modelcontextprotocol/related-task",uc="2.0",tt=Zk(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Yk=Me([C(),Pe().int()]),Xk=C(),n9=_t({ttl:Pe().optional(),pollInterval:Pe().optional()}),wL=W({ttl:Pe().optional()}),_L=W({taskId:C()}),Ih=_t({progressToken:Yk.optional(),[an]:_L.optional()}),Ut=W({_meta:Ih.optional()}),Gs=Ut.extend({task:wL.optional()}),Qk=t=>Gs.safeParse(t).success,ut=W({method:C(),params:Ut.loose().optional()}),Wt=W({_meta:Ih.optional()}),Gt=W({method:C(),params:Wt.loose().optional()}),dt=_t({_meta:Ih.optional()}),dc=Me([C(),Pe().int()]),ex=W({jsonrpc:ee(uc),id:dc,...ut.shape}).strict(),Oh=t=>ex.safeParse(t).success,tx=W({jsonrpc:ee(uc),...Gt.shape}).strict(),rx=t=>tx.safeParse(t).success,Nh=W({jsonrpc:ee(uc),id:dc,result:dt}).strict(),Js=t=>Nh.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"})(Q||(Q={}));Lh=W({jsonrpc:ee(uc),id:dc.optional(),error:W({code:Pe().int(),message:C(),data:Ve().optional()})}).strict(),nx=t=>Lh.safeParse(t).success,ox=Me([ex,tx,Nh,Lh]),o9=Me([Nh,Lh]),pc=dt.strict(),vL=Wt.extend({requestId:dc.optional(),reason:C().optional()}),hc=Gt.extend({method:ee("notifications/cancelled"),params:vL}),kL=W({src:C(),mimeType:C().optional(),sizes:ve(C()).optional(),theme:At(["light","dark"]).optional()}),Ys=W({icons:ve(kL).optional()}),zo=W({name:C(),title:C().optional()}),sx=zo.extend({...zo.shape,...Ys.shape,version:C(),websiteUrl:C().optional(),description:C().optional()}),xL=cc(W({applyDefaults:st().optional()}),ze(C(),Ve())),SL=Ph(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,cc(W({form:xL.optional(),url:tt.optional()}),ze(C(),Ve()).optional())),$L=_t({list:tt.optional(),cancel:tt.optional(),requests:_t({sampling:_t({createMessage:tt.optional()}).optional(),elicitation:_t({create:tt.optional()}).optional()}).optional()}),TL=_t({list:tt.optional(),cancel:tt.optional(),requests:_t({tools:_t({call:tt.optional()}).optional()}).optional()}),RL=W({experimental:ze(C(),tt).optional(),sampling:W({context:tt.optional(),tools:tt.optional()}).optional(),elicitation:SL.optional(),roots:W({listChanged:st().optional()}).optional(),tasks:$L.optional(),extensions:ze(C(),tt).optional()}),EL=Ut.extend({protocolVersion:C(),capabilities:RL,clientInfo:sx}),jh=ut.extend({method:ee("initialize"),params:EL}),PL=W({experimental:ze(C(),tt).optional(),logging:tt.optional(),completions:tt.optional(),prompts:W({listChanged:st().optional()}).optional(),resources:W({subscribe:st().optional(),listChanged:st().optional()}).optional(),tools:W({listChanged:st().optional()}).optional(),tasks:TL.optional(),extensions:ze(C(),tt).optional()}),AL=dt.extend({protocolVersion:C(),capabilities:PL,serverInfo:sx,instructions:C().optional()}),zh=Gt.extend({method:ee("notifications/initialized"),params:Wt.optional()}),mc=ut.extend({method:ee("ping"),params:Ut.optional()}),CL=W({progress:Pe(),total:He(Pe()),message:He(C())}),IL=W({...Wt.shape,...CL.shape,progressToken:Yk}),fc=Gt.extend({method:ee("notifications/progress"),params:IL}),OL=Ut.extend({cursor:Xk.optional()}),Xs=ut.extend({params:OL.optional()}),Qs=dt.extend({nextCursor:Xk.optional()}),NL=At(["working","input_required","completed","failed","cancelled"]),ei=W({taskId:C(),status:NL,ttl:Me([Pe(),zk()]),createdAt:C(),lastUpdatedAt:C(),pollInterval:He(Pe()),statusMessage:He(C())}),Do=dt.extend({task:ei}),LL=Wt.merge(ei),ti=Gt.extend({method:ee("notifications/tasks/status"),params:LL}),gc=ut.extend({method:ee("tasks/get"),params:Ut.extend({taskId:C()})}),yc=dt.merge(ei),bc=ut.extend({method:ee("tasks/result"),params:Ut.extend({taskId:C()})}),s9=dt.loose(),wc=Xs.extend({method:ee("tasks/list")}),_c=Qs.extend({tasks:ve(ei)}),vc=ut.extend({method:ee("tasks/cancel"),params:Ut.extend({taskId:C()})}),ix=dt.merge(ei),ax=W({uri:C(),mimeType:He(C()),_meta:ze(C(),Ve()).optional()}),cx=ax.extend({text:C()}),Dh=C().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),lx=ax.extend({blob:Dh}),ri=At(["user","assistant"]),Mo=W({audience:ve(ri).optional(),priority:Pe().min(0).max(1).optional(),lastModified:Ks.datetime({offset:!0}).optional()}),ux=W({...zo.shape,...Ys.shape,uri:C(),description:He(C()),mimeType:He(C()),size:He(Pe()),annotations:Mo.optional(),_meta:He(_t({}))}),jL=W({...zo.shape,...Ys.shape,uriTemplate:C(),description:He(C()),mimeType:He(C()),annotations:Mo.optional(),_meta:He(_t({}))}),kc=Xs.extend({method:ee("resources/list")}),zL=Qs.extend({resources:ve(ux)}),xc=Xs.extend({method:ee("resources/templates/list")}),DL=Qs.extend({resourceTemplates:ve(jL)}),Mh=Ut.extend({uri:C()}),ML=Mh,Sc=ut.extend({method:ee("resources/read"),params:ML}),UL=dt.extend({contents:ve(Me([cx,lx]))}),qL=Gt.extend({method:ee("notifications/resources/list_changed"),params:Wt.optional()}),FL=Mh,BL=ut.extend({method:ee("resources/subscribe"),params:FL}),ZL=Mh,VL=ut.extend({method:ee("resources/unsubscribe"),params:ZL}),HL=Wt.extend({uri:C()}),KL=Gt.extend({method:ee("notifications/resources/updated"),params:HL}),WL=W({name:C(),description:He(C()),required:He(st())}),GL=W({...zo.shape,...Ys.shape,description:He(C()),arguments:He(ve(WL)),_meta:He(_t({}))}),$c=Xs.extend({method:ee("prompts/list")}),JL=Qs.extend({prompts:ve(GL)}),YL=Ut.extend({name:C(),arguments:ze(C(),C()).optional()}),Tc=ut.extend({method:ee("prompts/get"),params:YL}),Uh=W({type:ee("text"),text:C(),annotations:Mo.optional(),_meta:ze(C(),Ve()).optional()}),qh=W({type:ee("image"),data:Dh,mimeType:C(),annotations:Mo.optional(),_meta:ze(C(),Ve()).optional()}),Fh=W({type:ee("audio"),data:Dh,mimeType:C(),annotations:Mo.optional(),_meta:ze(C(),Ve()).optional()}),XL=W({type:ee("tool_use"),name:C(),id:C(),input:ze(C(),Ve()),_meta:ze(C(),Ve()).optional()}),QL=W({type:ee("resource"),resource:Me([cx,lx]),annotations:Mo.optional(),_meta:ze(C(),Ve()).optional()}),ej=ux.extend({type:ee("resource_link")}),Bh=Me([Uh,qh,Fh,ej,QL]),tj=W({role:ri,content:Bh}),rj=dt.extend({description:C().optional(),messages:ve(tj)}),nj=Gt.extend({method:ee("notifications/prompts/list_changed"),params:Wt.optional()}),oj=W({title:C().optional(),readOnlyHint:st().optional(),destructiveHint:st().optional(),idempotentHint:st().optional(),openWorldHint:st().optional()}),sj=W({taskSupport:At(["required","optional","forbidden"]).optional()}),dx=W({...zo.shape,...Ys.shape,description:C().optional(),inputSchema:W({type:ee("object"),properties:ze(C(),tt).optional(),required:ve(C()).optional()}).catchall(Ve()),outputSchema:W({type:ee("object"),properties:ze(C(),tt).optional(),required:ve(C()).optional()}).catchall(Ve()).optional(),annotations:oj.optional(),execution:sj.optional(),_meta:ze(C(),Ve()).optional()}),Rc=Xs.extend({method:ee("tools/list")}),ij=Qs.extend({tools:ve(dx)}),Ec=dt.extend({content:ve(Bh).default([]),structuredContent:ze(C(),Ve()).optional(),isError:st().optional()}),i9=Ec.or(dt.extend({toolResult:Ve()})),aj=Gs.extend({name:C(),arguments:ze(C(),Ve()).optional()}),Uo=ut.extend({method:ee("tools/call"),params:aj}),cj=Gt.extend({method:ee("notifications/tools/list_changed"),params:Wt.optional()}),a9=W({autoRefresh:st().default(!0),debounceMs:Pe().int().nonnegative().default(300)}),ni=At(["debug","info","notice","warning","error","critical","alert","emergency"]),lj=Ut.extend({level:ni}),Zh=ut.extend({method:ee("logging/setLevel"),params:lj}),uj=Wt.extend({level:ni,logger:C().optional(),data:Ve()}),dj=Gt.extend({method:ee("notifications/message"),params:uj}),pj=W({name:C().optional()}),hj=W({hints:ve(pj).optional(),costPriority:Pe().min(0).max(1).optional(),speedPriority:Pe().min(0).max(1).optional(),intelligencePriority:Pe().min(0).max(1).optional()}),mj=W({mode:At(["auto","required","none"]).optional()}),fj=W({type:ee("tool_result"),toolUseId:C().describe("The unique identifier for the corresponding tool call."),content:ve(Bh).default([]),structuredContent:W({}).loose().optional(),isError:st().optional(),_meta:ze(C(),Ve()).optional()}),gj=Eh("type",[Uh,qh,Fh]),lc=Eh("type",[Uh,qh,Fh,XL,fj]),yj=W({role:ri,content:Me([lc,ve(lc)]),_meta:ze(C(),Ve()).optional()}),bj=Gs.extend({messages:ve(yj),modelPreferences:hj.optional(),systemPrompt:C().optional(),includeContext:At(["none","thisServer","allServers"]).optional(),temperature:Pe().optional(),maxTokens:Pe().int(),stopSequences:ve(C()).optional(),metadata:tt.optional(),tools:ve(dx).optional(),toolChoice:mj.optional()}),wj=ut.extend({method:ee("sampling/createMessage"),params:bj}),oi=dt.extend({model:C(),stopReason:He(At(["endTurn","stopSequence","maxTokens"]).or(C())),role:ri,content:gj}),Vh=dt.extend({model:C(),stopReason:He(At(["endTurn","stopSequence","maxTokens","toolUse"]).or(C())),role:ri,content:Me([lc,ve(lc)])}),_j=W({type:ee("boolean"),title:C().optional(),description:C().optional(),default:st().optional()}),vj=W({type:ee("string"),title:C().optional(),description:C().optional(),minLength:Pe().optional(),maxLength:Pe().optional(),format:At(["email","uri","date","date-time"]).optional(),default:C().optional()}),kj=W({type:At(["number","integer"]),title:C().optional(),description:C().optional(),minimum:Pe().optional(),maximum:Pe().optional(),default:Pe().optional()}),xj=W({type:ee("string"),title:C().optional(),description:C().optional(),enum:ve(C()),default:C().optional()}),Sj=W({type:ee("string"),title:C().optional(),description:C().optional(),oneOf:ve(W({const:C(),title:C()})),default:C().optional()}),$j=W({type:ee("string"),title:C().optional(),description:C().optional(),enum:ve(C()),enumNames:ve(C()).optional(),default:C().optional()}),Tj=Me([xj,Sj]),Rj=W({type:ee("array"),title:C().optional(),description:C().optional(),minItems:Pe().optional(),maxItems:Pe().optional(),items:W({type:ee("string"),enum:ve(C())}),default:ve(C()).optional()}),Ej=W({type:ee("array"),title:C().optional(),description:C().optional(),minItems:Pe().optional(),maxItems:Pe().optional(),items:W({anyOf:ve(W({const:C(),title:C()}))}),default:ve(C()).optional()}),Pj=Me([Rj,Ej]),Aj=Me([$j,Tj,Pj]),Cj=Me([Aj,_j,vj,kj]),Ij=Gs.extend({mode:ee("form").optional(),message:C(),requestedSchema:W({type:ee("object"),properties:ze(C(),Cj),required:ve(C()).optional()})}),Oj=Gs.extend({mode:ee("url"),message:C(),elicitationId:C(),url:C().url()}),Nj=Me([Ij,Oj]),Lj=ut.extend({method:ee("elicitation/create"),params:Nj}),jj=Wt.extend({elicitationId:C()}),zj=Gt.extend({method:ee("notifications/elicitation/complete"),params:jj}),qo=dt.extend({action:At(["accept","decline","cancel"]),content:Ph(t=>t===null?void 0:t,ze(C(),Me([C(),Pe(),st(),ve(C())])).optional())}),Dj=W({type:ee("ref/resource"),uri:C()}),Mj=W({type:ee("ref/prompt"),name:C()}),Uj=Ut.extend({ref:Me([Mj,Dj]),argument:W({name:C(),value:C()}),context:W({arguments:ze(C(),C()).optional()}).optional()}),Pc=ut.extend({method:ee("completion/complete"),params:Uj});qj=dt.extend({completion:_t({values:ve(C()).max(100),total:He(Pe().int()),hasMore:He(st())})}),Fj=W({uri:C().startsWith("file://"),name:C().optional(),_meta:ze(C(),Ve()).optional()}),Bj=ut.extend({method:ee("roots/list"),params:Ut.optional()}),Hh=dt.extend({roots:ve(Fj)}),Zj=Gt.extend({method:ee("notifications/roots/list_changed"),params:Wt.optional()}),c9=Me([mc,jh,Pc,Zh,Tc,$c,kc,xc,Sc,BL,VL,Uo,Rc,gc,bc,wc,vc]),l9=Me([hc,fc,zh,Zj,ti]),u9=Me([pc,oi,Vh,qo,Hh,yc,_c,Do]),d9=Me([mc,wj,Lj,Bj,gc,bc,wc,vc]),p9=Me([hc,fc,dj,KL,qL,cj,nj,ti,zj]),h9=Me([pc,AL,qj,rj,JL,zL,DL,UL,Ec,ij,yc,_c,Do]),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===Q.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ah(o.elicitations,r)}return new t(e,r,n)}},Ah=class extends G{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Q.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function cn(t){return t==="completed"||t==="failed"||t==="cancelled"}var mx=L(()=>{});var gx,fx,yx,Ac=L(()=>{gx=Symbol("Let zodToJsonSchema decide on which parser to use"),fx={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"},yx=t=>typeof t=="string"?{...fx,name:t}:{...fx,...t}});var bx,Kh=L(()=>{Ac();bx=t=>{let e=yx(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 Wh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ke(t,e,r,n,o){t[e]=r,Wh(t,e,n,o)}var ln=L(()=>{});var Cc,Ic=L(()=>{Cc=(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 Ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Cc(e,t.currentPath):e.join("/")}}var Jt=L(()=>{Ic()});function wx(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==U.ZodAny&&(r.items=ce(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ke(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ke(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ke(r,"minItems",t.exactLength.value,t.exactLength.message,e),ke(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Gh=L(()=>{Os();ln();Xe()});function _x(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?ke(r,"minimum",n.value,n.message,e):ke(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ke(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ke(r,"maximum",n.value,n.message,e):ke(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ke(r,"maximum",n.value,n.message,e));break;case"multipleOf":ke(r,"multipleOf",n.value,n.message,e);break}return r}var Jh=L(()=>{ln()});function vx(){return{type:"boolean"}}var Yh=L(()=>{});function Oc(t,e){return ce(t.type._def,e)}var Nc=L(()=>{Xe()});var kx,Xh=L(()=>{Xe();kx=(t,e)=>ce(t.innerType._def,e)});function Qh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Qh(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 Vj(t,e)}}var Vj,em=L(()=>{ln();Vj=(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":ke(r,"minimum",n.value,n.message,e);break;case"max":ke(r,"maximum",n.value,n.message,e);break}return r}});function xx(t,e){return{...ce(t.innerType._def,e),default:t.defaultValue()}}var tm=L(()=>{Xe()});function Sx(t,e){return e.effectStrategy==="input"?ce(t.schema._def,e):Ke(e)}var rm=L(()=>{Xe();Jt()});function $x(t){return{type:"string",enum:Array.from(t.values)}}var nm=L(()=>{});function Tx(t,e){let r=[ce(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ce(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(Hj(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 Hj,om=L(()=>{Xe();Hj=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Rx(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 sm=L(()=>{});function Lc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ke(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ke(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":lr(r,"email",n.message,e);break;case"format:idn-email":lr(r,"idn-email",n.message,e);break;case"pattern:zod":vt(r,cr.email,n.message,e);break}break;case"url":lr(r,"uri",n.message,e);break;case"uuid":lr(r,"uuid",n.message,e);break;case"regex":vt(r,n.regex,n.message,e);break;case"cuid":vt(r,cr.cuid,n.message,e);break;case"cuid2":vt(r,cr.cuid2,n.message,e);break;case"startsWith":vt(r,RegExp(`^${am(n.value,e)}`),n.message,e);break;case"endsWith":vt(r,RegExp(`${am(n.value,e)}$`),n.message,e);break;case"datetime":lr(r,"date-time",n.message,e);break;case"date":lr(r,"date",n.message,e);break;case"time":lr(r,"time",n.message,e);break;case"duration":lr(r,"duration",n.message,e);break;case"length":ke(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ke(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{vt(r,RegExp(am(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&lr(r,"ipv4",n.message,e),n.version!=="v4"&&lr(r,"ipv6",n.message,e);break}case"base64url":vt(r,cr.base64url,n.message,e);break;case"jwt":vt(r,cr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&vt(r,cr.ipv4Cidr,n.message,e),n.version!=="v4"&&vt(r,cr.ipv6Cidr,n.message,e);break}case"emoji":vt(r,cr.emoji(),n.message,e);break;case"ulid":{vt(r,cr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{lr(r,"binary",n.message,e);break}case"contentEncoding:base64":{ke(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{vt(r,cr.base64,n.message,e);break}}break}case"nanoid":vt(r,cr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function am(t,e){return e.patternStrategy==="escape"?Wj(t):t}function Wj(t){let e="";for(let r=0;r<t.length;r++)Kj.has(t[r])||(e+="\\"),e+=t[r];return e}function lr(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}}})):ke(t,"format",e,r,n)}function vt(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:Ex(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ke(t,"pattern",Ex(e,n),r,n)}function Ex(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
2480
2511
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
2481
2512
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
2482
2513
  `:`[${n[c]}\r
2483
- ]`;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 sm,cr,Hj,jc=L(()=>{ln();cr={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:()=>(sm===void 0&&(sm=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),sm),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-_]*$/};Hj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function zc(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]:ce(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ce(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}=Lc(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}=Oc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Dc=L(()=>{Os();Xe();jc();Nc();Jt()});function Ek(t,e){if(e.mapStrategy==="record")return zc(t,e);let r=ce(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ke(e),n=ce(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var am=L(()=>{Xe();Dc();Jt()});function Pk(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 cm=L(()=>{});function Ak(t){return t.target==="openAi"?void 0:{not:Ke({...t,currentPath:[...t.currentPath,"not"]})}}var lm=L(()=>{Jt()});function Ck(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var um=L(()=>{});function Ok(t,e){if(e.target==="openApi3")return Ik(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in si&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=si[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 Ik(t,e)}var si,Ik,Mc=L(()=>{Xe();si={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Ik=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ce(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 Nk(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:si[t.innerType._def.typeName],nullable:!0}:{type:[si[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ce(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ce(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var dm=L(()=>{Xe();Mc()});function Lk(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",Kh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var pm=L(()=>{ln()});function jk(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=Gj(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ce(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=Wj(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Wj(t,e){if(t.catchall._def.typeName!=="ZodNever")return ce(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 Gj(t){try{return t.isOptional()}catch{return!0}}var hm=L(()=>{Xe()});var zk,mm=L(()=>{Xe();Jt();zk=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ce(t.innerType._def,e);let r=ce(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ke(e)},r]}:Ke(e)}});var Dk,fm=L(()=>{Xe();Dk=(t,e)=>{if(e.pipeStrategy==="input")return ce(t.in._def,e);if(e.pipeStrategy==="output")return ce(t.out._def,e);let r=ce(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ce(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Mk(t,e){return ce(t.type._def,e)}var gm=L(()=>{Xe()});function Uk(t,e){let n={type:"array",uniqueItems:!0,items:ce(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&xe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&xe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var ym=L(()=>{ln();Xe()});function qk(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ce(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ce(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ce(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var bm=L(()=>{Xe()});function Fk(t){return{not:Ke(t)}}var wm=L(()=>{Jt()});function Bk(t){return Ke(t)}var _m=L(()=>{Jt()});var Zk,vm=L(()=>{Xe();Zk=(t,e)=>ce(t.innerType._def,e)});var Vk,xm=L(()=>{Os();Jt();Wh();Gh();Jh();Nc();Yh();Qh();em();tm();rm();nm();om();am();cm();lm();um();dm();pm();hm();mm();fm();gm();Dc();ym();jc();bm();wm();Mc();_m();vm();Vk=(t,e,r)=>{switch(e){case U.ZodString:return Lc(t,r);case U.ZodNumber:return Lk(t,r);case U.ZodObject:return jk(t,r);case U.ZodBigInt:return wk(t,r);case U.ZodBoolean:return _k();case U.ZodDate:return Xh(t,r);case U.ZodUndefined:return Fk(r);case U.ZodNull:return Ck(r);case U.ZodArray:return bk(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return Ok(t,r);case U.ZodIntersection:return $k(t,r);case U.ZodTuple:return qk(t,r);case U.ZodRecord:return zc(t,r);case U.ZodLiteral:return Tk(t,r);case U.ZodEnum:return Sk(t);case U.ZodNativeEnum:return Pk(t);case U.ZodNullable:return Nk(t,r);case U.ZodOptional:return zk(t,r);case U.ZodMap:return Ek(t,r);case U.ZodSet:return Uk(t,r);case U.ZodLazy:return()=>t.getter()._def;case U.ZodPromise:return Mk(t,r);case U.ZodNaN:case U.ZodNever:return Ak(r);case U.ZodEffects:return kk(t,r);case U.ZodAny:return Ke(r);case U.ZodUnknown:return Bk(r);case U.ZodDefault:return xk(t,r);case U.ZodBranded:return Oc(t,r);case U.ZodReadonly:return Zk(t,r);case U.ZodCatch:return vk(t,r);case U.ZodPipeline:return Dk(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(n=>{})(e)}}});function ce(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==fk)return a}if(n&&!r){let a=Jj(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=Vk(t,t.typeName,e),i=typeof s=="function"?ce(s(),e):s;if(i&&Yj(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Jj,Yj,Xe=L(()=>{Ac();xm();Ic();Jt();Jj=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Cc(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`),Ke(e)):e.$refStrategy==="seen"?Ke(e):void 0}},Yj=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var Hk=L(()=>{});var km,Sm=L(()=>{Xe();Hh();Jt();km=(t,e)=>{let r=yk(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ce(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Ke(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ce(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ke(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 Kk=L(()=>{Ac();Hh();ln();Ic();Xe();Hk();Jt();Wh();Gh();Jh();Nc();Yh();Qh();em();tm();rm();nm();om();am();cm();lm();um();dm();pm();hm();mm();fm();gm();vm();Dc();ym();jc();bm();wm();Mc();_m();xm();Sm();Sm()});function Xj(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function $m(t,e){return kr(t)?ph(t,{target:Xj(e?.target),io:e?.pipeStrategy??"input"}):km(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Tm(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=zo(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Rm(t,e){let r=on(t,e);if(!r.success)throw r.error;return r.data}var Em=L(()=>{fh();Hs();Kk()});function Wk(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Gk(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];Wk(i)&&Wk(s)?r[o]={...i,...s}:r[o]=s}return r}var Qj,Uc,Jk=L(()=>{Hs();Bo();hk();Em();Qj=6e4,Uc=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(hc,r=>{this._oncancel(r)}),this.setNotificationHandler(fc,r=>{this._onprogress(r)}),this.setRequestHandler(mc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(gc,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(Q.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(bc,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new J(Q.InvalidParams,`Task not found: ${s}`);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 J(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 J(Q.InvalidParams,`Task not found: ${s}`);if(!cn(i.status))return await this._waitForTaskUpdate(s,n.signal,n.sessionId),await o();if(cn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s,n.sessionId),{...a,_meta:{...a._meta,[an]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(wc,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 J(Q.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(vc,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(Q.InvalidParams,`Task not found: ${r.params.taskId}`);if(cn(o.status))throw new J(Q.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,n.sessionId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new J(Q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof J?o:new J(Q.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),J.fromError(Q.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)||rk(s)?this._onresponse(s):Ih(s)?this._onrequest(s,i):tk(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=J.fromError(Q.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?.[an]?.taskId,i=o?.sessionId,a=this._taskStore,c=!0,l;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(c=!1,l=(async()=>{if(!await a.getTask(s,i))throw new J(Q.InvalidParams,`Task not found: ${s}`);c=!0})()),n===void 0){let m={jsonrpc:"2.0",id:e.id,error:{code:Q.MethodNotFound,message:"Method not found"}};if(s&&l){let b={type:"error",message:m,timestamp:Date.now()};l.then(()=>this._enqueueTaskMessage(s,b,i),()=>o?.send(m)).catch($=>this._onerror(new Error(`Failed to send an error response: ${$}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:m,timestamp:Date.now()},o?.sessionId).catch(b=>this._onerror(new Error(`Failed to enqueue error response: ${b}`))):o?.send(m).catch(b=>this._onerror(new Error(`Failed to send an error response: ${b}`)));return}let u=new AbortController;this._requestHandlerAbortControllers.set(e.id,u);let p=Xx(e.params)?e.params.task:void 0,w=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,f={signal:u.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async m=>{if(u.signal.aborted)return;let b={relatedRequestId:e.id};s&&(b.relatedTask={taskId:s}),await this.notification(m,b)},sendRequest:async(m,b,$)=>{if(u.signal.aborted)throw new J(Q.ConnectionClosed,"Request was cancelled");let R={...$,relatedRequestId:e.id};s&&!R.relatedTask&&(R.relatedTask={taskId:s});let A=R.relatedTask?.taskId??s;return A&&w&&await w.updateTaskStatus(A,"input_required"),await this.request(m,b,R)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:w,taskRequestedTtl:p?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(l??Promise.resolve()).then(()=>{if(l&&u.signal.aborted)throw new J(Q.ConnectionClosed,"Request was cancelled");p&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,f)).then(async m=>{if(u.signal.aborted)return;let b={result:m,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:b,timestamp:Date.now()},o?.sessionId):await o?.send(b)},async m=>{if(u.signal.aborted)return;let b={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(m.code)?m.code:Q.InternalError,message:m.message??"Internal error",...m.data!==void 0&&{data:m.data}}};s&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(s,{type:"error",message:b,timestamp:Date.now()},o?.sessionId):await o?.send(b)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===u&&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 J(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=J.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 J?i:new J(Q.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Mo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new J(Q.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},cn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new J(Q.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new J(Q.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 J?i:new J(Q.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=A=>{u(A)};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(A){p(A);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[an]:c}});let m=A=>{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(A)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(q=>this._onerror(new Error(`Failed to send cancellation: ${q}`)));let O=A instanceof J?A:new J(Q.RequestTimeout,String(A));u(O)};this._responseHandlers.set(w,A=>{if(!n?.signal?.aborted){if(A instanceof Error)return u(A);try{let O=on(r,A.result);O.success?l(O.data):u(O.error)}catch(O){u(O)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let b=n?.timeout??Qj,$=()=>m(J.fromError(Q.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(w,b,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let R=c?.taskId;if(R){let A=O=>{let q=this._responseHandlers.get(w);q?q(O):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,A),this._enqueueTaskMessage(R,{type:"request",message:f,timestamp:Date.now()}).catch(O=>{this._cleanupTimeout(w),u(O)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(A=>{this._cleanupTimeout(w),u(A)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},yc,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},_c,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},sk,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||{},[an]: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||{},[an]: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||{},[an]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Tm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Rm(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=Tm(e);this._notificationHandlers.set(n,o=>{let s=Rm(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??this._transport?.sessionId,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"&&Ih(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new J(Q.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,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e,n);s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new J(Q.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new J(Q.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 J(Q.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=ti.parse({method:"notifications/tasks/status",params:a});await this.notification(c),cn(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 J(Q.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(cn(a.status))throw new J(Q.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=ti.parse({method:"notifications/tasks/status",params:c});await this.notification(l),cn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var ci=B(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.regexpCode=Re.getEsmExportName=Re.getProperty=Re.safeStringify=Re.stringify=Re.strConcat=Re.addCodeArg=Re.str=Re._=Re.nil=Re._Code=Re.Name=Re.IDENTIFIER=Re._CodeOrName=void 0;var ii=class{};Re._CodeOrName=ii;Re.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wn=class extends ii{constructor(e){if(super(),!Re.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}}};Re.Name=Wn;var Yt=class extends ii{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 Wn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Re._Code=Yt;Re.nil=new Yt("");function Yk(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Am(r,e[n]),r.push(t[++n]);return new Yt(r)}Re._=Yk;var Pm=new Yt("+");function Xk(t,...e){let r=[ai(t[0])],n=0;for(;n<e.length;)r.push(Pm),Am(r,e[n]),r.push(Pm,ai(t[++n]));return ez(r),new Yt(r)}Re.str=Xk;function Am(t,e){e instanceof Yt?t.push(...e._items):e instanceof Wn?t.push(e):t.push(nz(e))}Re.addCodeArg=Am;function ez(t){let e=1;for(;e<t.length-1;){if(t[e]===Pm){let r=tz(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function tz(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Wn||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 Wn))return`"${t}${e.slice(1)}`}function rz(t,e){return e.emptyStr()?t:t.emptyStr()?e:Xk`${t}${e}`}Re.strConcat=rz;function nz(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ai(Array.isArray(t)?t.join(","):t)}function oz(t){return new Yt(ai(t))}Re.stringify=oz;function ai(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Re.safeStringify=ai;function sz(t){return typeof t=="string"&&Re.IDENTIFIER.test(t)?new Yt(`.${t}`):Yk`[${t}]`}Re.getProperty=sz;function iz(t){if(typeof t=="string"&&Re.IDENTIFIER.test(t))return new Yt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Re.getEsmExportName=iz;function az(t){return new Yt(t.toString())}Re.regexpCode=az});var Om=B(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.ValueScope=It.ValueScopeName=It.Scope=It.varKinds=It.UsedValueState=void 0;var Ct=ci(),Cm=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},qc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(qc||(It.UsedValueState=qc={}));It.varKinds={const:new Ct.Name("const"),let:new Ct.Name("let"),var:new Ct.Name("var")};var Fc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ct.Name?e:this.name(e)}name(e){return new Ct.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}}};It.Scope=Fc;var Bc=class extends Ct.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ct._)`.${new Ct.Name(r)}[${n}]`}};It.ValueScopeName=Bc;var cz=(0,Ct._)`\n`,Im=class extends Fc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?cz:Ct.nil}}get(){return this._scope}name(e){return new Bc(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,Ct._)`${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=Ct.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,qc.Started);let u=r(l);if(u){let p=this.opts.es5?It.varKinds.var:It.varKinds.const;s=(0,Ct._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Ct._)`${s}${u}${this.opts._n}`;else throw new Cm(l);c.set(l,qc.Completed)})}return s}};It.ValueScope=Im});var me=B(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.or=ge.and=ge.not=ge.CodeGen=ge.operators=ge.varKinds=ge.ValueScopeName=ge.ValueScope=ge.Scope=ge.Name=ge.regexpCode=ge.stringify=ge.getProperty=ge.nil=ge.strConcat=ge.str=ge._=void 0;var ke=ci(),ur=Om(),un=ci();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return un._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return un.str}});Object.defineProperty(ge,"strConcat",{enumerable:!0,get:function(){return un.strConcat}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return un.nil}});Object.defineProperty(ge,"getProperty",{enumerable:!0,get:function(){return un.getProperty}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return un.stringify}});Object.defineProperty(ge,"regexpCode",{enumerable:!0,get:function(){return un.regexpCode}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return un.Name}});var Kc=Om();Object.defineProperty(ge,"Scope",{enumerable:!0,get:function(){return Kc.Scope}});Object.defineProperty(ge,"ValueScope",{enumerable:!0,get:function(){return Kc.ValueScope}});Object.defineProperty(ge,"ValueScopeName",{enumerable:!0,get:function(){return Kc.ValueScopeName}});Object.defineProperty(ge,"varKinds",{enumerable:!0,get:function(){return Kc.varKinds}});ge.operators={GT:new ke._Code(">"),GTE:new ke._Code(">="),LT:new ke._Code("<"),LTE:new ke._Code("<="),EQ:new ke._Code("==="),NEQ:new ke._Code("!=="),NOT:new ke._Code("!"),OR:new ke._Code("||"),AND:new ke._Code("&&"),ADD:new ke._Code("+")};var Ur=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Nm=class extends Ur{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ur.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=Vo(this.rhs,e,r)),this}get names(){return this.rhs instanceof ke._CodeOrName?this.rhs.names:{}}},Zc=class extends Ur{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 ke.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Vo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ke.Name?{}:{...this.lhs.names};return Hc(e,this.rhs)}},Lm=class extends Zc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},jm=class extends Ur{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},zm=class extends Ur{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Dm=class extends Ur{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Mm=class extends Ur{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=Vo(this.code,e,r),this}get names(){return this.code instanceof ke._CodeOrName?this.code.names:{}}},li=class extends Ur{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)||(lz(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Yn(e,r.names),{})}},qr=class extends li{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Um=class extends li{},Zo=class extends qr{};Zo.kind="else";var Gn=class t extends qr{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 Zo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Qk(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=Vo(this.condition,e,r),this}get names(){let e=super.names;return Hc(e,this.condition),this.else&&Yn(e,this.else.names),e}};Gn.kind="if";var Jn=class extends qr{};Jn.kind="for";var qm=class extends Jn{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=Vo(this.iteration,e,r),this}get names(){return Yn(super.names,this.iteration.names)}},Fm=class extends Jn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?ur.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=Hc(super.names,this.from);return Hc(e,this.to)}},Vc=class extends Jn{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=Vo(this.iterable,e,r),this}get names(){return Yn(super.names,this.iterable.names)}},ui=class extends qr{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)}};ui.kind="func";var di=class extends li{render(e){return"return "+super.render(e)}};di.kind="return";var Bm=class extends qr{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&&Yn(e,this.catch.names),this.finally&&Yn(e,this.finally.names),e}},pi=class extends qr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};pi.kind="catch";var hi=class extends qr{render(e){return"finally"+super.render(e)}};hi.kind="finally";var Zm=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2484
- `:""},this._extScope=e,this._scope=new ur.Scope({parent:e}),this._nodes=[new Um]}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 Nm(e,s,n)),s}const(e,r,n){return this._def(ur.varKinds.const,e,r,n)}let(e,r,n){return this._def(ur.varKinds.let,e,r,n)}var(e,r,n){return this._def(ur.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Zc(e,r,n))}add(e,r){return this._leafNode(new Lm(e,ge.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ke.nil&&this._leafNode(new Mm(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,ke.addCodeArg)(r,o));return r.push("}"),new ke._Code(r)}if(e,r,n){if(this._blockNode(new Gn(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 Gn(e))}else(){return this._elseNode(new Zo)}endIf(){return this._endBlockNode(Gn,Zo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new qm(e),r)}forRange(e,r,n,o,s=this.opts.es5?ur.varKinds.var:ur.varKinds.let){let i=this._scope.toName(e);return this._for(new Fm(s,i,r,n),()=>o(i))}forOf(e,r,n,o=ur.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ke.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ke._)`${i}.length`,a=>{this.var(s,(0,ke._)`${i}[${a}]`),n(s)})}return this._for(new Vc("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?ur.varKinds.var:ur.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ke._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Vc("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Jn)}label(e){return this._leafNode(new jm(e))}break(e){return this._leafNode(new zm(e))}return(e){let r=new di;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(di)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Bm;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new pi(s),r(s)}return n&&(this._currNode=o.finally=new hi,this.code(n)),this._endBlockNode(pi,hi)}throw(e){return this._leafNode(new Dm(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=ke.nil,n,o){return this._blockNode(new ui(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ui)}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 Gn))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}};ge.CodeGen=Zm;function Yn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Hc(t,e){return e instanceof ke._CodeOrName?Yn(t,e.names):t}function Vo(t,e,r){if(t instanceof ke.Name)return n(t);if(!o(t))return t;return new ke._Code(t._items.reduce((s,i)=>(i instanceof ke.Name&&(i=n(i)),i instanceof ke._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 ke._Code&&s._items.some(i=>i instanceof ke.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function lz(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Qk(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ke._)`!${Vm(t)}`}ge.not=Qk;var uz=eS(ge.operators.AND);function dz(...t){return t.reduce(uz)}ge.and=dz;var pz=eS(ge.operators.OR);function hz(...t){return t.reduce(pz)}ge.or=hz;function eS(t){return(e,r)=>e===ke.nil?r:r===ke.nil?e:(0,ke._)`${Vm(e)} ${t} ${Vm(r)}`}function Vm(t){return t instanceof ke.Name?t:(0,ke._)`(${t})`}});var $e=B(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.checkStrictMode=ye.getErrorPath=ye.Type=ye.useFunc=ye.setEvaluated=ye.evaluatedPropsToName=ye.mergeEvaluated=ye.eachItem=ye.unescapeJsonPointer=ye.escapeJsonPointer=ye.escapeFragment=ye.unescapeFragment=ye.schemaRefOrVal=ye.schemaHasRulesButRef=ye.schemaHasRules=ye.checkUnknownRules=ye.alwaysValidSchema=ye.toHash=void 0;var Oe=me(),mz=ci();function fz(t){let e={};for(let r of t)e[r]=!0;return e}ye.toHash=fz;function gz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(nS(t,e),!oS(e,t.self.RULES.all))}ye.alwaysValidSchema=gz;function nS(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]||aS(t,`unknown keyword: "${s}"`)}ye.checkUnknownRules=nS;function oS(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ye.schemaHasRules=oS;function yz(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ye.schemaHasRulesButRef=yz;function bz({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)}`}ye.schemaRefOrVal=bz;function wz(t){return sS(decodeURIComponent(t))}ye.unescapeFragment=wz;function _z(t){return encodeURIComponent(Km(t))}ye.escapeFragment=_z;function Km(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ye.escapeJsonPointer=Km;function sS(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ye.unescapeJsonPointer=sS;function vz(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ye.eachItem=vz;function tS({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}}ye.mergeEvaluated={props:tS({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} || {}`),Wm(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:iS}),items:tS({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 iS(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Oe._)`{}`);return e!==void 0&&Wm(t,r,e),r}ye.evaluatedPropsToName=iS;function Wm(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Oe._)`${e}${(0,Oe.getProperty)(n)}`,!0))}ye.setEvaluated=Wm;var rS={};function xz(t,e){return t.scopeValue("func",{ref:e,code:rS[e.code]||(rS[e.code]=new mz._Code(e.code))})}ye.useFunc=xz;var Hm;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Hm||(ye.Type=Hm={}));function kz(t,e,r){if(t instanceof Oe.Name){let n=e===Hm.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():"/"+Km(t)}ye.getErrorPath=kz;function aS(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ye.checkStrictMode=aS});var Fr=B(Gm=>{"use strict";Object.defineProperty(Gm,"__esModule",{value:!0});var ft=me(),Sz={data:new ft.Name("data"),valCxt:new ft.Name("valCxt"),instancePath:new ft.Name("instancePath"),parentData:new ft.Name("parentData"),parentDataProperty:new ft.Name("parentDataProperty"),rootData:new ft.Name("rootData"),dynamicAnchors:new ft.Name("dynamicAnchors"),vErrors:new ft.Name("vErrors"),errors:new ft.Name("errors"),this:new ft.Name("this"),self:new ft.Name("self"),scope:new ft.Name("scope"),json:new ft.Name("json"),jsonPos:new ft.Name("jsonPos"),jsonLen:new ft.Name("jsonLen"),jsonPart:new ft.Name("jsonPart")};Gm.default=Sz});var mi=B(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.extendErrors=gt.resetErrorsCount=gt.reportExtraError=gt.reportError=gt.keyword$DataError=gt.keywordError=void 0;var Te=me(),Wc=$e(),xt=Fr();gt.keywordError={message:({keyword:t})=>(0,Te.str)`must pass "${t}" keyword validation`};gt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Te.str)`"${t}" keyword must be ${e} ($data)`:(0,Te.str)`"${t}" keyword is invalid ($data)`};function $z(t,e=gt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=uS(t,e,r);n??(i||a)?cS(s,c):lS(o,(0,Te._)`[${c}]`)}gt.reportError=$z;function Tz(t,e=gt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=uS(t,e,r);cS(o,a),s||i||lS(n,xt.default.vErrors)}gt.reportExtraError=Tz;function Rz(t,e){t.assign(xt.default.errors,e),t.if((0,Te._)`${xt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Te._)`${xt.default.vErrors}.length`,e),()=>t.assign(xt.default.vErrors,null)))}gt.resetErrorsCount=Rz;function Ez({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,xt.default.errors,a=>{t.const(i,(0,Te._)`${xt.default.vErrors}[${a}]`),t.if((0,Te._)`${i}.instancePath === undefined`,()=>t.assign((0,Te._)`${i}.instancePath`,(0,Te.strConcat)(xt.default.instancePath,s.errorPath))),t.assign((0,Te._)`${i}.schemaPath`,(0,Te.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Te._)`${i}.schema`,r),t.assign((0,Te._)`${i}.data`,n))})}gt.extendErrors=Ez;function cS(t,e){let r=t.const("err",e);t.if((0,Te._)`${xt.default.vErrors} === null`,()=>t.assign(xt.default.vErrors,(0,Te._)`[${r}]`),(0,Te._)`${xt.default.vErrors}.push(${r})`),t.code((0,Te._)`${xt.default.errors}++`)}function lS(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Te._)`new ${t.ValidationError}(${e})`):(r.assign((0,Te._)`${n}.errors`,e),r.return(!1))}var Xn={keyword:new Te.Name("keyword"),schemaPath:new Te.Name("schemaPath"),params:new Te.Name("params"),propertyName:new Te.Name("propertyName"),message:new Te.Name("message"),schema:new Te.Name("schema"),parentSchema:new Te.Name("parentSchema")};function uS(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Te._)`{}`:Pz(t,e,r)}function Pz(t,e,r={}){let{gen:n,it:o}=t,s=[Az(o,r),Cz(t,r)];return Iz(t,e,s),n.object(...s)}function Az({errorPath:t},{instancePath:e}){let r=e?(0,Te.str)`${t}${(0,Wc.getErrorPath)(e,Wc.Type.Str)}`:t;return[xt.default.instancePath,(0,Te.strConcat)(xt.default.instancePath,r)]}function Cz({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Te.str)`${e}/${t}`;return r&&(o=(0,Te.str)`${o}${(0,Wc.getErrorPath)(r,Wc.Type.Str)}`),[Xn.schemaPath,o]}function Iz(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([Xn.keyword,o],[Xn.params,typeof e=="function"?e(t):e||(0,Te._)`{}`]),c.messages&&n.push([Xn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Xn.schema,i],[Xn.parentSchema,(0,Te._)`${u}${p}`],[xt.default.data,s]),l&&n.push([Xn.propertyName,l])}});var pS=B(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.boolOrEmptySchema=Ho.topBoolOrEmptySchema=void 0;var Oz=mi(),Nz=me(),Lz=Fr(),jz={message:"boolean schema is false"};function zz(t){let{gen:e,schema:r,validateName:n}=t;r===!1?dS(t,!1):typeof r=="object"&&r.$async===!0?e.return(Lz.default.data):(e.assign((0,Nz._)`${n}.errors`,null),e.return(!0))}Ho.topBoolOrEmptySchema=zz;function Dz(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),dS(t)):r.var(e,!0)}Ho.boolOrEmptySchema=Dz;function dS(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,Oz.reportError)(o,jz,void 0,e)}});var Jm=B(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.getRules=Ko.isJSONType=void 0;var Mz=["string","number","integer","boolean","null","object","array"],Uz=new Set(Mz);function qz(t){return typeof t=="string"&&Uz.has(t)}Ko.isJSONType=qz;function Fz(){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:{}}}Ko.getRules=Fz});var Ym=B(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.shouldUseRule=dn.shouldUseGroup=dn.schemaHasRulesForType=void 0;function Bz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&hS(t,n)}dn.schemaHasRulesForType=Bz;function hS(t,e){return e.rules.some(r=>mS(t,r))}dn.shouldUseGroup=hS;function mS(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))}dn.shouldUseRule=mS});var fi=B(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.reportTypeError=yt.checkDataTypes=yt.checkDataType=yt.coerceAndCheckDataType=yt.getJSONTypes=yt.getSchemaTypes=yt.DataType=void 0;var Zz=Jm(),Vz=Ym(),Hz=mi(),pe=me(),fS=$e(),Wo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Wo||(yt.DataType=Wo={}));function Kz(t){let e=gS(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}yt.getSchemaTypes=Kz;function gS(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Zz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}yt.getJSONTypes=gS;function Wz(t,e){let{gen:r,data:n,opts:o}=t,s=Gz(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Vz.schemaHasRulesForType)(t,e[0]));if(i){let a=Qm(e,n,o.strictNumbers,Wo.Wrong);r.if(a,()=>{s.length?Jz(t,e,s):ef(t)})}return i}yt.coerceAndCheckDataType=Wz;var yS=new Set(["string","number","integer","boolean","null"]);function Gz(t,e){return e?t.filter(r=>yS.has(r)||e==="array"&&r==="array"):[]}function Jz(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,pe._)`typeof ${o}`),a=n.let("coerced",(0,pe._)`undefined`);s.coerceTypes==="array"&&n.if((0,pe._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,pe._)`${o}[0]`).assign(i,(0,pe._)`typeof ${o}`).if(Qm(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,pe._)`${a} !== undefined`);for(let l of r)(yS.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),ef(t),n.endIf(),n.if((0,pe._)`${a} !== undefined`,()=>{n.assign(o,a),Yz(t,a)});function c(l){switch(l){case"string":n.elseIf((0,pe._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,pe._)`"" + ${o}`).elseIf((0,pe._)`${o} === null`).assign(a,(0,pe._)`""`);return;case"number":n.elseIf((0,pe._)`${i} == "boolean" || ${o} === null
2514
+ ]`;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 im,cr,Kj,jc=L(()=>{ln();cr={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:()=>(im===void 0&&(im=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),im),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-_]*$/};Kj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function zc(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]:ce(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ce(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}=Lc(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}=Oc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Dc=L(()=>{Os();Xe();jc();Nc();Jt()});function Px(t,e){if(e.mapStrategy==="record")return zc(t,e);let r=ce(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ke(e),n=ce(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var cm=L(()=>{Xe();Dc();Jt()});function Ax(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 lm=L(()=>{});function Cx(t){return t.target==="openAi"?void 0:{not:Ke({...t,currentPath:[...t.currentPath,"not"]})}}var um=L(()=>{Jt()});function Ix(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var dm=L(()=>{});function Nx(t,e){if(e.target==="openApi3")return Ox(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in si&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=si[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 Ox(t,e)}var si,Ox,Mc=L(()=>{Xe();si={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Ox=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ce(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 Lx(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:si[t.innerType._def.typeName],nullable:!0}:{type:[si[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ce(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ce(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var pm=L(()=>{Xe();Mc()});function jx(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",Wh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ke(r,"minimum",n.value,n.message,e):ke(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ke(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ke(r,"maximum",n.value,n.message,e):ke(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ke(r,"maximum",n.value,n.message,e));break;case"multipleOf":ke(r,"multipleOf",n.value,n.message,e);break}return r}var hm=L(()=>{ln()});function zx(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=Jj(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ce(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=Gj(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Gj(t,e){if(t.catchall._def.typeName!=="ZodNever")return ce(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 Jj(t){try{return t.isOptional()}catch{return!0}}var mm=L(()=>{Xe()});var Dx,fm=L(()=>{Xe();Jt();Dx=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ce(t.innerType._def,e);let r=ce(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ke(e)},r]}:Ke(e)}});var Mx,gm=L(()=>{Xe();Mx=(t,e)=>{if(e.pipeStrategy==="input")return ce(t.in._def,e);if(e.pipeStrategy==="output")return ce(t.out._def,e);let r=ce(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ce(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Ux(t,e){return ce(t.type._def,e)}var ym=L(()=>{Xe()});function qx(t,e){let n={type:"array",uniqueItems:!0,items:ce(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ke(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ke(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var bm=L(()=>{ln();Xe()});function Fx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ce(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ce(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ce(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var wm=L(()=>{Xe()});function Bx(t){return{not:Ke(t)}}var _m=L(()=>{Jt()});function Zx(t){return Ke(t)}var vm=L(()=>{Jt()});var Vx,km=L(()=>{Xe();Vx=(t,e)=>ce(t.innerType._def,e)});var Hx,xm=L(()=>{Os();Jt();Gh();Jh();Yh();Nc();Xh();em();tm();rm();nm();om();sm();cm();lm();um();dm();pm();hm();mm();fm();gm();ym();Dc();bm();jc();wm();_m();Mc();vm();km();Hx=(t,e,r)=>{switch(e){case U.ZodString:return Lc(t,r);case U.ZodNumber:return jx(t,r);case U.ZodObject:return zx(t,r);case U.ZodBigInt:return _x(t,r);case U.ZodBoolean:return vx();case U.ZodDate:return Qh(t,r);case U.ZodUndefined:return Bx(r);case U.ZodNull:return Ix(r);case U.ZodArray:return wx(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return Nx(t,r);case U.ZodIntersection:return Tx(t,r);case U.ZodTuple:return Fx(t,r);case U.ZodRecord:return zc(t,r);case U.ZodLiteral:return Rx(t,r);case U.ZodEnum:return $x(t);case U.ZodNativeEnum:return Ax(t);case U.ZodNullable:return Lx(t,r);case U.ZodOptional:return Dx(t,r);case U.ZodMap:return Px(t,r);case U.ZodSet:return qx(t,r);case U.ZodLazy:return()=>t.getter()._def;case U.ZodPromise:return Ux(t,r);case U.ZodNaN:case U.ZodNever:return Cx(r);case U.ZodEffects:return Sx(t,r);case U.ZodAny:return Ke(r);case U.ZodUnknown:return Zx(r);case U.ZodDefault:return xx(t,r);case U.ZodBranded:return Oc(t,r);case U.ZodReadonly:return Vx(t,r);case U.ZodCatch:return kx(t,r);case U.ZodPipeline:return Mx(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(n=>{})(e)}}});function ce(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==gx)return a}if(n&&!r){let a=Yj(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=Hx(t,t.typeName,e),i=typeof s=="function"?ce(s(),e):s;if(i&&Xj(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Yj,Xj,Xe=L(()=>{Ac();xm();Ic();Jt();Yj=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Cc(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`),Ke(e)):e.$refStrategy==="seen"?Ke(e):void 0}},Xj=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var Kx=L(()=>{});var Sm,$m=L(()=>{Xe();Kh();Jt();Sm=(t,e)=>{let r=bx(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ce(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Ke(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ce(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ke(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 Wx=L(()=>{Ac();Kh();ln();Ic();Xe();Kx();Jt();Gh();Jh();Yh();Nc();Xh();em();tm();rm();nm();om();sm();cm();lm();um();dm();pm();hm();mm();fm();gm();ym();km();Dc();bm();jc();wm();_m();Mc();vm();xm();$m();$m()});function Qj(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Tm(t,e){return xr(t)?hh(t,{target:Qj(e?.target),io:e?.pipeStrategy??"input"}):Sm(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Rm(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=jo(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Em(t,e){let r=on(t,e);if(!r.success)throw r.error;return r.data}var Pm=L(()=>{gh();Hs();Wx()});function Gx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Jx(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];Gx(i)&&Gx(s)?r[o]={...i,...s}:r[o]=s}return r}var ez,Uc,Yx=L(()=>{Hs();Fo();mx();Pm();ez=6e4,Uc=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(hc,r=>{this._oncancel(r)}),this.setNotificationHandler(fc,r=>{this._onprogress(r)}),this.setRequestHandler(mc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(gc,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new G(Q.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(bc,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new G(Q.InvalidParams,`Task not found: ${s}`);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(Q.InvalidParams,`Task not found: ${s}`);if(!cn(i.status))return await this._waitForTaskUpdate(s,n.signal,n.sessionId),await o();if(cn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s,n.sessionId),{...a,_meta:{...a._meta,[an]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(wc,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(Q.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(vc,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new G(Q.InvalidParams,`Task not found: ${r.params.taskId}`);if(cn(o.status))throw new G(Q.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,n.sessionId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new G(Q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof G?o:new G(Q.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(Q.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)||nx(s)?this._onresponse(s):Oh(s)?this._onrequest(s,i):rx(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(Q.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?.[an]?.taskId,i=o?.sessionId,a=this._taskStore,c=!0,l;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(c=!1,l=(async()=>{if(!await a.getTask(s,i))throw new G(Q.InvalidParams,`Task not found: ${s}`);c=!0})()),n===void 0){let m={jsonrpc:"2.0",id:e.id,error:{code:Q.MethodNotFound,message:"Method not found"}};if(s&&l){let b={type:"error",message:m,timestamp:Date.now()};l.then(()=>this._enqueueTaskMessage(s,b,i),()=>o?.send(m)).catch($=>this._onerror(new Error(`Failed to send an error response: ${$}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:m,timestamp:Date.now()},o?.sessionId).catch(b=>this._onerror(new Error(`Failed to enqueue error response: ${b}`))):o?.send(m).catch(b=>this._onerror(new Error(`Failed to send an error response: ${b}`)));return}let u=new AbortController;this._requestHandlerAbortControllers.set(e.id,u);let p=Qk(e.params)?e.params.task:void 0,w=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,f={signal:u.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async m=>{if(u.signal.aborted)return;let b={relatedRequestId:e.id};s&&(b.relatedTask={taskId:s}),await this.notification(m,b)},sendRequest:async(m,b,$)=>{if(u.signal.aborted)throw new G(Q.ConnectionClosed,"Request was cancelled");let R={...$,relatedRequestId:e.id};s&&!R.relatedTask&&(R.relatedTask={taskId:s});let A=R.relatedTask?.taskId??s;return A&&w&&await w.updateTaskStatus(A,"input_required"),await this.request(m,b,R)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:w,taskRequestedTtl:p?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(l??Promise.resolve()).then(()=>{if(l&&u.signal.aborted)throw new G(Q.ConnectionClosed,"Request was cancelled");p&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,f)).then(async m=>{if(u.signal.aborted)return;let b={result:m,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:b,timestamp:Date.now()},o?.sessionId):await o?.send(b)},async m=>{if(u.signal.aborted)return;let b={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(m.code)?m.code:Q.InternalError,message:m.message??"Internal error",...m.data!==void 0&&{data:m.data}}};s&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(s,{type:"error",message:b,timestamp:Date.now()},o?.sessionId):await o?.send(b)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===u&&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(Q.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Do,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new G(Q.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},cn(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(Q.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new G(Q.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(Q.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=A=>{u(A)};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(A){p(A);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[an]:c}});let m=A=>{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(A)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(q=>this._onerror(new Error(`Failed to send cancellation: ${q}`)));let O=A instanceof G?A:new G(Q.RequestTimeout,String(A));u(O)};this._responseHandlers.set(w,A=>{if(!n?.signal?.aborted){if(A instanceof Error)return u(A);try{let O=on(r,A.result);O.success?l(O.data):u(O.error)}catch(O){u(O)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let b=n?.timeout??ez,$=()=>m(G.fromError(Q.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(w,b,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let R=c?.taskId;if(R){let A=O=>{let q=this._responseHandlers.get(w);q?q(O):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,A),this._enqueueTaskMessage(R,{type:"request",message:f,timestamp:Date.now()}).catch(O=>{this._cleanupTimeout(w),u(O)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(A=>{this._cleanupTimeout(w),u(A)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},yc,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},_c,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ix,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||{},[an]: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||{},[an]: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||{},[an]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Rm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Em(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=Rm(e);this._notificationHandlers.set(n,o=>{let s=Em(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??this._transport?.sessionId,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"&&Oh(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new G(Q.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,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e,n);s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new G(Q.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new G(Q.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(Q.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=ti.parse({method:"notifications/tasks/status",params:a});await this.notification(c),cn(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(Q.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(cn(a.status))throw new G(Q.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=ti.parse({method:"notifications/tasks/status",params:c});await this.notification(l),cn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var ci=B(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.regexpCode=Re.getEsmExportName=Re.getProperty=Re.safeStringify=Re.stringify=Re.strConcat=Re.addCodeArg=Re.str=Re._=Re.nil=Re._Code=Re.Name=Re.IDENTIFIER=Re._CodeOrName=void 0;var ii=class{};Re._CodeOrName=ii;Re.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wn=class extends ii{constructor(e){if(super(),!Re.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}}};Re.Name=Wn;var Yt=class extends ii{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 Wn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Re._Code=Yt;Re.nil=new Yt("");function Xx(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Cm(r,e[n]),r.push(t[++n]);return new Yt(r)}Re._=Xx;var Am=new Yt("+");function Qx(t,...e){let r=[ai(t[0])],n=0;for(;n<e.length;)r.push(Am),Cm(r,e[n]),r.push(Am,ai(t[++n]));return tz(r),new Yt(r)}Re.str=Qx;function Cm(t,e){e instanceof Yt?t.push(...e._items):e instanceof Wn?t.push(e):t.push(oz(e))}Re.addCodeArg=Cm;function tz(t){let e=1;for(;e<t.length-1;){if(t[e]===Am){let r=rz(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function rz(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Wn||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 Wn))return`"${t}${e.slice(1)}`}function nz(t,e){return e.emptyStr()?t:t.emptyStr()?e:Qx`${t}${e}`}Re.strConcat=nz;function oz(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ai(Array.isArray(t)?t.join(","):t)}function sz(t){return new Yt(ai(t))}Re.stringify=sz;function ai(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Re.safeStringify=ai;function iz(t){return typeof t=="string"&&Re.IDENTIFIER.test(t)?new Yt(`.${t}`):Xx`[${t}]`}Re.getProperty=iz;function az(t){if(typeof t=="string"&&Re.IDENTIFIER.test(t))return new Yt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Re.getEsmExportName=az;function cz(t){return new Yt(t.toString())}Re.regexpCode=cz});var Nm=B(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.ValueScope=It.ValueScopeName=It.Scope=It.varKinds=It.UsedValueState=void 0;var Ct=ci(),Im=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},qc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(qc||(It.UsedValueState=qc={}));It.varKinds={const:new Ct.Name("const"),let:new Ct.Name("let"),var:new Ct.Name("var")};var Fc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ct.Name?e:this.name(e)}name(e){return new Ct.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}}};It.Scope=Fc;var Bc=class extends Ct.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ct._)`.${new Ct.Name(r)}[${n}]`}};It.ValueScopeName=Bc;var lz=(0,Ct._)`\n`,Om=class extends Fc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?lz:Ct.nil}}get(){return this._scope}name(e){return new Bc(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,Ct._)`${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=Ct.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,qc.Started);let u=r(l);if(u){let p=this.opts.es5?It.varKinds.var:It.varKinds.const;s=(0,Ct._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Ct._)`${s}${u}${this.opts._n}`;else throw new Im(l);c.set(l,qc.Completed)})}return s}};It.ValueScope=Om});var me=B(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.or=ge.and=ge.not=ge.CodeGen=ge.operators=ge.varKinds=ge.ValueScopeName=ge.ValueScope=ge.Scope=ge.Name=ge.regexpCode=ge.stringify=ge.getProperty=ge.nil=ge.strConcat=ge.str=ge._=void 0;var xe=ci(),ur=Nm(),un=ci();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return un._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return un.str}});Object.defineProperty(ge,"strConcat",{enumerable:!0,get:function(){return un.strConcat}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return un.nil}});Object.defineProperty(ge,"getProperty",{enumerable:!0,get:function(){return un.getProperty}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return un.stringify}});Object.defineProperty(ge,"regexpCode",{enumerable:!0,get:function(){return un.regexpCode}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return un.Name}});var Kc=Nm();Object.defineProperty(ge,"Scope",{enumerable:!0,get:function(){return Kc.Scope}});Object.defineProperty(ge,"ValueScope",{enumerable:!0,get:function(){return Kc.ValueScope}});Object.defineProperty(ge,"ValueScopeName",{enumerable:!0,get:function(){return Kc.ValueScopeName}});Object.defineProperty(ge,"varKinds",{enumerable:!0,get:function(){return Kc.varKinds}});ge.operators={GT:new xe._Code(">"),GTE:new xe._Code(">="),LT:new xe._Code("<"),LTE:new xe._Code("<="),EQ:new xe._Code("==="),NEQ:new xe._Code("!=="),NOT:new xe._Code("!"),OR:new xe._Code("||"),AND:new xe._Code("&&"),ADD:new xe._Code("+")};var Ur=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Lm=class extends Ur{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ur.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=Zo(this.rhs,e,r)),this}get names(){return this.rhs instanceof xe._CodeOrName?this.rhs.names:{}}},Zc=class extends Ur{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 xe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Zo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof xe.Name?{}:{...this.lhs.names};return Hc(e,this.rhs)}},jm=class extends Zc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},zm=class extends Ur{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Dm=class extends Ur{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Mm=class extends Ur{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Um=class extends Ur{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=Zo(this.code,e,r),this}get names(){return this.code instanceof xe._CodeOrName?this.code.names:{}}},li=class extends Ur{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)||(uz(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Yn(e,r.names),{})}},qr=class extends li{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},qm=class extends li{},Bo=class extends qr{};Bo.kind="else";var Gn=class t extends qr{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 Bo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(eS(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=Zo(this.condition,e,r),this}get names(){let e=super.names;return Hc(e,this.condition),this.else&&Yn(e,this.else.names),e}};Gn.kind="if";var Jn=class extends qr{};Jn.kind="for";var Fm=class extends Jn{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=Zo(this.iteration,e,r),this}get names(){return Yn(super.names,this.iteration.names)}},Bm=class extends Jn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?ur.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=Hc(super.names,this.from);return Hc(e,this.to)}},Vc=class extends Jn{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=Zo(this.iterable,e,r),this}get names(){return Yn(super.names,this.iterable.names)}},ui=class extends qr{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)}};ui.kind="func";var di=class extends li{render(e){return"return "+super.render(e)}};di.kind="return";var Zm=class extends qr{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&&Yn(e,this.catch.names),this.finally&&Yn(e,this.finally.names),e}},pi=class extends qr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};pi.kind="catch";var hi=class extends qr{render(e){return"finally"+super.render(e)}};hi.kind="finally";var Vm=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2515
+ `:""},this._extScope=e,this._scope=new ur.Scope({parent:e}),this._nodes=[new qm]}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 Lm(e,s,n)),s}const(e,r,n){return this._def(ur.varKinds.const,e,r,n)}let(e,r,n){return this._def(ur.varKinds.let,e,r,n)}var(e,r,n){return this._def(ur.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Zc(e,r,n))}add(e,r){return this._leafNode(new jm(e,ge.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==xe.nil&&this._leafNode(new Um(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,xe.addCodeArg)(r,o));return r.push("}"),new xe._Code(r)}if(e,r,n){if(this._blockNode(new Gn(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 Gn(e))}else(){return this._elseNode(new Bo)}endIf(){return this._endBlockNode(Gn,Bo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Fm(e),r)}forRange(e,r,n,o,s=this.opts.es5?ur.varKinds.var:ur.varKinds.let){let i=this._scope.toName(e);return this._for(new Bm(s,i,r,n),()=>o(i))}forOf(e,r,n,o=ur.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof xe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,xe._)`${i}.length`,a=>{this.var(s,(0,xe._)`${i}[${a}]`),n(s)})}return this._for(new Vc("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?ur.varKinds.var:ur.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,xe._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Vc("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Jn)}label(e){return this._leafNode(new zm(e))}break(e){return this._leafNode(new Dm(e))}return(e){let r=new di;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(di)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Zm;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new pi(s),r(s)}return n&&(this._currNode=o.finally=new hi,this.code(n)),this._endBlockNode(pi,hi)}throw(e){return this._leafNode(new Mm(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=xe.nil,n,o){return this._blockNode(new ui(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ui)}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 Gn))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}};ge.CodeGen=Vm;function Yn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Hc(t,e){return e instanceof xe._CodeOrName?Yn(t,e.names):t}function Zo(t,e,r){if(t instanceof xe.Name)return n(t);if(!o(t))return t;return new xe._Code(t._items.reduce((s,i)=>(i instanceof xe.Name&&(i=n(i)),i instanceof xe._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 xe._Code&&s._items.some(i=>i instanceof xe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function uz(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function eS(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,xe._)`!${Hm(t)}`}ge.not=eS;var dz=tS(ge.operators.AND);function pz(...t){return t.reduce(dz)}ge.and=pz;var hz=tS(ge.operators.OR);function mz(...t){return t.reduce(hz)}ge.or=mz;function tS(t){return(e,r)=>e===xe.nil?r:r===xe.nil?e:(0,xe._)`${Hm(e)} ${t} ${Hm(r)}`}function Hm(t){return t instanceof xe.Name?t:(0,xe._)`(${t})`}});var $e=B(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.checkStrictMode=ye.getErrorPath=ye.Type=ye.useFunc=ye.setEvaluated=ye.evaluatedPropsToName=ye.mergeEvaluated=ye.eachItem=ye.unescapeJsonPointer=ye.escapeJsonPointer=ye.escapeFragment=ye.unescapeFragment=ye.schemaRefOrVal=ye.schemaHasRulesButRef=ye.schemaHasRules=ye.checkUnknownRules=ye.alwaysValidSchema=ye.toHash=void 0;var Oe=me(),fz=ci();function gz(t){let e={};for(let r of t)e[r]=!0;return e}ye.toHash=gz;function yz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(oS(t,e),!sS(e,t.self.RULES.all))}ye.alwaysValidSchema=yz;function oS(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]||cS(t,`unknown keyword: "${s}"`)}ye.checkUnknownRules=oS;function sS(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ye.schemaHasRules=sS;function bz(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ye.schemaHasRulesButRef=bz;function wz({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)}`}ye.schemaRefOrVal=wz;function _z(t){return iS(decodeURIComponent(t))}ye.unescapeFragment=_z;function vz(t){return encodeURIComponent(Wm(t))}ye.escapeFragment=vz;function Wm(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ye.escapeJsonPointer=Wm;function iS(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ye.unescapeJsonPointer=iS;function kz(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ye.eachItem=kz;function rS({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}}ye.mergeEvaluated={props:rS({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} || {}`),Gm(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:aS}),items:rS({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 aS(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Oe._)`{}`);return e!==void 0&&Gm(t,r,e),r}ye.evaluatedPropsToName=aS;function Gm(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Oe._)`${e}${(0,Oe.getProperty)(n)}`,!0))}ye.setEvaluated=Gm;var nS={};function xz(t,e){return t.scopeValue("func",{ref:e,code:nS[e.code]||(nS[e.code]=new fz._Code(e.code))})}ye.useFunc=xz;var Km;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Km||(ye.Type=Km={}));function Sz(t,e,r){if(t instanceof Oe.Name){let n=e===Km.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():"/"+Wm(t)}ye.getErrorPath=Sz;function cS(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ye.checkStrictMode=cS});var Fr=B(Jm=>{"use strict";Object.defineProperty(Jm,"__esModule",{value:!0});var ft=me(),$z={data:new ft.Name("data"),valCxt:new ft.Name("valCxt"),instancePath:new ft.Name("instancePath"),parentData:new ft.Name("parentData"),parentDataProperty:new ft.Name("parentDataProperty"),rootData:new ft.Name("rootData"),dynamicAnchors:new ft.Name("dynamicAnchors"),vErrors:new ft.Name("vErrors"),errors:new ft.Name("errors"),this:new ft.Name("this"),self:new ft.Name("self"),scope:new ft.Name("scope"),json:new ft.Name("json"),jsonPos:new ft.Name("jsonPos"),jsonLen:new ft.Name("jsonLen"),jsonPart:new ft.Name("jsonPart")};Jm.default=$z});var mi=B(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.extendErrors=gt.resetErrorsCount=gt.reportExtraError=gt.reportError=gt.keyword$DataError=gt.keywordError=void 0;var Te=me(),Wc=$e(),kt=Fr();gt.keywordError={message:({keyword:t})=>(0,Te.str)`must pass "${t}" keyword validation`};gt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Te.str)`"${t}" keyword must be ${e} ($data)`:(0,Te.str)`"${t}" keyword is invalid ($data)`};function Tz(t,e=gt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=dS(t,e,r);n??(i||a)?lS(s,c):uS(o,(0,Te._)`[${c}]`)}gt.reportError=Tz;function Rz(t,e=gt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=dS(t,e,r);lS(o,a),s||i||uS(n,kt.default.vErrors)}gt.reportExtraError=Rz;function Ez(t,e){t.assign(kt.default.errors,e),t.if((0,Te._)`${kt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Te._)`${kt.default.vErrors}.length`,e),()=>t.assign(kt.default.vErrors,null)))}gt.resetErrorsCount=Ez;function Pz({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,kt.default.errors,a=>{t.const(i,(0,Te._)`${kt.default.vErrors}[${a}]`),t.if((0,Te._)`${i}.instancePath === undefined`,()=>t.assign((0,Te._)`${i}.instancePath`,(0,Te.strConcat)(kt.default.instancePath,s.errorPath))),t.assign((0,Te._)`${i}.schemaPath`,(0,Te.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Te._)`${i}.schema`,r),t.assign((0,Te._)`${i}.data`,n))})}gt.extendErrors=Pz;function lS(t,e){let r=t.const("err",e);t.if((0,Te._)`${kt.default.vErrors} === null`,()=>t.assign(kt.default.vErrors,(0,Te._)`[${r}]`),(0,Te._)`${kt.default.vErrors}.push(${r})`),t.code((0,Te._)`${kt.default.errors}++`)}function uS(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Te._)`new ${t.ValidationError}(${e})`):(r.assign((0,Te._)`${n}.errors`,e),r.return(!1))}var Xn={keyword:new Te.Name("keyword"),schemaPath:new Te.Name("schemaPath"),params:new Te.Name("params"),propertyName:new Te.Name("propertyName"),message:new Te.Name("message"),schema:new Te.Name("schema"),parentSchema:new Te.Name("parentSchema")};function dS(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Te._)`{}`:Az(t,e,r)}function Az(t,e,r={}){let{gen:n,it:o}=t,s=[Cz(o,r),Iz(t,r)];return Oz(t,e,s),n.object(...s)}function Cz({errorPath:t},{instancePath:e}){let r=e?(0,Te.str)`${t}${(0,Wc.getErrorPath)(e,Wc.Type.Str)}`:t;return[kt.default.instancePath,(0,Te.strConcat)(kt.default.instancePath,r)]}function Iz({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Te.str)`${e}/${t}`;return r&&(o=(0,Te.str)`${o}${(0,Wc.getErrorPath)(r,Wc.Type.Str)}`),[Xn.schemaPath,o]}function Oz(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([Xn.keyword,o],[Xn.params,typeof e=="function"?e(t):e||(0,Te._)`{}`]),c.messages&&n.push([Xn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Xn.schema,i],[Xn.parentSchema,(0,Te._)`${u}${p}`],[kt.default.data,s]),l&&n.push([Xn.propertyName,l])}});var hS=B(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.boolOrEmptySchema=Vo.topBoolOrEmptySchema=void 0;var Nz=mi(),Lz=me(),jz=Fr(),zz={message:"boolean schema is false"};function Dz(t){let{gen:e,schema:r,validateName:n}=t;r===!1?pS(t,!1):typeof r=="object"&&r.$async===!0?e.return(jz.default.data):(e.assign((0,Lz._)`${n}.errors`,null),e.return(!0))}Vo.topBoolOrEmptySchema=Dz;function Mz(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),pS(t)):r.var(e,!0)}Vo.boolOrEmptySchema=Mz;function pS(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,Nz.reportError)(o,zz,void 0,e)}});var Ym=B(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.getRules=Ho.isJSONType=void 0;var Uz=["string","number","integer","boolean","null","object","array"],qz=new Set(Uz);function Fz(t){return typeof t=="string"&&qz.has(t)}Ho.isJSONType=Fz;function Bz(){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:{}}}Ho.getRules=Bz});var Xm=B(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.shouldUseRule=dn.shouldUseGroup=dn.schemaHasRulesForType=void 0;function Zz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&mS(t,n)}dn.schemaHasRulesForType=Zz;function mS(t,e){return e.rules.some(r=>fS(t,r))}dn.shouldUseGroup=mS;function fS(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))}dn.shouldUseRule=fS});var fi=B(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.reportTypeError=yt.checkDataTypes=yt.checkDataType=yt.coerceAndCheckDataType=yt.getJSONTypes=yt.getSchemaTypes=yt.DataType=void 0;var Vz=Ym(),Hz=Xm(),Kz=mi(),pe=me(),gS=$e(),Ko;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ko||(yt.DataType=Ko={}));function Wz(t){let e=yS(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}yt.getSchemaTypes=Wz;function yS(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Vz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}yt.getJSONTypes=yS;function Gz(t,e){let{gen:r,data:n,opts:o}=t,s=Jz(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Hz.schemaHasRulesForType)(t,e[0]));if(i){let a=ef(e,n,o.strictNumbers,Ko.Wrong);r.if(a,()=>{s.length?Yz(t,e,s):tf(t)})}return i}yt.coerceAndCheckDataType=Gz;var bS=new Set(["string","number","integer","boolean","null"]);function Jz(t,e){return e?t.filter(r=>bS.has(r)||e==="array"&&r==="array"):[]}function Yz(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,pe._)`typeof ${o}`),a=n.let("coerced",(0,pe._)`undefined`);s.coerceTypes==="array"&&n.if((0,pe._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,pe._)`${o}[0]`).assign(i,(0,pe._)`typeof ${o}`).if(ef(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,pe._)`${a} !== undefined`);for(let l of r)(bS.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),tf(t),n.endIf(),n.if((0,pe._)`${a} !== undefined`,()=>{n.assign(o,a),Xz(t,a)});function c(l){switch(l){case"string":n.elseIf((0,pe._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,pe._)`"" + ${o}`).elseIf((0,pe._)`${o} === null`).assign(a,(0,pe._)`""`);return;case"number":n.elseIf((0,pe._)`${i} == "boolean" || ${o} === null
2485
2516
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,pe._)`+${o}`);return;case"integer":n.elseIf((0,pe._)`${i} === "boolean" || ${o} === null
2486
2517
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,pe._)`+${o}`);return;case"boolean":n.elseIf((0,pe._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,pe._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,pe._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,pe._)`${i} === "string" || ${i} === "number"
2487
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,pe._)`[${o}]`)}}}function Yz({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,pe._)`${e} !== undefined`,()=>t.assign((0,pe._)`${e}[${r}]`,n))}function Xm(t,e,r,n=Wo.Correct){let o=n===Wo.Correct?pe.operators.EQ:pe.operators.NEQ,s;switch(t){case"null":return(0,pe._)`${e} ${o} null`;case"array":s=(0,pe._)`Array.isArray(${e})`;break;case"object":s=(0,pe._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,pe._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,pe._)`typeof ${e} ${o} ${t}`}return n===Wo.Correct?s:(0,pe.not)(s);function i(a=pe.nil){return(0,pe.and)((0,pe._)`typeof ${e} == "number"`,a,r?(0,pe._)`isFinite(${e})`:pe.nil)}}yt.checkDataType=Xm;function Qm(t,e,r,n){if(t.length===1)return Xm(t[0],e,r,n);let o,s=(0,fS.toHash)(t);if(s.array&&s.object){let i=(0,pe._)`typeof ${e} != "object"`;o=s.null?i:(0,pe._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=pe.nil;s.number&&delete s.integer;for(let i in s)o=(0,pe.and)(o,Xm(i,e,r,n));return o}yt.checkDataTypes=Qm;var Xz={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,pe._)`{type: ${t}}`:(0,pe._)`{type: ${e}}`};function ef(t){let e=Qz(t);(0,Hz.reportError)(e,Xz)}yt.reportTypeError=ef;function Qz(t){let{gen:e,data:r,schema:n}=t,o=(0,fS.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var wS=B(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.assignDefaults=void 0;var Go=me(),eD=$e();function tD(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)bS(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>bS(t,s,o.default))}Gc.assignDefaults=tD;function bS(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Go._)`${s}${(0,Go.getProperty)(e)}`;if(o){(0,eD.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Go._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Go._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Go._)`${a} = ${(0,Go.stringify)(r)}`)}});var Xt=B(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.validateUnion=Ce.validateArray=Ce.usePattern=Ce.callValidateCode=Ce.schemaProperties=Ce.allSchemaProperties=Ce.noPropertyInData=Ce.propertyInData=Ce.isOwnProperty=Ce.hasPropFunc=Ce.reportMissingProp=Ce.checkMissingProp=Ce.checkReportMissingProp=void 0;var Ue=me(),tf=$e(),pn=Fr(),rD=$e();function nD(t,e){let{gen:r,data:n,it:o}=t;r.if(nf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ue._)`${e}`},!0),t.error()})}Ce.checkReportMissingProp=nD;function oD({gen:t,data:e,it:{opts:r}},n,o){return(0,Ue.or)(...n.map(s=>(0,Ue.and)(nf(t,e,s,r.ownProperties),(0,Ue._)`${o} = ${s}`)))}Ce.checkMissingProp=oD;function sD(t,e){t.setParams({missingProperty:e},!0),t.error()}Ce.reportMissingProp=sD;function _S(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ue._)`Object.prototype.hasOwnProperty`})}Ce.hasPropFunc=_S;function rf(t,e,r){return(0,Ue._)`${_S(t)}.call(${e}, ${r})`}Ce.isOwnProperty=rf;function iD(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} !== undefined`;return n?(0,Ue._)`${o} && ${rf(t,e,r)}`:o}Ce.propertyInData=iD;function nf(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} === undefined`;return n?(0,Ue.or)(o,(0,Ue.not)(rf(t,e,r))):o}Ce.noPropertyInData=nf;function vS(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ce.allSchemaProperties=vS;function aD(t,e){return vS(e).filter(r=>!(0,tf.alwaysValidSchema)(t,e[r]))}Ce.schemaProperties=aD;function cD({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Ue._)`${t}, ${e}, ${n}${o}`:e,p=[[pn.default.instancePath,(0,Ue.strConcat)(pn.default.instancePath,s)],[pn.default.parentData,i.parentData],[pn.default.parentDataProperty,i.parentDataProperty],[pn.default.rootData,pn.default.rootData]];i.opts.dynamicRef&&p.push([pn.default.dynamicAnchors,pn.default.dynamicAnchors]);let w=(0,Ue._)`${u}, ${r.object(...p)}`;return c!==Ue.nil?(0,Ue._)`${a}.call(${c}, ${w})`:(0,Ue._)`${a}(${w})`}Ce.callValidateCode=cD;var lD=(0,Ue._)`new RegExp`;function uD({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,Ue._)`${o.code==="new RegExp"?lD:(0,rD.useFunc)(t,o)}(${r}, ${n})`})}Ce.usePattern=uD;function dD(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,Ue._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:tf.Type.Num},s),e.if((0,Ue.not)(s),a)})}}Ce.validateArray=dD;function pD(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,tf.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,Ue._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Ue.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ce.validateUnion=pD});var SS=B(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.validateKeywordUsage=Sr.validSchemaType=Sr.funcKeywordCode=Sr.macroKeywordCode=void 0;var kt=me(),Qn=Fr(),hD=Xt(),mD=mi();function fD(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=kS(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:kt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Sr.macroKeywordCode=fD;function gD(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;bD(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=kS(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&&xS(t),$(()=>t.error());else{let R=e.async?f():m();e.modifying&&xS(t),$(()=>yD(t,R))}}function f(){let R=n.let("ruleErrs",null);return n.try(()=>b((0,kt._)`await `),A=>n.assign(p,!1).if((0,kt._)`${A} instanceof ${c.ValidationError}`,()=>n.assign(R,(0,kt._)`${A}.errors`),()=>n.throw(A))),R}function m(){let R=(0,kt._)`${u}.errors`;return n.assign(R,null),b(kt.nil),R}function b(R=e.async?(0,kt._)`await `:kt.nil){let A=c.opts.passContext?Qn.default.this:Qn.default.self,O=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,kt._)`${R}${(0,hD.callValidateCode)(t,u,A,O)}`,e.modifying)}function $(R){var A;n.if((0,kt.not)((A=e.valid)!==null&&A!==void 0?A:p),R)}}Sr.funcKeywordCode=gD;function xS(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,kt._)`${n.parentData}[${n.parentDataProperty}]`))}function yD(t,e){let{gen:r}=t;r.if((0,kt._)`Array.isArray(${e})`,()=>{r.assign(Qn.default.vErrors,(0,kt._)`${Qn.default.vErrors} === null ? ${e} : ${Qn.default.vErrors}.concat(${e})`).assign(Qn.default.errors,(0,kt._)`${Qn.default.vErrors}.length`),(0,mD.extendErrors)(t)},()=>t.error())}function bD({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function kS(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,kt.stringify)(r)})}function wD(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")}Sr.validSchemaType=wD;function _D({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)}}Sr.validateKeywordUsage=_D});var TS=B(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.extendSubschemaMode=hn.extendSubschemaData=hn.getSubschema=void 0;var $r=me(),$S=$e();function vD(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,$r._)`${t.schemaPath}${(0,$r.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,$r._)`${t.schemaPath}${(0,$r.getProperty)(e)}${(0,$r.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,$S.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')}hn.getSubschema=vD;function xD(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,$r._)`${e.data}${(0,$r.getProperty)(r)}`,!0);c(w),t.errorPath=(0,$r.str)`${l}${(0,$S.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,$r._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof $r.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]}}hn.extendSubschemaData=xD;function kD(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}hn.extendSubschemaMode=kD});var of=B((EG,RS)=>{"use strict";RS.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 PS=B((PG,ES)=>{"use strict";var mn=ES.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(){};Jc(e,n,o,t,"",t)};mn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};mn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};mn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};mn.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 Jc(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 mn.arrayKeywords)for(var w=0;w<p.length;w++)Jc(t,e,r,p[w],o+"/"+u+"/"+w,s,o,u,n,w)}else if(u in mn.propsKeywords){if(p&&typeof p=="object")for(var f in p)Jc(t,e,r,p[f],o+"/"+u+"/"+SD(f),s,o,u,n,f)}else(u in mn.keywords||t.allKeys&&!(u in mn.skipKeywords))&&Jc(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function SD(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gi=B(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getSchemaRefs=Ot.resolveUrl=Ot.normalizeId=Ot._getFullPath=Ot.getFullPath=Ot.inlineRef=void 0;var $D=$e(),TD=of(),RD=PS(),ED=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function PD(t,e=!0){return typeof t=="boolean"?!0:e===!0?!sf(t):e?AS(t)<=e:!1}Ot.inlineRef=PD;var AD=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function sf(t){for(let e in t){if(AD.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(sf)||typeof r=="object"&&sf(r))return!0}return!1}function AS(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!ED.has(r)&&(typeof t[r]=="object"&&(0,$D.eachItem)(t[r],n=>e+=AS(n)),e===1/0))return 1/0}return e}function CS(t,e="",r){r!==!1&&(e=Jo(e));let n=t.parse(e);return IS(t,n)}Ot.getFullPath=CS;function IS(t,e){return t.serialize(e).split("#")[0]+"#"}Ot._getFullPath=IS;var CD=/#\/?$/;function Jo(t){return t?t.replace(CD,""):""}Ot.normalizeId=Jo;function ID(t,e,r){return r=Jo(r),t.resolve(e,r)}Ot.resolveUrl=ID;var OD=/^[a-z_][-a-z0-9._]*$/i;function ND(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Jo(t[r]||e),s={"":o},i=CS(n,o,!1),a={},c=new Set;return RD(t,{allKeys:!0},(p,w,f,m)=>{if(m===void 0)return;let b=i+w,$=s[m];typeof p[r]=="string"&&($=R.call(this,p[r])),A.call(this,p.$anchor),A.call(this,p.$dynamicAnchor),s[w]=$;function R(O){let q=this.opts.uriResolver.resolve;if(O=Jo($?q($,O):O),c.has(O))throw u(O);c.add(O);let Y=this.refs[O];return typeof Y=="string"&&(Y=this.refs[Y]),typeof Y=="object"?l(p,Y.schema,O):O!==Jo(b)&&(O[0]==="#"?(l(p,a[O],O),a[O]=p):this.refs[O]=b),O}function A(O){if(typeof O=="string"){if(!OD.test(O))throw new Error(`invalid anchor "${O}"`);R.call(this,`#${O}`)}}}),a;function l(p,w,f){if(w!==void 0&&!TD(p,w))throw u(f)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Ot.getSchemaRefs=ND});var wi=B(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.getData=fn.KeywordCxt=fn.validateFunctionCode=void 0;var zS=pS(),OS=fi(),cf=Ym(),Yc=fi(),LD=wS(),bi=SS(),af=TS(),te=me(),ue=Fr(),jD=gi(),Br=$e(),yi=mi();function zD(t){if(US(t)&&(qS(t),MS(t))){UD(t);return}DS(t,()=>(0,zS.topBoolOrEmptySchema)(t))}fn.validateFunctionCode=zD;function DS({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,te._)`${ue.default.data}, ${ue.default.valCxt}`,n.$async,()=>{t.code((0,te._)`"use strict"; ${NS(r,o)}`),MD(t,o),t.code(s)}):t.func(e,(0,te._)`${ue.default.data}, ${DD(o)}`,n.$async,()=>t.code(NS(r,o)).code(s))}function DD(t){return(0,te._)`{${ue.default.instancePath}="", ${ue.default.parentData}, ${ue.default.parentDataProperty}, ${ue.default.rootData}=${ue.default.data}${t.dynamicRef?(0,te._)`, ${ue.default.dynamicAnchors}={}`:te.nil}}={}`}function MD(t,e){t.if(ue.default.valCxt,()=>{t.var(ue.default.instancePath,(0,te._)`${ue.default.valCxt}.${ue.default.instancePath}`),t.var(ue.default.parentData,(0,te._)`${ue.default.valCxt}.${ue.default.parentData}`),t.var(ue.default.parentDataProperty,(0,te._)`${ue.default.valCxt}.${ue.default.parentDataProperty}`),t.var(ue.default.rootData,(0,te._)`${ue.default.valCxt}.${ue.default.rootData}`),e.dynamicRef&&t.var(ue.default.dynamicAnchors,(0,te._)`${ue.default.valCxt}.${ue.default.dynamicAnchors}`)},()=>{t.var(ue.default.instancePath,(0,te._)`""`),t.var(ue.default.parentData,(0,te._)`undefined`),t.var(ue.default.parentDataProperty,(0,te._)`undefined`),t.var(ue.default.rootData,ue.default.data),e.dynamicRef&&t.var(ue.default.dynamicAnchors,(0,te._)`{}`)})}function UD(t){let{schema:e,opts:r,gen:n}=t;DS(t,()=>{r.$comment&&e.$comment&&BS(t),VD(t),n.let(ue.default.vErrors,null),n.let(ue.default.errors,0),r.unevaluated&&qD(t),FS(t),WD(t)})}function qD(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,te._)`${r}.evaluated`),e.if((0,te._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,te._)`${t.evaluated}.props`,(0,te._)`undefined`)),e.if((0,te._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,te._)`${t.evaluated}.items`,(0,te._)`undefined`))}function NS(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,te._)`/*# sourceURL=${r} */`:te.nil}function FD(t,e){if(US(t)&&(qS(t),MS(t))){BD(t,e);return}(0,zS.boolOrEmptySchema)(t,e)}function MS({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 US(t){return typeof t.schema!="boolean"}function BD(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&BS(t),HD(t),KD(t);let s=n.const("_errs",ue.default.errors);FS(t,s),n.var(e,(0,te._)`${s} === ${ue.default.errors}`)}function qS(t){(0,Br.checkUnknownRules)(t),ZD(t)}function FS(t,e){if(t.opts.jtd)return LS(t,[],!1,e);let r=(0,OS.getSchemaTypes)(t.schema),n=(0,OS.coerceAndCheckDataType)(t,r);LS(t,r,!n,e)}function ZD(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Br.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function VD(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Br.checkStrictMode)(t,"default is ignored in the schema root")}function HD(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,jD.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function KD(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function BS({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,te._)`${ue.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,te.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,te._)`${ue.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function WD(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,te._)`${ue.default.errors} === 0`,()=>e.return(ue.default.data),()=>e.throw((0,te._)`new ${o}(${ue.default.vErrors})`)):(e.assign((0,te._)`${n}.errors`,ue.default.vErrors),s.unevaluated&&GD(t),e.return((0,te._)`${ue.default.errors} === 0`))}function GD({gen:t,evaluated:e,props:r,items:n}){r instanceof te.Name&&t.assign((0,te._)`${e}.props`,r),n instanceof te.Name&&t.assign((0,te._)`${e}.items`,n)}function LS(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,Br.schemaHasRulesButRef)(s,u))){o.block(()=>VS(t,"$ref",u.all.$ref.definition));return}c.jtd||JD(t,e),o.block(()=>{for(let w of u.rules)p(w);p(u.post)});function p(w){(0,cf.shouldUseGroup)(s,w)&&(w.type?(o.if((0,Yc.checkDataType)(w.type,i,c.strictNumbers)),jS(t,w),e.length===1&&e[0]===w.type&&r&&(o.else(),(0,Yc.reportTypeError)(t)),o.endIf()):jS(t,w),a||o.if((0,te._)`${ue.default.errors} === ${n||0}`))}}function jS(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,LD.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,cf.shouldUseRule)(n,s)&&VS(t,s.keyword,s.definition,e.type)})}function JD(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(YD(t,e),t.opts.allowUnionTypes||XD(t,e),QD(t,t.dataTypes))}function YD(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{ZS(t.dataTypes,r)||lf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),t1(t,e)}}function XD(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&lf(t,"use allowUnionTypes to allow union type keyword")}function QD(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,cf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>e1(e,i))&&lf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function e1(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function ZS(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function t1(t,e){let r=[];for(let n of t.dataTypes)ZS(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function lf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Br.checkStrictMode)(t,e,t.opts.strictTypes)}var Xc=class{constructor(e,r,n){if((0,bi.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,Br.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",HS(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,bi.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",ue.default.errors))}result(e,r,n){this.failResult((0,te.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,te.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,te._)`${r} !== undefined && (${(0,te.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?yi.reportExtraError:yi.reportError)(this,this.def.error,r)}$dataError(){(0,yi.reportError)(this,this.def.$dataError||yi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,yi.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=te.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=te.nil,r=te.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,te.or)((0,te._)`${o} === undefined`,r)),e!==te.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==te.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,te.or)(i(),a());function i(){if(n.length){if(!(r instanceof te.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,te._)`${(0,Yc.checkDataTypes)(c,r,s.opts.strictNumbers,Yc.DataType.Wrong)}`}return te.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,te._)`!${c}(${r})`}return te.nil}}subschema(e,r){let n=(0,af.getSubschema)(this.it,e);(0,af.extendSubschemaData)(n,this.it,e),(0,af.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return FD(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Br.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Br.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,te.Name)),!0}};fn.KeywordCxt=Xc;function VS(t,e,r,n){let o=new Xc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,bi.funcKeywordCode)(o,r):"macro"in r?(0,bi.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,bi.funcKeywordCode)(o,r)}var r1=/^\/(?:[^~]|~0|~1)*$/,n1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function HS(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ue.default.rootData;if(t[0]==="/"){if(!r1.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ue.default.rootData}else{let l=n1.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,te._)`${s}${(0,te.getProperty)((0,Br.unescapeJsonPointer)(l))}`,i=(0,te._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}fn.getData=HS});var Qc=B(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var uf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};df.default=uf});var _i=B(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var pf=gi(),hf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,pf.resolveUrl)(e,r,n),this.missingSchema=(0,pf.normalizeId)((0,pf.getFullPath)(e,this.missingRef))}};mf.default=hf});var tl=B(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.resolveSchema=Qt.getCompilingSchema=Qt.resolveRef=Qt.compileSchema=Qt.SchemaEnv=void 0;var dr=me(),o1=Qc(),eo=Fr(),pr=gi(),KS=$e(),s1=wi(),Yo=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,pr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Qt.SchemaEnv=Yo;function gf(t){let e=WS.call(this,t);if(e)return e;let r=(0,pr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new dr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:o1.default,code:(0,dr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:eo.default.data,parentData:eo.default.parentData,parentDataProperty:eo.default.parentDataProperty,dataNames:[eo.default.data],dataPathArr:[dr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,dr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:dr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,dr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,s1.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(eo.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let f=new Function(`${eo.default.self}`,`${eo.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:b}=l;f.evaluated={props:m instanceof dr.Name?void 0:m,items:b instanceof dr.Name?void 0:b,dynamicProps:m instanceof dr.Name,dynamicItems:b instanceof dr.Name},f.source&&(f.source.evaluated=(0,dr.stringify)(f.evaluated))}return t.validate=f,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)}}Qt.compileSchema=gf;function i1(t,e,r){var n;r=(0,pr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=l1.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 Yo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=a1.call(this,s)}Qt.resolveRef=i1;function a1(t){return(0,pr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:gf.call(this,t)}function WS(t){for(let e of this._compilations)if(c1(e,t))return e}Qt.getCompilingSchema=WS;function c1(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function l1(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||el.call(this,t,e)}function el(t,e){let r=this.opts.uriResolver.parse(e),n=(0,pr._getFullPath)(this.opts.uriResolver,r),o=(0,pr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return ff.call(this,r,t);let s=(0,pr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=el.call(this,t,i);return typeof a?.schema!="object"?void 0:ff.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||gf.call(this,i),s===(0,pr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,pr.resolveUrl)(this.opts.uriResolver,o,l)),new Yo({schema:a,schemaId:c,root:t,baseId:o})}return ff.call(this,r,i)}}Qt.resolveSchema=el;var u1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ff(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,KS.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!u1.has(a)&&l&&(e=(0,pr.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,KS.schemaHasRulesButRef)(r,this.RULES)){let a=(0,pr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=el.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Yo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var GS=B((LG,d1)=>{d1.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 xf=B((jG,n$)=>{"use strict";var p1=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),bf=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),h1=RegExp.prototype.test.bind(/^\d*$/u),to=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),wf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),YS=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),_f=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),m1=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Nt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Nt[e]="%"+t[e>>4]+t[e&15]}function bt(t){return t<2048?Nt[192|t>>6]+Nt[128|t&63]:t<65536?Nt[224|t>>12]+Nt[128|t>>6&63]+Nt[128|t&63]:Nt[240|t>>18]+Nt[128|t>>12&63]+Nt[128|t>>6&63]+Nt[128|t&63]}function f1(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 g1=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),y1=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),b1=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),w1=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _1(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!b1(t[e])){if(t[e]==="%"&&e+2<t.length&&to(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function JS(t){let e=-1,r=0,n=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(n===-1&&(n=a),o++,o>r&&(r=o,e=n)):(n=-1,o=0);if(r<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+r).join(":");return s+"::"+i}function v1(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let r=e===-1?t.split(":"):t.slice(0,e).split(":"),n=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let o=r.concat(n),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&n.length===0||!bf(c))return;s+=2;continue}if(!g1(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:JS(o);if(s>=8)return;let i=o.slice(0,r.length);for(let a=s;a<8;a++)i.push("0");for(let a=r.length;a<o.length;a++)i.push(o[a]);return JS(i)}function yf(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let n=e?t.slice(1,-1):t;if(e&&y1(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x1(n,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=n.indexOf("%");if(s!==-1){let a=n.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=n.slice(s+a),!_1(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=v1(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function x1(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function XS(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("")}function k1(t){if(t===""||t[0]==="/")return XS(t);let e=t.split("/"),r=e.length-1,n=[],o=!1;for(let s=0;s<=r;s++){let i=e[s];i==="."||i===".."?(i===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),o=s===r):n.push(i)}return o&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var S1={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},$1=/[@/?#:]/g,T1=/[@/?#]/g;function QS(t,e){let r=e?T1:$1;return r.lastIndex=0,t.replace(r,n=>S1[n])}function e$(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(to(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&wf(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function R1(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(to(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&wf(i)?e+=i:e+="%"+s,r+=2;continue}}if(YS(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=r$(o)?n:Nt[o];else if(o<55296||o>57343)e+=bt(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=bt(65536+(o-55296<<10)+(s-56320)),r++):e+=bt(65533)}else e+=bt(65533)}}return e}function E1(t,e=!1){let r="",n=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(to(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),YS(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=Nt[i];else if(i<55296||i>57343)r+=bt(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=bt(65536+(i-55296<<10)+(a-56320)),o++):r+=bt(65533)}else r+=bt(65533)}}return r}function vf(t,e){let r="";for(let n=0;n<t.length;n++){let o=t[n];if(o==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(to(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=Nt[s];else if(s<55296||s>57343)r+=bt(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=bt(65536+(s-55296<<10)+(i-56320)),n++):r+=bt(65533)}else r+=bt(65533)}}return r}function t$(t){return vf(t,m1)}function P1(t){return vf(t,_f)}function A1(t){return vf(t,_f)}function r$(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function C1(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(to(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));wf(i)?e+=i:e+="%"+s,r+=2;continue}}if(_f(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=r$(o)?n:Nt[o];else if(o<55296||o>57343)e+=bt(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=bt(65536+(o-55296<<10)+(s-56320)),r++):e+=bt(65533)}else e+=bt(65533)}}return e}function I1(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(to(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function O1(t){let e=[];if(t.userinfo!==void 0&&(e.push(t$(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!bf(r)){let n=yf(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=e$(r,!0),n=yf(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=QS(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!h1(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}n$.exports={nonSimpleDomain:w1,recomposeAuthority:O1,reescapeHostDelimiters:QS,normalizePercentEncoding:e$,normalizePathEncoding:R1,serializePathEncoding:E1,normalizeQueryFragmentEncoding:C1,encodeUserinfo:t$,encodeQuery:P1,encodeFragment:A1,escapePreservingEscapes:I1,removeDotSegments:XS,removeDotSegmentsRelative:k1,isIPv4:bf,isUUID:p1,normalizeIPv6:yf,stringArrayToHexStripped:f1}});var c$=B((zG,a$)=>{"use strict";var{isUUID:N1}=xf(),L1=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,j1=["http","https","ws","wss","urn","urn:uuid"];function z1(t){return j1.indexOf(t)!==-1}function kf(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 o$(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function s$(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 D1(t){return t.secure=kf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function M1(t){if((t.port===(kf(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=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function U1(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(L1);if(r&&r[0]===t.path){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Sf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function q1(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=Sf(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 F1(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!N1(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function B1(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var i$={scheme:"http",domainHost:!0,parse:o$,serialize:s$},Z1={scheme:"https",domainHost:i$.domainHost,parse:o$,serialize:s$},rl={scheme:"ws",domainHost:!0,parse:D1,serialize:M1},V1={scheme:"wss",domainHost:rl.domainHost,parse:rl.parse,serialize:rl.serialize},H1={scheme:"urn",parse:U1,serialize:q1,skipNormalize:!0},K1={scheme:"urn:uuid",parse:F1,serialize:B1,skipNormalize:!0},nl={http:i$,https:Z1,ws:rl,wss:V1,urn:H1,"urn:uuid":K1};Object.setPrototypeOf(nl,null);function Sf(t){return t&&(nl[t]||nl[t.toLowerCase()])||void 0}a$.exports={wsIsSecure:kf,SCHEMES:nl,isValidSchemeName:z1,getSchemeHandler:Sf}});var k$=B((DG,cl)=>{"use strict";var{normalizeIPv6:h$,removeDotSegments:xi,removeDotSegmentsRelative:m$,recomposeAuthority:W1,normalizePercentEncoding:$f,normalizePathEncoding:G1,serializePathEncoding:l$,normalizeQueryFragmentEncoding:u$,encodeQuery:J1,encodeFragment:Y1,reescapeHostDelimiters:X1,isIPv4:f$,nonSimpleDomain:Q1}=xf(),{SCHEMES:g$,getSchemeHandler:Tf}=c$(),y$=/^[A-Za-z][A-Za-z0-9+.-]*$/u,b$="URI scheme is malformed.",ol="URI host is malformed.",eM=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function d$(t){let e=String(t);if(!y$.test(e))throw new TypeError(b$);return e}function tM(t,e){return typeof t=="string"?t=uM(t,e):typeof t=="object"&&(t=il(ro(t,e),e)),t}function rM(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:l}=sl(t,n),{parsed:u,malformedAuthorityOrPort:p,malformedPercentEncoding:w,malformedSchemeSpecific:f,malformedHost:m,malformedScheme:b}=sl(e,n);if(s||p||i||w||a||f||c||m||l||b)throw new Error(o.error||u.error||"URI is malformed.");let $=w$(o,u,n,!0),R=Tf(r&&r.scheme||$.scheme),A=$.host,O=A!==void 0&&A!==""&&(f$(A)||h$(A).isIPV6);if(v$($,r||{},R,O))throw new Error(ol);_$($,r||{},R,O);let q=A&&A.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(A);if($.error&&!q)throw new Error($.error);return n.skipEscape=!0,ro($,n)}function w$(t,e,r,n){let o={};if(n||(t=il(ro(t,r),r),e=il(ro(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=xi(e.path||""),o.query=e.query;else{if(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=xi(e.path||""),o.query=e.query;else{if(!e.path)o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query;else{if(e.path[0]==="/")o.path=xi(e.path);else{let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0;s&&!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=t.scheme===void 0&&!s&&o.path[0]!=="/"?m$(o.path):xi(o.path)}o.query=e.query}o.userinfo=t.userinfo,o.host=t.host,o.port=t.port}o.scheme=t.scheme}return o.fragment=e.fragment,o}function nM(t,e,r){let n=p$(t,r),o=p$(e,r);return n!==void 0&&o!==void 0&&n===o}function ro(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=[];r.scheme&&(r.scheme=d$(r.scheme));let s=Tf(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=(r.scheme===void 0||n.reference==="suffix")&&!i,c=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=$f(r.path):r.path=l$(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=d$(r.scheme),o.push(r.scheme,":"));let l=W1(r);if(l!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(l),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(u=a&&u[0]!=="/"?m$(u):xi(u)),a&&(u=l$(u,!0)),l===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return r.query!==void 0&&o.push("?",J1(r.query)),r.fragment!==void 0&&o.push("#",Y1(r.fragment)),o.join("")}var oM=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,sM=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,iM=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function aM(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 vi(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function al(t){return t[0]==="["&&t[t.length-1]==="]"}function cM(t){let e=t[4];return vi(t[3])||e!==void 0&&!al(e)&&vi(e)||vi(t[6])||vi(t[7])||vi(t[8])}function _$(t,e,r,n){if(v$(t,e,r,n))return t.error=t.error||ol,!0;if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!al(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&Q1(t.host)){let o;try{o=new URL("http://"+t.host)}catch(s){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!lM(o))return t.error=t.error||ol,!0;t.host=o.hostname}return!1}function v$(t,e,r,n){return!!(t.host&&n===!1&&!al(t.host)&&(e.domainHost||r&&r.domainHost)&&eM.test(t.host))}function lM(t){return t.username===""&&t.password===""&&t.port===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&t.hostname!==""}function sl(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,i=!1,a=!1,c=!1,l=!1,u=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let p=t.match(sM);p!==null&&p[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let w=t.match(iM);if(w!==null){let m=w[1],b=m.replace(/[\t\n\r]/g,"");b.length>=2&&(b.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):m.length!==b.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let f=t.match(oM);if(f){n.scheme=f[1],n.userinfo=f[3],n.host=f[4],n.port=parseInt(f[5],10),n.path=f[6]||"",n.query=f[7],n.fragment=f[8],n.scheme!==void 0&&(y$.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||b$,l=!0)),s=cM(f),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=f[5]);let m=aM(n,f);if(m!==void 0&&(n.error=n.error||m,o=!0),n.host)if(f$(n.host)===!1){let R=al(n.host),A=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,O=h$(n.host);u=O.isIPV6||O.isIPVFuture===!0,c=A&&(!R||O.error===!0),n.host=u?O.host:O.host.toLowerCase(),c&&(n.error=n.error||ol,o=!0)}else u=!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 b=Tf(r.scheme||n.scheme);if(c||(a=_$(n,r,b,u)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let $=u?n.host:$f(n.host,!0);u||($=$f($.toLowerCase())),n.host=u||r.scheme!=="null"?X1($,u):$}(!b||b&&!b.skipNormalize)&&(n.path&&(n.path=G1(n.path)),n.query&&(n.query=u$(n.query)),n.fragment&&(n.fragment=u$(n.fragment))),b&&b.parse&&(b.parse(n,r),b===g$.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:l}}function il(t,e){return sl(t,e).parsed}function uM(t,e){return x$(t,e).normalized}function x$(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=sl(t,e);return{normalized:n||o||s||i||a?t:ro(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function p$(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:ro(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=x$(r,e);return o||s||i||a||c?void 0:n}var Rf={SCHEMES:g$,normalize:tM,resolve:rM,resolveComponent:w$,equal:nM,serialize:ro,parse:il};cl.exports=Rf;cl.exports.default=Rf;cl.exports.fastUri=Rf});var $$=B(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var S$=k$();S$.code='require("ajv/dist/runtime/uri").default';Ef.default=S$});var O$=B(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.CodeGen=pt.Name=pt.nil=pt.stringify=pt.str=pt._=pt.KeywordCxt=void 0;var dM=wi();Object.defineProperty(pt,"KeywordCxt",{enumerable:!0,get:function(){return dM.KeywordCxt}});var Xo=me();Object.defineProperty(pt,"_",{enumerable:!0,get:function(){return Xo._}});Object.defineProperty(pt,"str",{enumerable:!0,get:function(){return Xo.str}});Object.defineProperty(pt,"stringify",{enumerable:!0,get:function(){return Xo.stringify}});Object.defineProperty(pt,"nil",{enumerable:!0,get:function(){return Xo.nil}});Object.defineProperty(pt,"Name",{enumerable:!0,get:function(){return Xo.Name}});Object.defineProperty(pt,"CodeGen",{enumerable:!0,get:function(){return Xo.CodeGen}});var pM=Qc(),A$=_i(),hM=Jm(),ki=tl(),mM=me(),Si=gi(),ll=fi(),Af=$e(),T$=GS(),fM=$$(),C$=(t,e)=>new RegExp(t,e);C$.code="new RegExp";var gM=["removeAdditional","useDefaults","coerceTypes"],yM=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),bM={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."},wM={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},R$=200;function _M(t){var e,r,n,o,s,i,a,c,l,u,p,w,f,m,b,$,R,A,O,q,Y,De,Qe,zt,Vr;let fr=t.strict,Hr=(e=t.code)===null||e===void 0?void 0:e.optimize,Di=Hr===!0||Hr===void 0?1:Hr||0,wn=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:C$,Pr=(o=t.uriResolver)!==null&&o!==void 0?o:fM.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:fr)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:fr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:fr)!==null&&u!==void 0?u:"log",strictTuples:(w=(p=t.strictTuples)!==null&&p!==void 0?p:fr)!==null&&w!==void 0?w:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:fr)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Di,regExp:wn}:{optimize:Di,regExp:wn},loopRequired:(b=t.loopRequired)!==null&&b!==void 0?b:R$,loopEnum:($=t.loopEnum)!==null&&$!==void 0?$:R$,meta:(R=t.meta)!==null&&R!==void 0?R:!0,messages:(A=t.messages)!==null&&A!==void 0?A:!0,inlineRefs:(O=t.inlineRefs)!==null&&O!==void 0?O:!0,schemaId:(q=t.schemaId)!==null&&q!==void 0?q:"$id",addUsedSchema:(Y=t.addUsedSchema)!==null&&Y!==void 0?Y:!0,validateSchema:(De=t.validateSchema)!==null&&De!==void 0?De:!0,validateFormats:(Qe=t.validateFormats)!==null&&Qe!==void 0?Qe:!0,unicodeRegExp:(zt=t.unicodeRegExp)!==null&&zt!==void 0?zt:!0,int32range:(Vr=t.int32range)!==null&&Vr!==void 0?Vr:!0,uriResolver:Pr}}var $i=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,..._M(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new mM.ValueScope({scope:{},prefixes:yM,es5:r,lines:n}),this.logger=TM(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,hM.getRules)(),E$.call(this,bM,e,"NOT SUPPORTED"),E$.call(this,wM,e,"DEPRECATED","warn"),this._metaOpts=SM.call(this),e.formats&&xM.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&kM.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),vM.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=T$;n==="id"&&(o={...T$},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 A$.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,Si.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=P$.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ki.SchemaEnv({schema:{},schemaId:n});if(r=ki.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=P$.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,Si.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(EM.call(this,n,r),!r)return(0,Af.eachItem)(n,s=>Pf.call(this,s)),this;AM.call(this,r);let o={...r,type:(0,ll.getJSONTypes)(r.type),schemaType:(0,ll.getJSONTypes)(r.schemaType)};return(0,Af.eachItem)(n,o.type.length===0?s=>Pf.call(this,s,o):s=>o.type.forEach(i=>Pf.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]=I$(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,Si.normalizeId)(i||n);let l=Si.getSchemaRefs.call(this,e,n);return c=new ki.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):ki.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{ki.compileSchema.call(this,e)}finally{this.opts=r}}};$i.ValidationError=pM.default;$i.MissingRefError=A$.default;pt.default=$i;function E$(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 P$(t){return t=(0,Si.normalizeId)(t),this.schemas[t]||this.refs[t]}function vM(){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 xM(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function kM(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 SM(){let t={...this.opts};for(let e of gM)delete t[e];return t}var $M={log(){},warn(){},error(){}};function TM(t){if(t===!1)return $M;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 RM=/^[a-z_$][a-z0-9_$:-]*$/i;function EM(t,e){let{RULES:r}=this;if((0,Af.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!RM.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 Pf(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,ll.getJSONTypes)(e.type),schemaType:(0,ll.getJSONTypes)(e.schemaType)}};e.before?PM.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 PM(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 AM(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=I$(e)),t.validateSchema=this.compile(e,!0))}var CM={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function I$(t){return{anyOf:[t,CM]}}});var N$=B(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var IM={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Cf.default=IM});var D$=B(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.callRef=no.getValidate=void 0;var OM=_i(),L$=Xt(),Lt=me(),Qo=Fr(),j$=tl(),ul=$e(),NM={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=j$.resolveRef.call(c,l,o,r);if(u===void 0)throw new OM.default(n.opts.uriResolver,o,r);if(u instanceof j$.SchemaEnv)return w(u);return f(u);function p(){if(s===l)return dl(t,i,s,s.$async);let m=e.scopeValue("root",{ref:l});return dl(t,(0,Lt._)`${m}.validate`,l,l.$async)}function w(m){let b=z$(t,m);dl(t,b,m,m.$async)}function f(m){let b=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Lt.stringify)(m)}:{ref:m}),$=e.name("valid"),R=t.subschema({schema:m,dataTypes:[],schemaPath:Lt.nil,topSchemaRef:b,errSchemaPath:r},$);t.mergeEvaluated(R),t.ok($)}}};function z$(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Lt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}no.getValidate=z$;function dl(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Qo.default.this:Lt.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Lt._)`await ${(0,L$.callValidateCode)(t,e,l)}`),f(e),i||o.assign(m,!0)},b=>{o.if((0,Lt._)`!(${b} instanceof ${s.ValidationError})`,()=>o.throw(b)),w(b),i||o.assign(m,!1)}),t.ok(m)}function p(){t.result((0,L$.callValidateCode)(t,e,l),()=>f(e),()=>w(e))}function w(m){let b=(0,Lt._)`${m}.errors`;o.assign(Qo.default.vErrors,(0,Lt._)`${Qo.default.vErrors} === null ? ${b} : ${Qo.default.vErrors}.concat(${b})`),o.assign(Qo.default.errors,(0,Lt._)`${Qo.default.vErrors}.length`)}function f(m){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=ul.mergeEvaluated.props(o,$.props,s.props));else{let R=o.var("props",(0,Lt._)`${m}.evaluated.props`);s.props=ul.mergeEvaluated.props(o,R,s.props,Lt.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=ul.mergeEvaluated.items(o,$.items,s.items));else{let R=o.var("items",(0,Lt._)`${m}.evaluated.items`);s.items=ul.mergeEvaluated.items(o,R,s.items,Lt.Name)}}}no.callRef=dl;no.default=NM});var M$=B(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var LM=N$(),jM=D$(),zM=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",LM.default,jM.default];If.default=zM});var U$=B(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var pl=me(),gn=pl.operators,hl={maximum:{okStr:"<=",ok:gn.LTE,fail:gn.GT},minimum:{okStr:">=",ok:gn.GTE,fail:gn.LT},exclusiveMaximum:{okStr:"<",ok:gn.LT,fail:gn.GTE},exclusiveMinimum:{okStr:">",ok:gn.GT,fail:gn.LTE}},DM={message:({keyword:t,schemaCode:e})=>(0,pl.str)`must be ${hl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pl._)`{comparison: ${hl[t].okStr}, limit: ${e}}`},MM={keyword:Object.keys(hl),type:"number",schemaType:"number",$data:!0,error:DM,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,pl._)`${r} ${hl[e].fail} ${n} || isNaN(${r})`)}};Of.default=MM});var q$=B(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var Ti=me(),UM={message:({schemaCode:t})=>(0,Ti.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ti._)`{multipleOf: ${t}}`},qM={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:UM,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ti._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ti._)`${i} !== parseInt(${i})`;t.fail$data((0,Ti._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Nf.default=qM});var B$=B(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});function F$(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}Lf.default=F$;F$.code='require("ajv/dist/runtime/ucs2length").default'});var Z$=B(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var oo=me(),FM=$e(),BM=B$(),ZM={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,oo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,oo._)`{limit: ${t}}`},VM={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ZM,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?oo.operators.GT:oo.operators.LT,i=o.opts.unicode===!1?(0,oo._)`${r}.length`:(0,oo._)`${(0,FM.useFunc)(t.gen,BM.default)}(${r})`;t.fail$data((0,oo._)`${i} ${s} ${n}`)}};jf.default=VM});var V$=B(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var HM=Xt(),KM=$e(),es=me(),WM={message:({schemaCode:t})=>(0,es.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,es._)`{pattern: ${t}}`},GM={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:WM,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,es._)`new RegExp`:(0,KM.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,es._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,es._)`!${u}`)}else{let c=(0,HM.usePattern)(t,o);t.fail$data((0,es._)`!${c}.test(${r})`)}}};zf.default=GM});var H$=B(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var Ri=me(),JM={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ri.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ri._)`{limit: ${t}}`},YM={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:JM,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Ri.operators.GT:Ri.operators.LT;t.fail$data((0,Ri._)`Object.keys(${r}).length ${o} ${n}`)}};Df.default=YM});var K$=B(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Ei=Xt(),Pi=me(),XM=$e(),QM={message:({params:{missingProperty:t}})=>(0,Pi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Pi._)`{missingProperty: ${t}}`},eU={keyword:"required",type:"object",schemaType:"array",$data:!0,error:QM,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 f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let b of r)if(f?.[b]===void 0&&!m.has(b)){let $=i.schemaEnv.baseId+i.errSchemaPath,R=`required property "${b}" is not defined at "${$}" (strictRequired)`;(0,XM.checkStrictMode)(i,R,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(Pi.nil,p);else for(let f of r)(0,Ei.checkReportMissingProp)(t,f)}function u(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>w(f,m)),t.ok(m)}else e.if((0,Ei.checkMissingProp)(t,r,f)),(0,Ei.reportMissingProp)(t,f),e.else()}function p(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ei.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function w(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Ei.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Pi.not)(m),()=>{t.error(),e.break()})},Pi.nil)}}};Mf.default=eU});var W$=B(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var Ai=me(),tU={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ai.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ai._)`{limit: ${t}}`},rU={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:tU,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ai.operators.GT:Ai.operators.LT;t.fail$data((0,Ai._)`${r}.length ${o} ${n}`)}};Uf.default=rU});var ml=B(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var G$=of();G$.code='require("ajv/dist/runtime/equal").default';qf.default=G$});var J$=B(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var Ff=fi(),ht=me(),nU=$e(),oU=ml(),sU={message:({params:{i:t,j:e}})=>(0,ht.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ht._)`{i: ${t}, j: ${e}}`},iU={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:sU,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,Ff.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,ht._)`${i} === false`),t.ok(c);function u(){let m=e.let("i",(0,ht._)`${r}.length`),b=e.let("j");t.setParams({i:m,j:b}),e.assign(c,!0),e.if((0,ht._)`${m} > 1`,()=>(p()?w:f)(m,b))}function p(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function w(m,b){let $=e.name("item"),R=(0,Ff.checkDataTypes)(l,$,a.opts.strictNumbers,Ff.DataType.Wrong),A=e.const("indices",(0,ht._)`{}`);e.for((0,ht._)`;${m}--;`,()=>{e.let($,(0,ht._)`${r}[${m}]`),e.if(R,(0,ht._)`continue`),l.length>1&&e.if((0,ht._)`typeof ${$} == "string"`,(0,ht._)`${$} += "_"`),e.if((0,ht._)`typeof ${A}[${$}] == "number"`,()=>{e.assign(b,(0,ht._)`${A}[${$}]`),t.error(),e.assign(c,!1).break()}).code((0,ht._)`${A}[${$}] = ${m}`)})}function f(m,b){let $=(0,nU.useFunc)(e,oU.default),R=e.name("outer");e.label(R).for((0,ht._)`;${m}--;`,()=>e.for((0,ht._)`${b} = ${m}; ${b}--;`,()=>e.if((0,ht._)`${$}(${r}[${m}], ${r}[${b}])`,()=>{t.error(),e.assign(c,!1).break(R)})))}}};Bf.default=iU});var Y$=B(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var Zf=me(),aU=$e(),cU=ml(),lU={message:"must be equal to constant",params:({schemaCode:t})=>(0,Zf._)`{allowedValue: ${t}}`},uU={keyword:"const",$data:!0,error:lU,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Zf._)`!${(0,aU.useFunc)(e,cU.default)}(${r}, ${o})`):t.fail((0,Zf._)`${s} !== ${r}`)}};Vf.default=uU});var X$=B(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var Ci=me(),dU=$e(),pU=ml(),hU={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ci._)`{allowedValues: ${t}}`},mU={keyword:"enum",schemaType:"array",$data:!0,error:hU,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,dU.useFunc)(e,pU.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 f=e.const("vSchema",s);u=(0,Ci.or)(...o.map((m,b)=>w(f,b)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,f=>e.if((0,Ci._)`${l()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function w(f,m){let b=o[m];return typeof b=="object"&&b!==null?(0,Ci._)`${l()}(${r}, ${f}[${m}])`:(0,Ci._)`${r} === ${b}`}}};Hf.default=mU});var Q$=B(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var fU=U$(),gU=q$(),yU=Z$(),bU=V$(),wU=H$(),_U=K$(),vU=W$(),xU=J$(),kU=Y$(),SU=X$(),$U=[fU.default,gU.default,yU.default,bU.default,wU.default,_U.default,vU.default,xU.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},kU.default,SU.default];Kf.default=$U});var Gf=B(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.validateAdditionalItems=void 0;var so=me(),Wf=$e(),TU={message:({params:{len:t}})=>(0,so.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,so._)`{limit: ${t}}`},RU={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:TU,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Wf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}eT(t,n)}};function eT(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,so._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,so._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Wf.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,so._)`${a} <= ${e.length}`);r.if((0,so.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Wf.Type.Num},l),i.allErrors||r.if((0,so.not)(l),()=>r.break())})}}Ii.validateAdditionalItems=eT;Ii.default=RU});var Jf=B(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.validateTuple=void 0;var tT=me(),fl=$e(),EU=Xt(),PU={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return rT(t,"additionalItems",e);r.items=!0,!(0,fl.alwaysValidSchema)(r,e)&&t.ok((0,EU.validateArray)(t))}};function rT(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=fl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,tT._)`${s}.length`);r.forEach((p,w)=>{(0,fl.alwaysValidSchema)(a,p)||(n.if((0,tT._)`${l} > ${w}`,()=>t.subschema({keyword:i,schemaProp:w,dataProp:w},c)),t.ok(c))});function u(p){let{opts:w,errSchemaPath:f}=a,m=r.length,b=m===p.minItems&&(m===p.maxItems||p[e]===!1);if(w.strictTuples&&!b){let $=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,fl.checkStrictMode)(a,$,w.strictTuples)}}}Oi.validateTuple=rT;Oi.default=PU});var nT=B(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var AU=Jf(),CU={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,AU.validateTuple)(t,"items")};Yf.default=CU});var sT=B(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var oT=me(),IU=$e(),OU=Xt(),NU=Gf(),LU={message:({params:{len:t}})=>(0,oT.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,oT._)`{limit: ${t}}`},jU={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:LU,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,IU.alwaysValidSchema)(n,e)&&(o?(0,NU.validateAdditionalItems)(t,o):t.ok((0,OU.validateArray)(t)))}};Xf.default=jU});var iT=B(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var er=me(),gl=$e(),zU={message:({params:{min:t,max:e}})=>e===void 0?(0,er.str)`must contain at least ${t} valid item(s)`:(0,er.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,er._)`{minContains: ${t}}`:(0,er._)`{minContains: ${t}, maxContains: ${e}}`},DU={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:zU,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,er._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,gl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,gl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,gl.alwaysValidSchema)(s,r)){let b=(0,er._)`${u} >= ${i}`;a!==void 0&&(b=(0,er._)`${b} && ${u} <= ${a}`),t.pass(b);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?f(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,er._)`${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);f(b,()=>e.if(b,()=>m($)))}function f(b,$){e.forRange("i",0,u,R=>{t.subschema({keyword:"contains",dataProp:R,dataPropType:gl.Type.Num,compositeRule:!0},b),$()})}function m(b){e.code((0,er._)`${b}++`),a===void 0?e.if((0,er._)`${b} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,er._)`${b} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,er._)`${b} >= ${i}`,()=>e.assign(p,!0)))}}};Qf.default=DU});var lT=B(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.validateSchemaDeps=Tr.validatePropertyDeps=Tr.error=void 0;var eg=me(),MU=$e(),Ni=Xt();Tr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,eg.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,eg._)`{property: ${t},
2518
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,pe._)`[${o}]`)}}}function Xz({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,pe._)`${e} !== undefined`,()=>t.assign((0,pe._)`${e}[${r}]`,n))}function Qm(t,e,r,n=Ko.Correct){let o=n===Ko.Correct?pe.operators.EQ:pe.operators.NEQ,s;switch(t){case"null":return(0,pe._)`${e} ${o} null`;case"array":s=(0,pe._)`Array.isArray(${e})`;break;case"object":s=(0,pe._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,pe._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,pe._)`typeof ${e} ${o} ${t}`}return n===Ko.Correct?s:(0,pe.not)(s);function i(a=pe.nil){return(0,pe.and)((0,pe._)`typeof ${e} == "number"`,a,r?(0,pe._)`isFinite(${e})`:pe.nil)}}yt.checkDataType=Qm;function ef(t,e,r,n){if(t.length===1)return Qm(t[0],e,r,n);let o,s=(0,gS.toHash)(t);if(s.array&&s.object){let i=(0,pe._)`typeof ${e} != "object"`;o=s.null?i:(0,pe._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=pe.nil;s.number&&delete s.integer;for(let i in s)o=(0,pe.and)(o,Qm(i,e,r,n));return o}yt.checkDataTypes=ef;var Qz={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,pe._)`{type: ${t}}`:(0,pe._)`{type: ${e}}`};function tf(t){let e=eD(t);(0,Kz.reportError)(e,Qz)}yt.reportTypeError=tf;function eD(t){let{gen:e,data:r,schema:n}=t,o=(0,gS.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var _S=B(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.assignDefaults=void 0;var Wo=me(),tD=$e();function rD(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)wS(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>wS(t,s,o.default))}Gc.assignDefaults=rD;function wS(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Wo._)`${s}${(0,Wo.getProperty)(e)}`;if(o){(0,tD.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Wo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Wo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Wo._)`${a} = ${(0,Wo.stringify)(r)}`)}});var Xt=B(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.validateUnion=Ce.validateArray=Ce.usePattern=Ce.callValidateCode=Ce.schemaProperties=Ce.allSchemaProperties=Ce.noPropertyInData=Ce.propertyInData=Ce.isOwnProperty=Ce.hasPropFunc=Ce.reportMissingProp=Ce.checkMissingProp=Ce.checkReportMissingProp=void 0;var Ue=me(),rf=$e(),pn=Fr(),nD=$e();function oD(t,e){let{gen:r,data:n,it:o}=t;r.if(of(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ue._)`${e}`},!0),t.error()})}Ce.checkReportMissingProp=oD;function sD({gen:t,data:e,it:{opts:r}},n,o){return(0,Ue.or)(...n.map(s=>(0,Ue.and)(of(t,e,s,r.ownProperties),(0,Ue._)`${o} = ${s}`)))}Ce.checkMissingProp=sD;function iD(t,e){t.setParams({missingProperty:e},!0),t.error()}Ce.reportMissingProp=iD;function vS(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ue._)`Object.prototype.hasOwnProperty`})}Ce.hasPropFunc=vS;function nf(t,e,r){return(0,Ue._)`${vS(t)}.call(${e}, ${r})`}Ce.isOwnProperty=nf;function aD(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} !== undefined`;return n?(0,Ue._)`${o} && ${nf(t,e,r)}`:o}Ce.propertyInData=aD;function of(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} === undefined`;return n?(0,Ue.or)(o,(0,Ue.not)(nf(t,e,r))):o}Ce.noPropertyInData=of;function kS(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ce.allSchemaProperties=kS;function cD(t,e){return kS(e).filter(r=>!(0,rf.alwaysValidSchema)(t,e[r]))}Ce.schemaProperties=cD;function lD({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Ue._)`${t}, ${e}, ${n}${o}`:e,p=[[pn.default.instancePath,(0,Ue.strConcat)(pn.default.instancePath,s)],[pn.default.parentData,i.parentData],[pn.default.parentDataProperty,i.parentDataProperty],[pn.default.rootData,pn.default.rootData]];i.opts.dynamicRef&&p.push([pn.default.dynamicAnchors,pn.default.dynamicAnchors]);let w=(0,Ue._)`${u}, ${r.object(...p)}`;return c!==Ue.nil?(0,Ue._)`${a}.call(${c}, ${w})`:(0,Ue._)`${a}(${w})`}Ce.callValidateCode=lD;var uD=(0,Ue._)`new RegExp`;function dD({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,Ue._)`${o.code==="new RegExp"?uD:(0,nD.useFunc)(t,o)}(${r}, ${n})`})}Ce.usePattern=dD;function pD(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,Ue._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:rf.Type.Num},s),e.if((0,Ue.not)(s),a)})}}Ce.validateArray=pD;function hD(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,rf.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,Ue._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Ue.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ce.validateUnion=hD});var $S=B(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.validateKeywordUsage=Sr.validSchemaType=Sr.funcKeywordCode=Sr.macroKeywordCode=void 0;var xt=me(),Qn=Fr(),mD=Xt(),fD=mi();function gD(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=SS(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:xt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Sr.macroKeywordCode=gD;function yD(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;wD(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=SS(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&&xS(t),$(()=>t.error());else{let R=e.async?f():m();e.modifying&&xS(t),$(()=>bD(t,R))}}function f(){let R=n.let("ruleErrs",null);return n.try(()=>b((0,xt._)`await `),A=>n.assign(p,!1).if((0,xt._)`${A} instanceof ${c.ValidationError}`,()=>n.assign(R,(0,xt._)`${A}.errors`),()=>n.throw(A))),R}function m(){let R=(0,xt._)`${u}.errors`;return n.assign(R,null),b(xt.nil),R}function b(R=e.async?(0,xt._)`await `:xt.nil){let A=c.opts.passContext?Qn.default.this:Qn.default.self,O=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,xt._)`${R}${(0,mD.callValidateCode)(t,u,A,O)}`,e.modifying)}function $(R){var A;n.if((0,xt.not)((A=e.valid)!==null&&A!==void 0?A:p),R)}}Sr.funcKeywordCode=yD;function xS(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,xt._)`${n.parentData}[${n.parentDataProperty}]`))}function bD(t,e){let{gen:r}=t;r.if((0,xt._)`Array.isArray(${e})`,()=>{r.assign(Qn.default.vErrors,(0,xt._)`${Qn.default.vErrors} === null ? ${e} : ${Qn.default.vErrors}.concat(${e})`).assign(Qn.default.errors,(0,xt._)`${Qn.default.vErrors}.length`),(0,fD.extendErrors)(t)},()=>t.error())}function wD({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function SS(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,xt.stringify)(r)})}function _D(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")}Sr.validSchemaType=_D;function vD({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)}}Sr.validateKeywordUsage=vD});var RS=B(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.extendSubschemaMode=hn.extendSubschemaData=hn.getSubschema=void 0;var $r=me(),TS=$e();function kD(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,$r._)`${t.schemaPath}${(0,$r.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,$r._)`${t.schemaPath}${(0,$r.getProperty)(e)}${(0,$r.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,TS.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')}hn.getSubschema=kD;function xD(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,$r._)`${e.data}${(0,$r.getProperty)(r)}`,!0);c(w),t.errorPath=(0,$r.str)`${l}${(0,TS.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,$r._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof $r.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]}}hn.extendSubschemaData=xD;function SD(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}hn.extendSubschemaMode=SD});var sf=B((PG,ES)=>{"use strict";ES.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 AS=B((AG,PS)=>{"use strict";var mn=PS.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(){};Jc(e,n,o,t,"",t)};mn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};mn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};mn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};mn.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 Jc(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 mn.arrayKeywords)for(var w=0;w<p.length;w++)Jc(t,e,r,p[w],o+"/"+u+"/"+w,s,o,u,n,w)}else if(u in mn.propsKeywords){if(p&&typeof p=="object")for(var f in p)Jc(t,e,r,p[f],o+"/"+u+"/"+$D(f),s,o,u,n,f)}else(u in mn.keywords||t.allKeys&&!(u in mn.skipKeywords))&&Jc(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function $D(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gi=B(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getSchemaRefs=Ot.resolveUrl=Ot.normalizeId=Ot._getFullPath=Ot.getFullPath=Ot.inlineRef=void 0;var TD=$e(),RD=sf(),ED=AS(),PD=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function AD(t,e=!0){return typeof t=="boolean"?!0:e===!0?!af(t):e?CS(t)<=e:!1}Ot.inlineRef=AD;var CD=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function af(t){for(let e in t){if(CD.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(af)||typeof r=="object"&&af(r))return!0}return!1}function CS(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!PD.has(r)&&(typeof t[r]=="object"&&(0,TD.eachItem)(t[r],n=>e+=CS(n)),e===1/0))return 1/0}return e}function IS(t,e="",r){r!==!1&&(e=Go(e));let n=t.parse(e);return OS(t,n)}Ot.getFullPath=IS;function OS(t,e){return t.serialize(e).split("#")[0]+"#"}Ot._getFullPath=OS;var ID=/#\/?$/;function Go(t){return t?t.replace(ID,""):""}Ot.normalizeId=Go;function OD(t,e,r){return r=Go(r),t.resolve(e,r)}Ot.resolveUrl=OD;var ND=/^[a-z_][-a-z0-9._]*$/i;function LD(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Go(t[r]||e),s={"":o},i=IS(n,o,!1),a={},c=new Set;return ED(t,{allKeys:!0},(p,w,f,m)=>{if(m===void 0)return;let b=i+w,$=s[m];typeof p[r]=="string"&&($=R.call(this,p[r])),A.call(this,p.$anchor),A.call(this,p.$dynamicAnchor),s[w]=$;function R(O){let q=this.opts.uriResolver.resolve;if(O=Go($?q($,O):O),c.has(O))throw u(O);c.add(O);let J=this.refs[O];return typeof J=="string"&&(J=this.refs[J]),typeof J=="object"?l(p,J.schema,O):O!==Go(b)&&(O[0]==="#"?(l(p,a[O],O),a[O]=p):this.refs[O]=b),O}function A(O){if(typeof O=="string"){if(!ND.test(O))throw new Error(`invalid anchor "${O}"`);R.call(this,`#${O}`)}}}),a;function l(p,w,f){if(w!==void 0&&!RD(p,w))throw u(f)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Ot.getSchemaRefs=LD});var wi=B(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.getData=fn.KeywordCxt=fn.validateFunctionCode=void 0;var DS=hS(),NS=fi(),lf=Xm(),Yc=fi(),jD=_S(),bi=$S(),cf=RS(),te=me(),ue=Fr(),zD=gi(),Br=$e(),yi=mi();function DD(t){if(qS(t)&&(FS(t),US(t))){qD(t);return}MS(t,()=>(0,DS.topBoolOrEmptySchema)(t))}fn.validateFunctionCode=DD;function MS({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,te._)`${ue.default.data}, ${ue.default.valCxt}`,n.$async,()=>{t.code((0,te._)`"use strict"; ${LS(r,o)}`),UD(t,o),t.code(s)}):t.func(e,(0,te._)`${ue.default.data}, ${MD(o)}`,n.$async,()=>t.code(LS(r,o)).code(s))}function MD(t){return(0,te._)`{${ue.default.instancePath}="", ${ue.default.parentData}, ${ue.default.parentDataProperty}, ${ue.default.rootData}=${ue.default.data}${t.dynamicRef?(0,te._)`, ${ue.default.dynamicAnchors}={}`:te.nil}}={}`}function UD(t,e){t.if(ue.default.valCxt,()=>{t.var(ue.default.instancePath,(0,te._)`${ue.default.valCxt}.${ue.default.instancePath}`),t.var(ue.default.parentData,(0,te._)`${ue.default.valCxt}.${ue.default.parentData}`),t.var(ue.default.parentDataProperty,(0,te._)`${ue.default.valCxt}.${ue.default.parentDataProperty}`),t.var(ue.default.rootData,(0,te._)`${ue.default.valCxt}.${ue.default.rootData}`),e.dynamicRef&&t.var(ue.default.dynamicAnchors,(0,te._)`${ue.default.valCxt}.${ue.default.dynamicAnchors}`)},()=>{t.var(ue.default.instancePath,(0,te._)`""`),t.var(ue.default.parentData,(0,te._)`undefined`),t.var(ue.default.parentDataProperty,(0,te._)`undefined`),t.var(ue.default.rootData,ue.default.data),e.dynamicRef&&t.var(ue.default.dynamicAnchors,(0,te._)`{}`)})}function qD(t){let{schema:e,opts:r,gen:n}=t;MS(t,()=>{r.$comment&&e.$comment&&ZS(t),HD(t),n.let(ue.default.vErrors,null),n.let(ue.default.errors,0),r.unevaluated&&FD(t),BS(t),GD(t)})}function FD(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,te._)`${r}.evaluated`),e.if((0,te._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,te._)`${t.evaluated}.props`,(0,te._)`undefined`)),e.if((0,te._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,te._)`${t.evaluated}.items`,(0,te._)`undefined`))}function LS(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,te._)`/*# sourceURL=${r} */`:te.nil}function BD(t,e){if(qS(t)&&(FS(t),US(t))){ZD(t,e);return}(0,DS.boolOrEmptySchema)(t,e)}function US({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 qS(t){return typeof t.schema!="boolean"}function ZD(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&ZS(t),KD(t),WD(t);let s=n.const("_errs",ue.default.errors);BS(t,s),n.var(e,(0,te._)`${s} === ${ue.default.errors}`)}function FS(t){(0,Br.checkUnknownRules)(t),VD(t)}function BS(t,e){if(t.opts.jtd)return jS(t,[],!1,e);let r=(0,NS.getSchemaTypes)(t.schema),n=(0,NS.coerceAndCheckDataType)(t,r);jS(t,r,!n,e)}function VD(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Br.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function HD(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Br.checkStrictMode)(t,"default is ignored in the schema root")}function KD(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,zD.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function WD(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function ZS({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,te._)`${ue.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,te.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,te._)`${ue.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function GD(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,te._)`${ue.default.errors} === 0`,()=>e.return(ue.default.data),()=>e.throw((0,te._)`new ${o}(${ue.default.vErrors})`)):(e.assign((0,te._)`${n}.errors`,ue.default.vErrors),s.unevaluated&&JD(t),e.return((0,te._)`${ue.default.errors} === 0`))}function JD({gen:t,evaluated:e,props:r,items:n}){r instanceof te.Name&&t.assign((0,te._)`${e}.props`,r),n instanceof te.Name&&t.assign((0,te._)`${e}.items`,n)}function jS(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,Br.schemaHasRulesButRef)(s,u))){o.block(()=>HS(t,"$ref",u.all.$ref.definition));return}c.jtd||YD(t,e),o.block(()=>{for(let w of u.rules)p(w);p(u.post)});function p(w){(0,lf.shouldUseGroup)(s,w)&&(w.type?(o.if((0,Yc.checkDataType)(w.type,i,c.strictNumbers)),zS(t,w),e.length===1&&e[0]===w.type&&r&&(o.else(),(0,Yc.reportTypeError)(t)),o.endIf()):zS(t,w),a||o.if((0,te._)`${ue.default.errors} === ${n||0}`))}}function zS(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,jD.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,lf.shouldUseRule)(n,s)&&HS(t,s.keyword,s.definition,e.type)})}function YD(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(XD(t,e),t.opts.allowUnionTypes||QD(t,e),e1(t,t.dataTypes))}function XD(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{VS(t.dataTypes,r)||uf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),r1(t,e)}}function QD(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&uf(t,"use allowUnionTypes to allow union type keyword")}function e1(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,lf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>t1(e,i))&&uf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function t1(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function VS(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function r1(t,e){let r=[];for(let n of t.dataTypes)VS(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function uf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Br.checkStrictMode)(t,e,t.opts.strictTypes)}var Xc=class{constructor(e,r,n){if((0,bi.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,Br.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",KS(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,bi.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",ue.default.errors))}result(e,r,n){this.failResult((0,te.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,te.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,te._)`${r} !== undefined && (${(0,te.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?yi.reportExtraError:yi.reportError)(this,this.def.error,r)}$dataError(){(0,yi.reportError)(this,this.def.$dataError||yi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,yi.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=te.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=te.nil,r=te.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,te.or)((0,te._)`${o} === undefined`,r)),e!==te.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==te.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,te.or)(i(),a());function i(){if(n.length){if(!(r instanceof te.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,te._)`${(0,Yc.checkDataTypes)(c,r,s.opts.strictNumbers,Yc.DataType.Wrong)}`}return te.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,te._)`!${c}(${r})`}return te.nil}}subschema(e,r){let n=(0,cf.getSubschema)(this.it,e);(0,cf.extendSubschemaData)(n,this.it,e),(0,cf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return BD(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Br.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Br.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,te.Name)),!0}};fn.KeywordCxt=Xc;function HS(t,e,r,n){let o=new Xc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,bi.funcKeywordCode)(o,r):"macro"in r?(0,bi.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,bi.funcKeywordCode)(o,r)}var n1=/^\/(?:[^~]|~0|~1)*$/,o1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function KS(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ue.default.rootData;if(t[0]==="/"){if(!n1.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ue.default.rootData}else{let l=o1.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,te._)`${s}${(0,te.getProperty)((0,Br.unescapeJsonPointer)(l))}`,i=(0,te._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}fn.getData=KS});var Qc=B(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var df=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};pf.default=df});var _i=B(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var hf=gi(),mf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,hf.resolveUrl)(e,r,n),this.missingSchema=(0,hf.normalizeId)((0,hf.getFullPath)(e,this.missingRef))}};ff.default=mf});var tl=B(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.resolveSchema=Qt.getCompilingSchema=Qt.resolveRef=Qt.compileSchema=Qt.SchemaEnv=void 0;var dr=me(),s1=Qc(),eo=Fr(),pr=gi(),WS=$e(),i1=wi(),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,pr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Qt.SchemaEnv=Jo;function yf(t){let e=GS.call(this,t);if(e)return e;let r=(0,pr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new dr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:s1.default,code:(0,dr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:eo.default.data,parentData:eo.default.parentData,parentDataProperty:eo.default.parentDataProperty,dataNames:[eo.default.data],dataPathArr:[dr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,dr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:dr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,dr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,i1.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(eo.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let f=new Function(`${eo.default.self}`,`${eo.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:b}=l;f.evaluated={props:m instanceof dr.Name?void 0:m,items:b instanceof dr.Name?void 0:b,dynamicProps:m instanceof dr.Name,dynamicItems:b instanceof dr.Name},f.source&&(f.source.evaluated=(0,dr.stringify)(f.evaluated))}return t.validate=f,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)}}Qt.compileSchema=yf;function a1(t,e,r){var n;r=(0,pr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=u1.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]=c1.call(this,s)}Qt.resolveRef=a1;function c1(t){return(0,pr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:yf.call(this,t)}function GS(t){for(let e of this._compilations)if(l1(e,t))return e}Qt.getCompilingSchema=GS;function l1(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function u1(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||el.call(this,t,e)}function el(t,e){let r=this.opts.uriResolver.parse(e),n=(0,pr._getFullPath)(this.opts.uriResolver,r),o=(0,pr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return gf.call(this,r,t);let s=(0,pr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=el.call(this,t,i);return typeof a?.schema!="object"?void 0:gf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||yf.call(this,i),s===(0,pr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,pr.resolveUrl)(this.opts.uriResolver,o,l)),new Jo({schema:a,schemaId:c,root:t,baseId:o})}return gf.call(this,r,i)}}Qt.resolveSchema=el;var d1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function gf(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,WS.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!d1.has(a)&&l&&(e=(0,pr.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,WS.schemaHasRulesButRef)(r,this.RULES)){let a=(0,pr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=el.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 JS=B((jG,p1)=>{p1.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 xf=B((zG,o$)=>{"use strict";var h1=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),wf=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),m1=RegExp.prototype.test.bind(/^\d*$/u),to=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),_f=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),XS=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),vf=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),f1=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Nt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Nt[e]="%"+t[e>>4]+t[e&15]}function bt(t){return t<2048?Nt[192|t>>6]+Nt[128|t&63]:t<65536?Nt[224|t>>12]+Nt[128|t>>6&63]+Nt[128|t&63]:Nt[240|t>>18]+Nt[128|t>>12&63]+Nt[128|t>>6&63]+Nt[128|t&63]}function g1(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 y1=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),b1=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),w1=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),_1=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function v1(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!w1(t[e])){if(t[e]==="%"&&e+2<t.length&&to(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function YS(t){let e=-1,r=0,n=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(n===-1&&(n=a),o++,o>r&&(r=o,e=n)):(n=-1,o=0);if(r<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+r).join(":");return s+"::"+i}function k1(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let r=e===-1?t.split(":"):t.slice(0,e).split(":"),n=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let o=r.concat(n),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&n.length===0||!wf(c))return;s+=2;continue}if(!y1(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:YS(o);if(s>=8)return;let i=o.slice(0,r.length);for(let a=s;a<8;a++)i.push("0");for(let a=r.length;a<o.length;a++)i.push(o[a]);return YS(i)}function bf(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let n=e?t.slice(1,-1):t;if(e&&b1(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x1(n,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=n.indexOf("%");if(s!==-1){let a=n.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=n.slice(s+a),!v1(o))return{host:t,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=k1(n);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function x1(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function QS(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("")}function S1(t){if(t===""||t[0]==="/")return QS(t);let e=t.split("/"),r=e.length-1,n=[],o=!1;for(let s=0;s<=r;s++){let i=e[s];i==="."||i===".."?(i===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),o=s===r):n.push(i)}return o&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var $1={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},T1=/[@/?#:]/g,R1=/[@/?#]/g;function e$(t,e){let r=e?R1:T1;return r.lastIndex=0,t.replace(r,n=>$1[n])}function t$(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(to(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&_f(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function E1(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(to(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&_f(i)?e+=i:e+="%"+s,r+=2;continue}}if(XS(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=n$(o)?n:Nt[o];else if(o<55296||o>57343)e+=bt(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=bt(65536+(o-55296<<10)+(s-56320)),r++):e+=bt(65533)}else e+=bt(65533)}}return e}function P1(t,e=!1){let r="",n=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(to(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),XS(s)&&(s!==":"||!n))r+=s;else{let i=t.charCodeAt(o);if(i<128)r+=Nt[i];else if(i<55296||i>57343)r+=bt(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(r+=bt(65536+(i-55296<<10)+(a-56320)),o++):r+=bt(65533)}else r+=bt(65533)}}return r}function kf(t,e){let r="";for(let n=0;n<t.length;n++){let o=t[n];if(o==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(to(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(e(o))r+=o;else{let s=t.charCodeAt(n);if(s<128)r+=Nt[s];else if(s<55296||s>57343)r+=bt(s);else if(s<=56319&&n+1<t.length){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(r+=bt(65536+(s-55296<<10)+(i-56320)),n++):r+=bt(65533)}else r+=bt(65533)}}return r}function r$(t){return kf(t,f1)}function A1(t){return kf(t,vf)}function C1(t){return kf(t,vf)}function n$(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function I1(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];if(n==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(to(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));_f(i)?e+=i:e+="%"+s,r+=2;continue}}if(vf(n))e+=n;else{let o=t.charCodeAt(r);if(o<128)e+=n$(o)?n:Nt[o];else if(o<55296||o>57343)e+=bt(o);else if(o<=56319&&r+1<t.length){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=bt(65536+(o-55296<<10)+(s-56320)),r++):e+=bt(65533)}else e+=bt(65533)}}return e}function O1(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(to(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function N1(t){let e=[];if(t.userinfo!==void 0&&(e.push(r$(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!wf(r)){let n=bf(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=t$(r,!0),n=bf(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=e$(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!m1(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}o$.exports={nonSimpleDomain:_1,recomposeAuthority:N1,reescapeHostDelimiters:e$,normalizePercentEncoding:t$,normalizePathEncoding:E1,serializePathEncoding:P1,normalizeQueryFragmentEncoding:I1,encodeUserinfo:r$,encodeQuery:A1,encodeFragment:C1,escapePreservingEscapes:O1,removeDotSegments:QS,removeDotSegmentsRelative:S1,isIPv4:wf,isUUID:h1,normalizeIPv6:bf,stringArrayToHexStripped:g1}});var l$=B((DG,c$)=>{"use strict";var{isUUID:L1}=xf(),j1=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,z1=["http","https","ws","wss","urn","urn:uuid"];function D1(t){return z1.indexOf(t)!==-1}function Sf(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 s$(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function i$(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 M1(t){return t.secure=Sf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function U1(t){if((t.port===(Sf(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=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function q1(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(j1);if(r&&r[0]===t.path){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=$f(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function F1(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=$f(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 B1(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!L1(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Z1(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var a$={scheme:"http",domainHost:!0,parse:s$,serialize:i$},V1={scheme:"https",domainHost:a$.domainHost,parse:s$,serialize:i$},rl={scheme:"ws",domainHost:!0,parse:M1,serialize:U1},H1={scheme:"wss",domainHost:rl.domainHost,parse:rl.parse,serialize:rl.serialize},K1={scheme:"urn",parse:q1,serialize:F1,skipNormalize:!0},W1={scheme:"urn:uuid",parse:B1,serialize:Z1,skipNormalize:!0},nl={http:a$,https:V1,ws:rl,wss:H1,urn:K1,"urn:uuid":W1};Object.setPrototypeOf(nl,null);function $f(t){return t&&(nl[t]||nl[t.toLowerCase()])||void 0}c$.exports={wsIsSecure:Sf,SCHEMES:nl,isValidSchemeName:D1,getSchemeHandler:$f}});var S$=B((MG,cl)=>{"use strict";var{normalizeIPv6:m$,removeDotSegments:ki,removeDotSegmentsRelative:f$,recomposeAuthority:G1,normalizePercentEncoding:Tf,normalizePathEncoding:J1,serializePathEncoding:u$,normalizeQueryFragmentEncoding:d$,encodeQuery:Y1,encodeFragment:X1,reescapeHostDelimiters:Q1,isIPv4:g$,nonSimpleDomain:eM}=xf(),{SCHEMES:y$,getSchemeHandler:Rf}=l$(),b$=/^[A-Za-z][A-Za-z0-9+.-]*$/u,w$="URI scheme is malformed.",ol="URI host is malformed.",tM=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function p$(t){let e=String(t);if(!b$.test(e))throw new TypeError(w$);return e}function rM(t,e){return typeof t=="string"?t=dM(t,e):typeof t=="object"&&(t=il(ro(t,e),e)),t}function nM(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:l}=sl(t,n),{parsed:u,malformedAuthorityOrPort:p,malformedPercentEncoding:w,malformedSchemeSpecific:f,malformedHost:m,malformedScheme:b}=sl(e,n);if(s||p||i||w||a||f||c||m||l||b)throw new Error(o.error||u.error||"URI is malformed.");let $=_$(o,u,n,!0),R=Rf(r&&r.scheme||$.scheme),A=$.host,O=A!==void 0&&A!==""&&(g$(A)||m$(A).isIPV6);if(k$($,r||{},R,O))throw new Error(ol);v$($,r||{},R,O);let q=A&&A.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(A);if($.error&&!q)throw new Error($.error);return n.skipEscape=!0,ro($,n)}function _$(t,e,r,n){let o={};if(n||(t=il(ro(t,r),r),e=il(ro(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=ki(e.path||""),o.query=e.query;else{if(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=ki(e.path||""),o.query=e.query;else{if(!e.path)o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query;else{if(e.path[0]==="/")o.path=ki(e.path);else{let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0;s&&!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=t.scheme===void 0&&!s&&o.path[0]!=="/"?f$(o.path):ki(o.path)}o.query=e.query}o.userinfo=t.userinfo,o.host=t.host,o.port=t.port}o.scheme=t.scheme}return o.fragment=e.fragment,o}function oM(t,e,r){let n=h$(t,r),o=h$(e,r);return n!==void 0&&o!==void 0&&n===o}function ro(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=[];r.scheme&&(r.scheme=p$(r.scheme));let s=Rf(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=(r.scheme===void 0||n.reference==="suffix")&&!i,c=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=Tf(r.path):r.path=u$(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=p$(r.scheme),o.push(r.scheme,":"));let l=G1(r);if(l!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(l),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let u=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(u=a&&u[0]!=="/"?f$(u):ki(u)),a&&(u=u$(u,!0)),l===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return r.query!==void 0&&o.push("?",Y1(r.query)),r.fragment!==void 0&&o.push("#",X1(r.fragment)),o.join("")}var sM=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,iM=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,aM=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function cM(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 vi(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function al(t){return t[0]==="["&&t[t.length-1]==="]"}function lM(t){let e=t[4];return vi(t[3])||e!==void 0&&!al(e)&&vi(e)||vi(t[6])||vi(t[7])||vi(t[8])}function v$(t,e,r,n){if(k$(t,e,r,n))return t.error=t.error||ol,!0;if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!al(t.host)&&(e.domainHost||r&&r.domainHost)&&n===!1&&eM(t.host)){let o;try{o=new URL("http://"+t.host)}catch(s){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!uM(o))return t.error=t.error||ol,!0;t.host=o.hostname}return!1}function k$(t,e,r,n){return!!(t.host&&n===!1&&!al(t.host)&&(e.domainHost||r&&r.domainHost)&&tM.test(t.host))}function uM(t){return t.username===""&&t.password===""&&t.port===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&t.hostname!==""}function sl(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,i=!1,a=!1,c=!1,l=!1,u=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let p=t.match(iM);p!==null&&p[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let w=t.match(aM);if(w!==null){let m=w[1],b=m.replace(/[\t\n\r]/g,"");b.length>=2&&(b.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):m.length!==b.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let f=t.match(sM);if(f){n.scheme=f[1],n.userinfo=f[3],n.host=f[4],n.port=parseInt(f[5],10),n.path=f[6]||"",n.query=f[7],n.fragment=f[8],n.scheme!==void 0&&(b$.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||w$,l=!0)),s=lM(f),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=f[5]);let m=cM(n,f);if(m!==void 0&&(n.error=n.error||m,o=!0),n.host)if(g$(n.host)===!1){let R=al(n.host),A=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,O=m$(n.host);u=O.isIPV6||O.isIPVFuture===!0,c=A&&(!R||O.error===!0),n.host=u?O.host:O.host.toLowerCase(),c&&(n.error=n.error||ol,o=!0)}else u=!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 b=Rf(r.scheme||n.scheme);if(c||(a=v$(n,r,b,u)),t.indexOf("%")!==-1&&n.host!==void 0&&!c){let $=u?n.host:Tf(n.host,!0);u||($=Tf($.toLowerCase())),n.host=u||r.scheme!=="null"?Q1($,u):$}(!b||b&&!b.skipNormalize)&&(n.path&&(n.path=J1(n.path)),n.query&&(n.query=d$(n.query)),n.fragment&&(n.fragment=d$(n.fragment))),b&&b.parse&&(b.parse(n,r),b===y$.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:l}}function il(t,e){return sl(t,e).parsed}function dM(t,e){return x$(t,e).normalized}function x$(t,e){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=sl(t,e);return{normalized:n||o||s||i||a?t:ro(r,e),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function h$(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:ro(t,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=x$(r,e);return o||s||i||a||c?void 0:n}var Ef={SCHEMES:y$,normalize:rM,resolve:nM,resolveComponent:_$,equal:oM,serialize:ro,parse:il};cl.exports=Ef;cl.exports.default=Ef;cl.exports.fastUri=Ef});var T$=B(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var $$=S$();$$.code='require("ajv/dist/runtime/uri").default';Pf.default=$$});var N$=B(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.CodeGen=pt.Name=pt.nil=pt.stringify=pt.str=pt._=pt.KeywordCxt=void 0;var pM=wi();Object.defineProperty(pt,"KeywordCxt",{enumerable:!0,get:function(){return pM.KeywordCxt}});var Yo=me();Object.defineProperty(pt,"_",{enumerable:!0,get:function(){return Yo._}});Object.defineProperty(pt,"str",{enumerable:!0,get:function(){return Yo.str}});Object.defineProperty(pt,"stringify",{enumerable:!0,get:function(){return Yo.stringify}});Object.defineProperty(pt,"nil",{enumerable:!0,get:function(){return Yo.nil}});Object.defineProperty(pt,"Name",{enumerable:!0,get:function(){return Yo.Name}});Object.defineProperty(pt,"CodeGen",{enumerable:!0,get:function(){return Yo.CodeGen}});var hM=Qc(),C$=_i(),mM=Ym(),xi=tl(),fM=me(),Si=gi(),ll=fi(),Cf=$e(),R$=JS(),gM=T$(),I$=(t,e)=>new RegExp(t,e);I$.code="new RegExp";var yM=["removeAdditional","useDefaults","coerceTypes"],bM=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),wM={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."},_M={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},E$=200;function vM(t){var e,r,n,o,s,i,a,c,l,u,p,w,f,m,b,$,R,A,O,q,J,De,Qe,zt,Vr;let fr=t.strict,Hr=(e=t.code)===null||e===void 0?void 0:e.optimize,Di=Hr===!0||Hr===void 0?1:Hr||0,wn=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:I$,Pr=(o=t.uriResolver)!==null&&o!==void 0?o:gM.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:fr)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:fr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:fr)!==null&&u!==void 0?u:"log",strictTuples:(w=(p=t.strictTuples)!==null&&p!==void 0?p:fr)!==null&&w!==void 0?w:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:fr)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Di,regExp:wn}:{optimize:Di,regExp:wn},loopRequired:(b=t.loopRequired)!==null&&b!==void 0?b:E$,loopEnum:($=t.loopEnum)!==null&&$!==void 0?$:E$,meta:(R=t.meta)!==null&&R!==void 0?R:!0,messages:(A=t.messages)!==null&&A!==void 0?A:!0,inlineRefs:(O=t.inlineRefs)!==null&&O!==void 0?O:!0,schemaId:(q=t.schemaId)!==null&&q!==void 0?q:"$id",addUsedSchema:(J=t.addUsedSchema)!==null&&J!==void 0?J:!0,validateSchema:(De=t.validateSchema)!==null&&De!==void 0?De:!0,validateFormats:(Qe=t.validateFormats)!==null&&Qe!==void 0?Qe:!0,unicodeRegExp:(zt=t.unicodeRegExp)!==null&&zt!==void 0?zt:!0,int32range:(Vr=t.int32range)!==null&&Vr!==void 0?Vr:!0,uriResolver:Pr}}var $i=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,...vM(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new fM.ValueScope({scope:{},prefixes:bM,es5:r,lines:n}),this.logger=RM(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,mM.getRules)(),P$.call(this,wM,e,"NOT SUPPORTED"),P$.call(this,_M,e,"DEPRECATED","warn"),this._metaOpts=$M.call(this),e.formats&&xM.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&SM.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),kM.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=R$;n==="id"&&(o={...R$},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 C$.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,Si.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=A$.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new xi.SchemaEnv({schema:{},schemaId:n});if(r=xi.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=A$.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,Si.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(PM.call(this,n,r),!r)return(0,Cf.eachItem)(n,s=>Af.call(this,s)),this;CM.call(this,r);let o={...r,type:(0,ll.getJSONTypes)(r.type),schemaType:(0,ll.getJSONTypes)(r.schemaType)};return(0,Cf.eachItem)(n,o.type.length===0?s=>Af.call(this,s,o):s=>o.type.forEach(i=>Af.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]=O$(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,Si.normalizeId)(i||n);let l=Si.getSchemaRefs.call(this,e,n);return c=new xi.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):xi.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{xi.compileSchema.call(this,e)}finally{this.opts=r}}};$i.ValidationError=hM.default;$i.MissingRefError=C$.default;pt.default=$i;function P$(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 A$(t){return t=(0,Si.normalizeId)(t),this.schemas[t]||this.refs[t]}function kM(){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 xM(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function SM(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 $M(){let t={...this.opts};for(let e of yM)delete t[e];return t}var TM={log(){},warn(){},error(){}};function RM(t){if(t===!1)return TM;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 EM=/^[a-z_$][a-z0-9_$:-]*$/i;function PM(t,e){let{RULES:r}=this;if((0,Cf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!EM.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 Af(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,ll.getJSONTypes)(e.type),schemaType:(0,ll.getJSONTypes)(e.schemaType)}};e.before?AM.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 AM(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 CM(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=O$(e)),t.validateSchema=this.compile(e,!0))}var IM={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function O$(t){return{anyOf:[t,IM]}}});var L$=B(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var OM={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};If.default=OM});var M$=B(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.callRef=no.getValidate=void 0;var NM=_i(),j$=Xt(),Lt=me(),Xo=Fr(),z$=tl(),ul=$e(),LM={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=z$.resolveRef.call(c,l,o,r);if(u===void 0)throw new NM.default(n.opts.uriResolver,o,r);if(u instanceof z$.SchemaEnv)return w(u);return f(u);function p(){if(s===l)return dl(t,i,s,s.$async);let m=e.scopeValue("root",{ref:l});return dl(t,(0,Lt._)`${m}.validate`,l,l.$async)}function w(m){let b=D$(t,m);dl(t,b,m,m.$async)}function f(m){let b=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Lt.stringify)(m)}:{ref:m}),$=e.name("valid"),R=t.subschema({schema:m,dataTypes:[],schemaPath:Lt.nil,topSchemaRef:b,errSchemaPath:r},$);t.mergeEvaluated(R),t.ok($)}}};function D$(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Lt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}no.getValidate=D$;function dl(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Xo.default.this:Lt.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Lt._)`await ${(0,j$.callValidateCode)(t,e,l)}`),f(e),i||o.assign(m,!0)},b=>{o.if((0,Lt._)`!(${b} instanceof ${s.ValidationError})`,()=>o.throw(b)),w(b),i||o.assign(m,!1)}),t.ok(m)}function p(){t.result((0,j$.callValidateCode)(t,e,l),()=>f(e),()=>w(e))}function w(m){let b=(0,Lt._)`${m}.errors`;o.assign(Xo.default.vErrors,(0,Lt._)`${Xo.default.vErrors} === null ? ${b} : ${Xo.default.vErrors}.concat(${b})`),o.assign(Xo.default.errors,(0,Lt._)`${Xo.default.vErrors}.length`)}function f(m){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=ul.mergeEvaluated.props(o,$.props,s.props));else{let R=o.var("props",(0,Lt._)`${m}.evaluated.props`);s.props=ul.mergeEvaluated.props(o,R,s.props,Lt.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=ul.mergeEvaluated.items(o,$.items,s.items));else{let R=o.var("items",(0,Lt._)`${m}.evaluated.items`);s.items=ul.mergeEvaluated.items(o,R,s.items,Lt.Name)}}}no.callRef=dl;no.default=LM});var U$=B(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var jM=L$(),zM=M$(),DM=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",jM.default,zM.default];Of.default=DM});var q$=B(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var pl=me(),gn=pl.operators,hl={maximum:{okStr:"<=",ok:gn.LTE,fail:gn.GT},minimum:{okStr:">=",ok:gn.GTE,fail:gn.LT},exclusiveMaximum:{okStr:"<",ok:gn.LT,fail:gn.GTE},exclusiveMinimum:{okStr:">",ok:gn.GT,fail:gn.LTE}},MM={message:({keyword:t,schemaCode:e})=>(0,pl.str)`must be ${hl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pl._)`{comparison: ${hl[t].okStr}, limit: ${e}}`},UM={keyword:Object.keys(hl),type:"number",schemaType:"number",$data:!0,error:MM,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,pl._)`${r} ${hl[e].fail} ${n} || isNaN(${r})`)}};Nf.default=UM});var F$=B(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var Ti=me(),qM={message:({schemaCode:t})=>(0,Ti.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ti._)`{multipleOf: ${t}}`},FM={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:qM,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ti._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ti._)`${i} !== parseInt(${i})`;t.fail$data((0,Ti._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Lf.default=FM});var Z$=B(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});function B$(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}jf.default=B$;B$.code='require("ajv/dist/runtime/ucs2length").default'});var V$=B(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var oo=me(),BM=$e(),ZM=Z$(),VM={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,oo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,oo._)`{limit: ${t}}`},HM={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:VM,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?oo.operators.GT:oo.operators.LT,i=o.opts.unicode===!1?(0,oo._)`${r}.length`:(0,oo._)`${(0,BM.useFunc)(t.gen,ZM.default)}(${r})`;t.fail$data((0,oo._)`${i} ${s} ${n}`)}};zf.default=HM});var H$=B(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var KM=Xt(),WM=$e(),Qo=me(),GM={message:({schemaCode:t})=>(0,Qo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Qo._)`{pattern: ${t}}`},JM={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:GM,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,Qo._)`new RegExp`:(0,WM.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Qo._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Qo._)`!${u}`)}else{let c=(0,KM.usePattern)(t,o);t.fail$data((0,Qo._)`!${c}.test(${r})`)}}};Df.default=JM});var K$=B(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Ri=me(),YM={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ri.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ri._)`{limit: ${t}}`},XM={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:YM,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Ri.operators.GT:Ri.operators.LT;t.fail$data((0,Ri._)`Object.keys(${r}).length ${o} ${n}`)}};Mf.default=XM});var W$=B(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var Ei=Xt(),Pi=me(),QM=$e(),eU={message:({params:{missingProperty:t}})=>(0,Pi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Pi._)`{missingProperty: ${t}}`},tU={keyword:"required",type:"object",schemaType:"array",$data:!0,error:eU,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 f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let b of r)if(f?.[b]===void 0&&!m.has(b)){let $=i.schemaEnv.baseId+i.errSchemaPath,R=`required property "${b}" is not defined at "${$}" (strictRequired)`;(0,QM.checkStrictMode)(i,R,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(Pi.nil,p);else for(let f of r)(0,Ei.checkReportMissingProp)(t,f)}function u(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>w(f,m)),t.ok(m)}else e.if((0,Ei.checkMissingProp)(t,r,f)),(0,Ei.reportMissingProp)(t,f),e.else()}function p(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ei.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function w(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Ei.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Pi.not)(m),()=>{t.error(),e.break()})},Pi.nil)}}};Uf.default=tU});var G$=B(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var Ai=me(),rU={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ai.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ai._)`{limit: ${t}}`},nU={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:rU,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ai.operators.GT:Ai.operators.LT;t.fail$data((0,Ai._)`${r}.length ${o} ${n}`)}};qf.default=nU});var ml=B(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var J$=sf();J$.code='require("ajv/dist/runtime/equal").default';Ff.default=J$});var Y$=B(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var Bf=fi(),ht=me(),oU=$e(),sU=ml(),iU={message:({params:{i:t,j:e}})=>(0,ht.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ht._)`{i: ${t}, j: ${e}}`},aU={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:iU,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,Bf.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,ht._)`${i} === false`),t.ok(c);function u(){let m=e.let("i",(0,ht._)`${r}.length`),b=e.let("j");t.setParams({i:m,j:b}),e.assign(c,!0),e.if((0,ht._)`${m} > 1`,()=>(p()?w:f)(m,b))}function p(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function w(m,b){let $=e.name("item"),R=(0,Bf.checkDataTypes)(l,$,a.opts.strictNumbers,Bf.DataType.Wrong),A=e.const("indices",(0,ht._)`{}`);e.for((0,ht._)`;${m}--;`,()=>{e.let($,(0,ht._)`${r}[${m}]`),e.if(R,(0,ht._)`continue`),l.length>1&&e.if((0,ht._)`typeof ${$} == "string"`,(0,ht._)`${$} += "_"`),e.if((0,ht._)`typeof ${A}[${$}] == "number"`,()=>{e.assign(b,(0,ht._)`${A}[${$}]`),t.error(),e.assign(c,!1).break()}).code((0,ht._)`${A}[${$}] = ${m}`)})}function f(m,b){let $=(0,oU.useFunc)(e,sU.default),R=e.name("outer");e.label(R).for((0,ht._)`;${m}--;`,()=>e.for((0,ht._)`${b} = ${m}; ${b}--;`,()=>e.if((0,ht._)`${$}(${r}[${m}], ${r}[${b}])`,()=>{t.error(),e.assign(c,!1).break(R)})))}}};Zf.default=aU});var X$=B(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var Vf=me(),cU=$e(),lU=ml(),uU={message:"must be equal to constant",params:({schemaCode:t})=>(0,Vf._)`{allowedValue: ${t}}`},dU={keyword:"const",$data:!0,error:uU,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Vf._)`!${(0,cU.useFunc)(e,lU.default)}(${r}, ${o})`):t.fail((0,Vf._)`${s} !== ${r}`)}};Hf.default=dU});var Q$=B(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var Ci=me(),pU=$e(),hU=ml(),mU={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ci._)`{allowedValues: ${t}}`},fU={keyword:"enum",schemaType:"array",$data:!0,error:mU,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,pU.useFunc)(e,hU.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 f=e.const("vSchema",s);u=(0,Ci.or)(...o.map((m,b)=>w(f,b)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,f=>e.if((0,Ci._)`${l()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function w(f,m){let b=o[m];return typeof b=="object"&&b!==null?(0,Ci._)`${l()}(${r}, ${f}[${m}])`:(0,Ci._)`${r} === ${b}`}}};Kf.default=fU});var eT=B(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var gU=q$(),yU=F$(),bU=V$(),wU=H$(),_U=K$(),vU=W$(),kU=G$(),xU=Y$(),SU=X$(),$U=Q$(),TU=[gU.default,yU.default,bU.default,wU.default,_U.default,vU.default,kU.default,xU.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},SU.default,$U.default];Wf.default=TU});var Jf=B(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.validateAdditionalItems=void 0;var so=me(),Gf=$e(),RU={message:({params:{len:t}})=>(0,so.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,so._)`{limit: ${t}}`},EU={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:RU,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Gf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}tT(t,n)}};function tT(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,so._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,so._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Gf.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,so._)`${a} <= ${e.length}`);r.if((0,so.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Gf.Type.Num},l),i.allErrors||r.if((0,so.not)(l),()=>r.break())})}}Ii.validateAdditionalItems=tT;Ii.default=EU});var Yf=B(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.validateTuple=void 0;var rT=me(),fl=$e(),PU=Xt(),AU={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return nT(t,"additionalItems",e);r.items=!0,!(0,fl.alwaysValidSchema)(r,e)&&t.ok((0,PU.validateArray)(t))}};function nT(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=fl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,rT._)`${s}.length`);r.forEach((p,w)=>{(0,fl.alwaysValidSchema)(a,p)||(n.if((0,rT._)`${l} > ${w}`,()=>t.subschema({keyword:i,schemaProp:w,dataProp:w},c)),t.ok(c))});function u(p){let{opts:w,errSchemaPath:f}=a,m=r.length,b=m===p.minItems&&(m===p.maxItems||p[e]===!1);if(w.strictTuples&&!b){let $=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,fl.checkStrictMode)(a,$,w.strictTuples)}}}Oi.validateTuple=nT;Oi.default=AU});var oT=B(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var CU=Yf(),IU={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,CU.validateTuple)(t,"items")};Xf.default=IU});var iT=B(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var sT=me(),OU=$e(),NU=Xt(),LU=Jf(),jU={message:({params:{len:t}})=>(0,sT.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sT._)`{limit: ${t}}`},zU={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:jU,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,OU.alwaysValidSchema)(n,e)&&(o?(0,LU.validateAdditionalItems)(t,o):t.ok((0,NU.validateArray)(t)))}};Qf.default=zU});var aT=B(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});var er=me(),gl=$e(),DU={message:({params:{min:t,max:e}})=>e===void 0?(0,er.str)`must contain at least ${t} valid item(s)`:(0,er.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,er._)`{minContains: ${t}}`:(0,er._)`{minContains: ${t}, maxContains: ${e}}`},MU={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:DU,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,er._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,gl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,gl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,gl.alwaysValidSchema)(s,r)){let b=(0,er._)`${u} >= ${i}`;a!==void 0&&(b=(0,er._)`${b} && ${u} <= ${a}`),t.pass(b);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?f(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,er._)`${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);f(b,()=>e.if(b,()=>m($)))}function f(b,$){e.forRange("i",0,u,R=>{t.subschema({keyword:"contains",dataProp:R,dataPropType:gl.Type.Num,compositeRule:!0},b),$()})}function m(b){e.code((0,er._)`${b}++`),a===void 0?e.if((0,er._)`${b} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,er._)`${b} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,er._)`${b} >= ${i}`,()=>e.assign(p,!0)))}}};eg.default=MU});var uT=B(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.validateSchemaDeps=Tr.validatePropertyDeps=Tr.error=void 0;var tg=me(),UU=$e(),Ni=Xt();Tr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,tg.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,tg._)`{property: ${t},
2488
2519
  missingProperty: ${n},
2489
2520
  depsCount: ${e},
2490
- deps: ${r}}`};var UU={keyword:"dependencies",type:"object",schemaType:"object",error:Tr.error,code(t){let[e,r]=qU(t);aT(t,e),cT(t,r)}};function qU({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 aT(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,Ni.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,Ni.checkReportMissingProp)(t,l)}):(r.if((0,eg._)`${c} && (${(0,Ni.checkMissingProp)(t,a,s)})`),(0,Ni.reportMissingProp)(t,s),r.else())}}Tr.validatePropertyDeps=aT;function cT(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,MU.alwaysValidSchema)(s,e[a])||(r.if((0,Ni.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))}Tr.validateSchemaDeps=cT;Tr.default=UU});var dT=B(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});var uT=me(),FU=$e(),BU={message:"property name must be valid",params:({params:t})=>(0,uT._)`{propertyName: ${t.propertyName}}`},ZU={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:BU,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,FU.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,uT.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};tg.default=ZU});var ng=B(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});var yl=Xt(),hr=me(),VU=Fr(),bl=$e(),HU={message:"must NOT have additional properties",params:({params:t})=>(0,hr._)`{additionalProperty: ${t.additionalProperty}}`},KU={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:HU,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,bl.alwaysValidSchema)(i,r))return;let l=(0,yl.allSchemaProperties)(n.properties),u=(0,yl.allSchemaProperties)(n.patternProperties);p(),t.ok((0,hr._)`${s} === ${VU.default.errors}`);function p(){e.forIn("key",o,$=>{!l.length&&!u.length?m($):e.if(w($),()=>m($))})}function w($){let R;if(l.length>8){let A=(0,bl.schemaRefOrVal)(i,n.properties,"properties");R=(0,yl.isOwnProperty)(e,A,$)}else l.length?R=(0,hr.or)(...l.map(A=>(0,hr._)`${$} === ${A}`)):R=hr.nil;return u.length&&(R=(0,hr.or)(R,...u.map(A=>(0,hr._)`${(0,yl.usePattern)(t,A)}.test(${$})`))),(0,hr.not)(R)}function f($){e.code((0,hr._)`delete ${o}[${$}]`)}function m($){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f($);return}if(r===!1){t.setParams({additionalProperty:$}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,bl.alwaysValidSchema)(i,r)){let R=e.name("valid");c.removeAdditional==="failing"?(b($,R,!1),e.if((0,hr.not)(R),()=>{t.reset(),f($)})):(b($,R),a||e.if((0,hr.not)(R),()=>e.break()))}}function b($,R,A){let O={keyword:"additionalProperties",dataProp:$,dataPropType:bl.Type.Str};A===!1&&Object.assign(O,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(O,R)}}};rg.default=KU});var mT=B(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var WU=wi(),pT=Xt(),og=$e(),hT=ng(),GU={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&&hT.default.code(new WU.KeywordCxt(s,hT.default,"additionalProperties"));let i=(0,pT.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=og.mergeEvaluated.props(e,(0,og.toHash)(i),s.props));let a=i.filter(p=>!(0,og.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,pT.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)}}};sg.default=GU});var bT=B(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var fT=Xt(),wl=me(),gT=$e(),yT=$e(),JU={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,fT.allSchemaProperties)(r),c=a.filter(b=>(0,gT.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 wl.Name)&&(s.props=(0,yT.evaluatedPropsToName)(e,s.props));let{props:p}=s;w();function w(){for(let b of a)l&&f(b),s.allErrors?m(b):(e.var(u,!0),m(b),e.if(u))}function f(b){for(let $ in l)new RegExp(b).test($)&&(0,gT.checkStrictMode)(s,`property ${$} matches pattern ${b} (use allowMatchingProperties)`)}function m(b){e.forIn("key",n,$=>{e.if((0,wl._)`${(0,fT.usePattern)(t,b)}.test(${$})`,()=>{let R=c.includes(b);R||t.subschema({keyword:"patternProperties",schemaProp:b,dataProp:$,dataPropType:yT.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,wl._)`${p}[${$}]`,!0):!R&&!s.allErrors&&e.if((0,wl.not)(u),()=>e.break())})})}}};ig.default=JU});var wT=B(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var YU=$e(),XU={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,YU.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"}};ag.default=XU});var _T=B(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});var QU=Xt(),eq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:QU.validateUnion,error:{message:"must match a schema in anyOf"}};cg.default=eq});var vT=B(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var _l=me(),tq=$e(),rq={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,_l._)`{passingSchemas: ${t.passing}}`},nq={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:rq,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,tq.alwaysValidSchema)(o,u)?e.var(c,!0):w=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,_l._)`${c} && ${i}`).assign(i,!1).assign(a,(0,_l._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),w&&t.mergeEvaluated(w,_l.Name)})})}}};lg.default=nq});var xT=B(ug=>{"use strict";Object.defineProperty(ug,"__esModule",{value:!0});var oq=$e(),sq={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,oq.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};ug.default=sq});var $T=B(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var vl=me(),ST=$e(),iq={message:({params:t})=>(0,vl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,vl._)`{failingKeyword: ${t.ifClause}}`},aq={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:iq,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,ST.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=kT(n,"then"),s=kT(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,vl.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,vl._)`${u}`):t.setParams({ifClause:u})}}}};function kT(t,e){let r=t.schema[e];return r!==void 0&&!(0,ST.alwaysValidSchema)(t,r)}dg.default=aq});var TT=B(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var cq=$e(),lq={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,cq.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};pg.default=lq});var RT=B(hg=>{"use strict";Object.defineProperty(hg,"__esModule",{value:!0});var uq=Gf(),dq=nT(),pq=Jf(),hq=sT(),mq=iT(),fq=lT(),gq=dT(),yq=ng(),bq=mT(),wq=bT(),_q=wT(),vq=_T(),xq=vT(),kq=xT(),Sq=$T(),$q=TT();function Tq(t=!1){let e=[_q.default,vq.default,xq.default,kq.default,Sq.default,$q.default,gq.default,yq.default,fq.default,bq.default,wq.default];return t?e.push(dq.default,hq.default):e.push(uq.default,pq.default),e.push(mq.default),e}hg.default=Tq});var ET=B(mg=>{"use strict";Object.defineProperty(mg,"__esModule",{value:!0});var Ge=me(),Rq={message:({schemaCode:t})=>(0,Ge.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ge._)`{format: ${t}}`},Eq={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Rq,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():f();function w(){let m=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),b=r.const("fDef",(0,Ge._)`${m}[${i}]`),$=r.let("fType"),R=r.let("format");r.if((0,Ge._)`typeof ${b} == "object" && !(${b} instanceof RegExp)`,()=>r.assign($,(0,Ge._)`${b}.type || "string"`).assign(R,(0,Ge._)`${b}.validate`),()=>r.assign($,(0,Ge._)`"string"`).assign(R,b)),t.fail$data((0,Ge.or)(A(),O()));function A(){return c.strictSchema===!1?Ge.nil:(0,Ge._)`${i} && !${R}`}function O(){let q=u.$async?(0,Ge._)`(${b}.async ? await ${R}(${n}) : ${R}(${n}))`:(0,Ge._)`${R}(${n})`,Y=(0,Ge._)`(typeof ${R} == "function" ? ${q} : ${R}.test(${n}))`;return(0,Ge._)`${R} && ${R} !== true && ${$} === ${e} && !${Y}`}}function f(){let m=p.formats[s];if(!m){A();return}if(m===!0)return;let[b,$,R]=O(m);b===e&&t.pass(q());function A(){if(c.strictSchema===!1){p.logger.warn(Y());return}throw new Error(Y());function Y(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function O(Y){let De=Y instanceof RegExp?(0,Ge.regexpCode)(Y):c.code.formats?(0,Ge._)`${c.code.formats}${(0,Ge.getProperty)(s)}`:void 0,Qe=r.scopeValue("formats",{key:s,ref:Y,code:De});return typeof Y=="object"&&!(Y instanceof RegExp)?[Y.type||"string",Y.validate,(0,Ge._)`${Qe}.validate`]:["string",Y,Qe]}function q(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ge._)`await ${R}(${n})`}return typeof $=="function"?(0,Ge._)`${R}(${n})`:(0,Ge._)`${R}.test(${n})`}}}};mg.default=Eq});var PT=B(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var Pq=ET(),Aq=[Pq.default];fg.default=Aq});var AT=B(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.contentVocabulary=ts.metadataVocabulary=void 0;ts.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ts.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var IT=B(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var Cq=M$(),Iq=Q$(),Oq=RT(),Nq=PT(),CT=AT(),Lq=[Cq.default,Iq.default,(0,Oq.default)(),Nq.default,CT.metadataVocabulary,CT.contentVocabulary];gg.default=Lq});var NT=B(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});xl.DiscrError=void 0;var OT;(function(t){t.Tag="tag",t.Mapping="mapping"})(OT||(xl.DiscrError=OT={}))});var jT=B(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var rs=me(),yg=NT(),LT=tl(),jq=_i(),zq=$e(),Dq={message:({params:{discrError:t,tagName:e}})=>t===yg.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,rs._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Mq={keyword:"discriminator",type:"object",schemaType:"object",error:Dq,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,rs._)`${r}${(0,rs.getProperty)(a)}`);e.if((0,rs._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:yg.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let f=w();e.if(!1);for(let m in f)e.elseIf((0,rs._)`${l} === ${m}`),e.assign(c,p(f[m]));e.else(),t.error(!1,{discrError:yg.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(f){let m=e.name("valid"),b=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(b,rs.Name),m}function w(){var f;let m={},b=R(o),$=!0;for(let q=0;q<i.length;q++){let Y=i[q];if(Y?.$ref&&!(0,zq.schemaHasRulesButRef)(Y,s.self.RULES)){let Qe=Y.$ref;if(Y=LT.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Qe),Y instanceof LT.SchemaEnv&&(Y=Y.schema),Y===void 0)throw new jq.default(s.opts.uriResolver,s.baseId,Qe)}let De=(f=Y?.properties)===null||f===void 0?void 0:f[a];if(typeof De!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(b||R(Y)),A(De,q)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return m;function R({required:q}){return Array.isArray(q)&&q.includes(a)}function A(q,Y){if(q.const)O(q.const,Y);else if(q.enum)for(let De of q.enum)O(De,Y);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function O(q,Y){if(typeof q!="string"||q in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[q]=Y}}}};bg.default=Mq});var zT=B((T6,Uq)=>{Uq.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 _g=B((qe,wg)=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.MissingRefError=qe.ValidationError=qe.CodeGen=qe.Name=qe.nil=qe.stringify=qe.str=qe._=qe.KeywordCxt=qe.Ajv=void 0;var qq=O$(),Fq=IT(),Bq=jT(),DT=zT(),Zq=["/properties"],kl="http://json-schema.org/draft-07/schema",ns=class extends qq.default{_addVocabularies(){super._addVocabularies(),Fq.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Bq.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(DT,Zq):DT;this.addMetaSchema(e,kl,!1),this.refs["http://json-schema.org/schema"]=kl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(kl)?kl:void 0)}};qe.Ajv=ns;wg.exports=qe=ns;wg.exports.Ajv=ns;Object.defineProperty(qe,"__esModule",{value:!0});qe.default=ns;var Vq=wi();Object.defineProperty(qe,"KeywordCxt",{enumerable:!0,get:function(){return Vq.KeywordCxt}});var os=me();Object.defineProperty(qe,"_",{enumerable:!0,get:function(){return os._}});Object.defineProperty(qe,"str",{enumerable:!0,get:function(){return os.str}});Object.defineProperty(qe,"stringify",{enumerable:!0,get:function(){return os.stringify}});Object.defineProperty(qe,"nil",{enumerable:!0,get:function(){return os.nil}});Object.defineProperty(qe,"Name",{enumerable:!0,get:function(){return os.Name}});Object.defineProperty(qe,"CodeGen",{enumerable:!0,get:function(){return os.CodeGen}});var Hq=Qc();Object.defineProperty(qe,"ValidationError",{enumerable:!0,get:function(){return Hq.default}});var Kq=_i();Object.defineProperty(qe,"MissingRefError",{enumerable:!0,get:function(){return Kq.default}})});var HT=B(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.formatNames=Er.fastFormats=Er.fullFormats=void 0;function Rr(t,e){return{validate:t,compare:e}}Er.fullFormats={date:Rr(FT,Sg),time:Rr(xg(!0),$g),"date-time":Rr(MT(!0),ZT),"iso-time":Rr(xg(),BT),"iso-date-time":Rr(MT(),VT),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Qq,"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:iF,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:eF,int32:{type:"number",validate:nF},int64:{type:"number",validate:oF},float:{type:"number",validate:qT},double:{type:"number",validate:qT},password:!0,binary:!0};Er.fastFormats={...Er.fullFormats,date:Rr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Sg),time:Rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,$g),"date-time":Rr(/^\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,ZT),"iso-time":Rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,BT),"iso-date-time":Rr(/^\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,VT),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};Er.formatNames=Object.keys(Er.fullFormats);function Wq(t){return t%4===0&&(t%100!==0||t%400===0)}var Gq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Jq=[0,31,28,31,30,31,30,31,31,30,31,30,31];function FT(t){let e=Gq.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&&Wq(r)?29:Jq[n])}function Sg(t,e){if(t&&e)return t>e?1:t<e?-1:0}var vg=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function xg(t){return function(r){let n=vg.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 $g(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 BT(t,e){if(!(t&&e))return;let r=vg.exec(t),n=vg.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 kg=/t|\s/i;function MT(t){let e=xg(t);return function(n){let o=n.split(kg);return o.length===2&&FT(o[0])&&e(o[1])}}function ZT(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function VT(t,e){if(!(t&&e))return;let[r,n]=t.split(kg),[o,s]=e.split(kg),i=Sg(r,o);if(i!==void 0)return i||$g(n,s)}var Yq=/\/|:/,Xq=/^(?:[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 Qq(t){return Yq.test(t)&&Xq.test(t)}var UT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function eF(t){return UT.lastIndex=0,UT.test(t)}var tF=-(2**31),rF=2**31-1;function nF(t){return Number.isInteger(t)&&t<=rF&&t>=tF}function oF(t){return Number.isInteger(t)}function qT(){return!0}var sF=/[^\\]\\Z/;function iF(t){if(sF.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var KT=B(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.formatLimitDefinition=void 0;var aF=_g(),mr=me(),yn=mr.operators,Sl={formatMaximum:{okStr:"<=",ok:yn.LTE,fail:yn.GT},formatMinimum:{okStr:">=",ok:yn.GTE,fail:yn.LT},formatExclusiveMaximum:{okStr:"<",ok:yn.LT,fail:yn.GTE},formatExclusiveMinimum:{okStr:">",ok:yn.GT,fail:yn.LTE}},cF={message:({keyword:t,schemaCode:e})=>(0,mr.str)`should be ${Sl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,mr._)`{comparison: ${Sl[t].okStr}, limit: ${e}}`};ss.formatLimitDefinition={keyword:Object.keys(Sl),type:"string",schemaType:"string",$data:!0,error:cF,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 aF.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}),f=e.const("fmt",(0,mr._)`${w}[${c.schemaCode}]`);t.fail$data((0,mr.or)((0,mr._)`typeof ${f} != "object"`,(0,mr._)`${f} instanceof RegExp`,(0,mr._)`typeof ${f}.compare != "function"`,p(f)))}function u(){let w=c.schema,f=a.formats[w];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${w}" does not define "compare" function`);let m=e.scopeValue("formats",{key:w,ref:f,code:i.code.formats?(0,mr._)`${i.code.formats}${(0,mr.getProperty)(w)}`:void 0});t.fail$data(p(m))}function p(w){return(0,mr._)`${w}.compare(${r}, ${n}) ${Sl[o].fail} 0`}},dependencies:["format"]};var lF=t=>(t.addKeyword(ss.formatLimitDefinition),t);ss.default=lF});var YT=B((Li,JT)=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});var is=HT(),uF=KT(),Tg=me(),WT=new Tg.Name("fullFormats"),dF=new Tg.Name("fastFormats"),Rg=(t,e={keywords:!0})=>{if(Array.isArray(e))return GT(t,e,is.fullFormats,WT),t;let[r,n]=e.mode==="fast"?[is.fastFormats,dF]:[is.fullFormats,WT],o=e.formats||is.formatNames;return GT(t,o,r,n),e.keywords&&(0,uF.default)(t),t};Rg.get=(t,e="full")=>{let n=(e==="fast"?is.fastFormats:is.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function GT(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Tg._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}JT.exports=Li=Rg;Object.defineProperty(Li,"__esModule",{value:!0});Li.default=Rg});function pF(){let t=new XT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,QT.default)(t),t}var XT,QT,$l,eR=L(()=>{XT=Dl(_g(),1),QT=Dl(YT(),1);$l=class{constructor(e){this._ajv=e??pF()}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 Tl,tR=L(()=>{Bo();Tl=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},oi,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},Fo,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 rR(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 nR(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 oR=L(()=>{});var Rl,sR=L(()=>{Jk();Bo();eR();Hs();tR();oR();Rl=class extends Uc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ni.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 $l,this.setRequestHandler(Lh,n=>this._oninitialize(n)),this.setNotificationHandler(jh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Bh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ni.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Tl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Gk(this._capabilities,e)}setRequestHandler(e,r){let o=sn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=zo(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=on(qo,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new J(Q.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,w=await Promise.resolve(r(c,l));if(p.task){let m=on(Mo,w);if(!m.success){let b=m.error instanceof Error?m.error.message:String(m.error);throw new J(Q.InvalidParams,`Invalid task creation result: ${b}`)}return m.data}let f=on(Ec,w);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new J(Q.InvalidParams,`Invalid tools/call result: ${m}`)}return f.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){nR(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&rR(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:Gx.includes(r)?r:Ah,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"},pc)}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},Zh,r):this.request({method:"sampling/createMessage",params:e},oi,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},Fo,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},Fo,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new J(Q.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof J?i:new J(Q.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},Vh,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 Eg(t){return!!t&&typeof t=="object"&&aR in t}function cR(t){return t[aR]?.complete}var aR,iR,lR=L(()=>{aR=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(iR||(iR={}))});var uR=L(()=>{});function mF(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"),!hF.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 fF(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 Pg(t){let e=mF(t);return fF(t,e.warnings),e.isValid}var hF,dR=L(()=>{hF=/^[A-Za-z0-9._-]{1,128}$/});var El,pR=L(()=>{El=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 gF(t,e){let r=0,n=[t];for(;n.length>0;){let o=n.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let s of o){if(++r>e)return r;s!==null&&typeof s=="object"&&n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>e)return r;let i=o[s];i!==null&&typeof i=="object"&&n.push(i)}}return r}function yF(t){if(!(t===void 0||t===1/0)){if(typeof t!="number"||Number.isNaN(t)||t<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(t)}`);return t}}function fR(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function gR(t){return"_def"in t||"_zod"in t||fR(t)}function Ag(t){return typeof t!="object"||t===null||gR(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(fR)}function hR(t){if(t){if(Ag(t))return Kn(t);if(!gR(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function wF(t){let e=sn(t);return e?Object.entries(e).map(([r,n])=>{let o=_x(n),s=vx(n);return{name:r,description:o,required:!s}}):[]}function bn(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=zo(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function mR(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Pl,bF,ji,yR=L(()=>{sR();Hs();Em();Bo();lR();uR();dR();pR();zn();Pl=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 Rl(e,r),this._maxToolInputElements=yF(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new El(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(bn(Rc)),this.server.assertCanSetRequestHandler(bn(qo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Rc,()=>({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=jo(r.inputSchema);return o?$m(o,{strictUnions:!0,pipeStrategy:"input"}):bF})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=jo(r.outputSchema);o&&(n.outputSchema=$m(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(qo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new J(Q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new J(Q.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 J(Q.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new J(Q.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 J&&n.code===Q.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(this._maxToolInputElements!==void 0&&gF(r,this._maxToolInputElements)>this._maxToolInputElements)throw new J(Q.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=jo(e.inputSchema)??e.inputSchema,i=await sc(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",c=ic(a);throw new J(Q.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 J(Q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=jo(e.outputSchema),s=await sc(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ic(i);throw new J(Q.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 J(Q.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(bn(Pc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Pc,async e=>{switch(e.params.ref.type){case"ref/prompt":return dk(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return pk(e),this.handleResourceCompletion(e,e.params.ref);default:throw new J(Q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new J(Q.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new J(Q.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ji;let s=sn(n.argsSchema)?.[e.params.argument.name];if(!Eg(s))return ji;let i=cR(s);if(!i)return ji;let a=await i(e.params.argument.value,e.params.context);return mR(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 ji;throw new J(Q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ji;let s=await o(e.params.argument.value,e.params.context);return mR(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(bn(xc)),this.server.assertCanSetRequestHandler(bn(kc)),this.server.assertCanSetRequestHandler(bn(Sc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(xc,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(kc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Sc,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new J(Q.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 J(Q.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(bn($c)),this.server.assertCanSetRequestHandler(bn(Tc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($c,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?wF(r.argsSchema):void 0}))})),this.server.setRequestHandler(Tc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new J(Q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new J(Q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=jo(n.argsSchema),s=await sc(o,e.params.arguments??{});if(!s.success){let c="error"in s?s.error:"Unknown error",l=ic(c);throw new J(Q.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:Kn(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=Kn(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 $t?c._def?.innerType:c;return Eg(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){Pg(e);let u={title:r,description:n,inputSchema:hR(o),outputSchema:hR(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"&&Pg(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=Kn(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Kn(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(Ag(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Ag(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()}},bF={type:"object",properties:{}};ji={completion:{values:[],hasMore:!1}}});function vF(t){return nk.parse(JSON.parse(t))}function bR(t){return JSON.stringify(t)+`
2491
- `}var _F,Al,wR=L(()=>{Bo();_F=10*1024*1024,Al=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??_F}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(`
2492
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),vF(r)}clear(){this._buffer=void 0}}});import _R from"node:process";var Cl,vR=L(()=>{wR();Cl=class{constructor(e=_R.stdin,r=_R.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 Al({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=bR(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var xR,kR=L(()=>{xR=[]});var IR={};ls(IR,{AUTHORING_MCP_SERVER_NAME:()=>RR,AUTHORING_MCP_SERVER_VERSION:()=>ER,AUTHORING_RESOURCES:()=>EF,AUTHORING_TOOLS:()=>RF,AUTHORING_TOOLS_PUBLIC:()=>CR,buildAuthoringMcpServer:()=>AR,resolveSamplesDir:()=>PR,runAuthoringMcpServer:()=>PF});import{promises as xF}from"node:fs";import{isAbsolute as kF,resolve as Il,sep as SF}from"node:path";function TR(){return $R??=import("../mcp/grounding.js").then(e=>e,()=>null),$R}function PR(t,e){if(e===void 0)return Il(process.cwd(),t??"samples");let r=Il(e);if(t===void 0)return r;if(kF(t))return null;let n=Il(r,t);return n===r||n.startsWith(r+SF)?n:null}function Fe(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function TF(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 AR(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let f=await nr(t.baseUrl);if(!f)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:f.baseUrl,token:f.token}}let r=t.grounding??{},n=await TR(),o=null;if(n)try{let f=await e();o={surface:"mcp-authoring",baseUrl:f.baseUrl,token:f.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(f=>({id:f.id,record_type:f.record_type,intent:f.intent}))}catch{c=[]}}let l=o?await TF(o,r):null,u=new Pl({name:RR,version:ER},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(f=>f.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let f=o;for(let m of a)u.registerPrompt(m.id,{title:m.name,description:m.description},async()=>{let b=await n.getMcpPromptSkill(f,m.id,r);if(!b)throw new Error(`unknown prompt: ${m.id}`);return{description:b.description,messages:[{role:"user",content:{type:"text",text:(b.prompts??[]).join(`
2521
+ deps: ${r}}`};var qU={keyword:"dependencies",type:"object",schemaType:"object",error:Tr.error,code(t){let[e,r]=FU(t);cT(t,e),lT(t,r)}};function FU({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 cT(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,Ni.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,Ni.checkReportMissingProp)(t,l)}):(r.if((0,tg._)`${c} && (${(0,Ni.checkMissingProp)(t,a,s)})`),(0,Ni.reportMissingProp)(t,s),r.else())}}Tr.validatePropertyDeps=cT;function lT(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,UU.alwaysValidSchema)(s,e[a])||(r.if((0,Ni.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))}Tr.validateSchemaDeps=lT;Tr.default=qU});var pT=B(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});var dT=me(),BU=$e(),ZU={message:"property name must be valid",params:({params:t})=>(0,dT._)`{propertyName: ${t.propertyName}}`},VU={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ZU,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,BU.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,dT.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};rg.default=VU});var og=B(ng=>{"use strict";Object.defineProperty(ng,"__esModule",{value:!0});var yl=Xt(),hr=me(),HU=Fr(),bl=$e(),KU={message:"must NOT have additional properties",params:({params:t})=>(0,hr._)`{additionalProperty: ${t.additionalProperty}}`},WU={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:KU,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,bl.alwaysValidSchema)(i,r))return;let l=(0,yl.allSchemaProperties)(n.properties),u=(0,yl.allSchemaProperties)(n.patternProperties);p(),t.ok((0,hr._)`${s} === ${HU.default.errors}`);function p(){e.forIn("key",o,$=>{!l.length&&!u.length?m($):e.if(w($),()=>m($))})}function w($){let R;if(l.length>8){let A=(0,bl.schemaRefOrVal)(i,n.properties,"properties");R=(0,yl.isOwnProperty)(e,A,$)}else l.length?R=(0,hr.or)(...l.map(A=>(0,hr._)`${$} === ${A}`)):R=hr.nil;return u.length&&(R=(0,hr.or)(R,...u.map(A=>(0,hr._)`${(0,yl.usePattern)(t,A)}.test(${$})`))),(0,hr.not)(R)}function f($){e.code((0,hr._)`delete ${o}[${$}]`)}function m($){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f($);return}if(r===!1){t.setParams({additionalProperty:$}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,bl.alwaysValidSchema)(i,r)){let R=e.name("valid");c.removeAdditional==="failing"?(b($,R,!1),e.if((0,hr.not)(R),()=>{t.reset(),f($)})):(b($,R),a||e.if((0,hr.not)(R),()=>e.break()))}}function b($,R,A){let O={keyword:"additionalProperties",dataProp:$,dataPropType:bl.Type.Str};A===!1&&Object.assign(O,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(O,R)}}};ng.default=WU});var fT=B(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var GU=wi(),hT=Xt(),sg=$e(),mT=og(),JU={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&&mT.default.code(new GU.KeywordCxt(s,mT.default,"additionalProperties"));let i=(0,hT.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=sg.mergeEvaluated.props(e,(0,sg.toHash)(i),s.props));let a=i.filter(p=>!(0,sg.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,hT.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)}}};ig.default=JU});var wT=B(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var gT=Xt(),wl=me(),yT=$e(),bT=$e(),YU={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,gT.allSchemaProperties)(r),c=a.filter(b=>(0,yT.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 wl.Name)&&(s.props=(0,bT.evaluatedPropsToName)(e,s.props));let{props:p}=s;w();function w(){for(let b of a)l&&f(b),s.allErrors?m(b):(e.var(u,!0),m(b),e.if(u))}function f(b){for(let $ in l)new RegExp(b).test($)&&(0,yT.checkStrictMode)(s,`property ${$} matches pattern ${b} (use allowMatchingProperties)`)}function m(b){e.forIn("key",n,$=>{e.if((0,wl._)`${(0,gT.usePattern)(t,b)}.test(${$})`,()=>{let R=c.includes(b);R||t.subschema({keyword:"patternProperties",schemaProp:b,dataProp:$,dataPropType:bT.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,wl._)`${p}[${$}]`,!0):!R&&!s.allErrors&&e.if((0,wl.not)(u),()=>e.break())})})}}};ag.default=YU});var _T=B(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});var XU=$e(),QU={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,XU.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"}};cg.default=QU});var vT=B(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var eq=Xt(),tq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:eq.validateUnion,error:{message:"must match a schema in anyOf"}};lg.default=tq});var kT=B(ug=>{"use strict";Object.defineProperty(ug,"__esModule",{value:!0});var _l=me(),rq=$e(),nq={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,_l._)`{passingSchemas: ${t.passing}}`},oq={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:nq,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,rq.alwaysValidSchema)(o,u)?e.var(c,!0):w=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,_l._)`${c} && ${i}`).assign(i,!1).assign(a,(0,_l._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),w&&t.mergeEvaluated(w,_l.Name)})})}}};ug.default=oq});var xT=B(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var sq=$e(),iq={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,sq.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};dg.default=iq});var TT=B(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var vl=me(),$T=$e(),aq={message:({params:t})=>(0,vl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,vl._)`{failingKeyword: ${t.ifClause}}`},cq={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:aq,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,$T.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=ST(n,"then"),s=ST(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,vl.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,vl._)`${u}`):t.setParams({ifClause:u})}}}};function ST(t,e){let r=t.schema[e];return r!==void 0&&!(0,$T.alwaysValidSchema)(t,r)}pg.default=cq});var RT=B(hg=>{"use strict";Object.defineProperty(hg,"__esModule",{value:!0});var lq=$e(),uq={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,lq.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};hg.default=uq});var ET=B(mg=>{"use strict";Object.defineProperty(mg,"__esModule",{value:!0});var dq=Jf(),pq=oT(),hq=Yf(),mq=iT(),fq=aT(),gq=uT(),yq=pT(),bq=og(),wq=fT(),_q=wT(),vq=_T(),kq=vT(),xq=kT(),Sq=xT(),$q=TT(),Tq=RT();function Rq(t=!1){let e=[vq.default,kq.default,xq.default,Sq.default,$q.default,Tq.default,yq.default,bq.default,gq.default,wq.default,_q.default];return t?e.push(pq.default,mq.default):e.push(dq.default,hq.default),e.push(fq.default),e}mg.default=Rq});var PT=B(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var Ge=me(),Eq={message:({schemaCode:t})=>(0,Ge.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ge._)`{format: ${t}}`},Pq={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Eq,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():f();function w(){let m=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),b=r.const("fDef",(0,Ge._)`${m}[${i}]`),$=r.let("fType"),R=r.let("format");r.if((0,Ge._)`typeof ${b} == "object" && !(${b} instanceof RegExp)`,()=>r.assign($,(0,Ge._)`${b}.type || "string"`).assign(R,(0,Ge._)`${b}.validate`),()=>r.assign($,(0,Ge._)`"string"`).assign(R,b)),t.fail$data((0,Ge.or)(A(),O()));function A(){return c.strictSchema===!1?Ge.nil:(0,Ge._)`${i} && !${R}`}function O(){let q=u.$async?(0,Ge._)`(${b}.async ? await ${R}(${n}) : ${R}(${n}))`:(0,Ge._)`${R}(${n})`,J=(0,Ge._)`(typeof ${R} == "function" ? ${q} : ${R}.test(${n}))`;return(0,Ge._)`${R} && ${R} !== true && ${$} === ${e} && !${J}`}}function f(){let m=p.formats[s];if(!m){A();return}if(m===!0)return;let[b,$,R]=O(m);b===e&&t.pass(q());function A(){if(c.strictSchema===!1){p.logger.warn(J());return}throw new Error(J());function J(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function O(J){let De=J instanceof RegExp?(0,Ge.regexpCode)(J):c.code.formats?(0,Ge._)`${c.code.formats}${(0,Ge.getProperty)(s)}`:void 0,Qe=r.scopeValue("formats",{key:s,ref:J,code:De});return typeof J=="object"&&!(J instanceof RegExp)?[J.type||"string",J.validate,(0,Ge._)`${Qe}.validate`]:["string",J,Qe]}function q(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ge._)`await ${R}(${n})`}return typeof $=="function"?(0,Ge._)`${R}(${n})`:(0,Ge._)`${R}.test(${n})`}}}};fg.default=Pq});var AT=B(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var Aq=PT(),Cq=[Aq.default];gg.default=Cq});var CT=B(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.contentVocabulary=es.metadataVocabulary=void 0;es.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];es.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var OT=B(yg=>{"use strict";Object.defineProperty(yg,"__esModule",{value:!0});var Iq=U$(),Oq=eT(),Nq=ET(),Lq=AT(),IT=CT(),jq=[Iq.default,Oq.default,(0,Nq.default)(),Lq.default,IT.metadataVocabulary,IT.contentVocabulary];yg.default=jq});var LT=B(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.DiscrError=void 0;var NT;(function(t){t.Tag="tag",t.Mapping="mapping"})(NT||(kl.DiscrError=NT={}))});var zT=B(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});var ts=me(),bg=LT(),jT=tl(),zq=_i(),Dq=$e(),Mq={message:({params:{discrError:t,tagName:e}})=>t===bg.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ts._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Uq={keyword:"discriminator",type:"object",schemaType:"object",error:Mq,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,ts._)`${r}${(0,ts.getProperty)(a)}`);e.if((0,ts._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:bg.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let f=w();e.if(!1);for(let m in f)e.elseIf((0,ts._)`${l} === ${m}`),e.assign(c,p(f[m]));e.else(),t.error(!1,{discrError:bg.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(f){let m=e.name("valid"),b=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(b,ts.Name),m}function w(){var f;let m={},b=R(o),$=!0;for(let q=0;q<i.length;q++){let J=i[q];if(J?.$ref&&!(0,Dq.schemaHasRulesButRef)(J,s.self.RULES)){let Qe=J.$ref;if(J=jT.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Qe),J instanceof jT.SchemaEnv&&(J=J.schema),J===void 0)throw new zq.default(s.opts.uriResolver,s.baseId,Qe)}let De=(f=J?.properties)===null||f===void 0?void 0:f[a];if(typeof De!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(b||R(J)),A(De,q)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return m;function R({required:q}){return Array.isArray(q)&&q.includes(a)}function A(q,J){if(q.const)O(q.const,J);else if(q.enum)for(let De of q.enum)O(De,J);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function O(q,J){if(typeof q!="string"||q in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[q]=J}}}};wg.default=Uq});var DT=B((R6,qq)=>{qq.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 vg=B((qe,_g)=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.MissingRefError=qe.ValidationError=qe.CodeGen=qe.Name=qe.nil=qe.stringify=qe.str=qe._=qe.KeywordCxt=qe.Ajv=void 0;var Fq=N$(),Bq=OT(),Zq=zT(),MT=DT(),Vq=["/properties"],xl="http://json-schema.org/draft-07/schema",rs=class extends Fq.default{_addVocabularies(){super._addVocabularies(),Bq.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Zq.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(MT,Vq):MT;this.addMetaSchema(e,xl,!1),this.refs["http://json-schema.org/schema"]=xl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(xl)?xl:void 0)}};qe.Ajv=rs;_g.exports=qe=rs;_g.exports.Ajv=rs;Object.defineProperty(qe,"__esModule",{value:!0});qe.default=rs;var Hq=wi();Object.defineProperty(qe,"KeywordCxt",{enumerable:!0,get:function(){return Hq.KeywordCxt}});var ns=me();Object.defineProperty(qe,"_",{enumerable:!0,get:function(){return ns._}});Object.defineProperty(qe,"str",{enumerable:!0,get:function(){return ns.str}});Object.defineProperty(qe,"stringify",{enumerable:!0,get:function(){return ns.stringify}});Object.defineProperty(qe,"nil",{enumerable:!0,get:function(){return ns.nil}});Object.defineProperty(qe,"Name",{enumerable:!0,get:function(){return ns.Name}});Object.defineProperty(qe,"CodeGen",{enumerable:!0,get:function(){return ns.CodeGen}});var Kq=Qc();Object.defineProperty(qe,"ValidationError",{enumerable:!0,get:function(){return Kq.default}});var Wq=_i();Object.defineProperty(qe,"MissingRefError",{enumerable:!0,get:function(){return Wq.default}})});var KT=B(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.formatNames=Er.fastFormats=Er.fullFormats=void 0;function Rr(t,e){return{validate:t,compare:e}}Er.fullFormats={date:Rr(BT,$g),time:Rr(xg(!0),Tg),"date-time":Rr(UT(!0),VT),"iso-time":Rr(xg(),ZT),"iso-date-time":Rr(UT(),HT),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:eF,"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:aF,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:tF,int32:{type:"number",validate:oF},int64:{type:"number",validate:sF},float:{type:"number",validate:FT},double:{type:"number",validate:FT},password:!0,binary:!0};Er.fastFormats={...Er.fullFormats,date:Rr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,$g),time:Rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Tg),"date-time":Rr(/^\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,VT),"iso-time":Rr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,ZT),"iso-date-time":Rr(/^\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,HT),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};Er.formatNames=Object.keys(Er.fullFormats);function Gq(t){return t%4===0&&(t%100!==0||t%400===0)}var Jq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Yq=[0,31,28,31,30,31,30,31,31,30,31,30,31];function BT(t){let e=Jq.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&&Gq(r)?29:Yq[n])}function $g(t,e){if(t&&e)return t>e?1:t<e?-1:0}var kg=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function xg(t){return function(r){let n=kg.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 Tg(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 ZT(t,e){if(!(t&&e))return;let r=kg.exec(t),n=kg.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 Sg=/t|\s/i;function UT(t){let e=xg(t);return function(n){let o=n.split(Sg);return o.length===2&&BT(o[0])&&e(o[1])}}function VT(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function HT(t,e){if(!(t&&e))return;let[r,n]=t.split(Sg),[o,s]=e.split(Sg),i=$g(r,o);if(i!==void 0)return i||Tg(n,s)}var Xq=/\/|:/,Qq=/^(?:[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 eF(t){return Xq.test(t)&&Qq.test(t)}var qT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function tF(t){return qT.lastIndex=0,qT.test(t)}var rF=-(2**31),nF=2**31-1;function oF(t){return Number.isInteger(t)&&t<=nF&&t>=rF}function sF(t){return Number.isInteger(t)}function FT(){return!0}var iF=/[^\\]\\Z/;function aF(t){if(iF.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var WT=B(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.formatLimitDefinition=void 0;var cF=vg(),mr=me(),yn=mr.operators,Sl={formatMaximum:{okStr:"<=",ok:yn.LTE,fail:yn.GT},formatMinimum:{okStr:">=",ok:yn.GTE,fail:yn.LT},formatExclusiveMaximum:{okStr:"<",ok:yn.LT,fail:yn.GTE},formatExclusiveMinimum:{okStr:">",ok:yn.GT,fail:yn.LTE}},lF={message:({keyword:t,schemaCode:e})=>(0,mr.str)`should be ${Sl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,mr._)`{comparison: ${Sl[t].okStr}, limit: ${e}}`};os.formatLimitDefinition={keyword:Object.keys(Sl),type:"string",schemaType:"string",$data:!0,error:lF,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 cF.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}),f=e.const("fmt",(0,mr._)`${w}[${c.schemaCode}]`);t.fail$data((0,mr.or)((0,mr._)`typeof ${f} != "object"`,(0,mr._)`${f} instanceof RegExp`,(0,mr._)`typeof ${f}.compare != "function"`,p(f)))}function u(){let w=c.schema,f=a.formats[w];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${w}" does not define "compare" function`);let m=e.scopeValue("formats",{key:w,ref:f,code:i.code.formats?(0,mr._)`${i.code.formats}${(0,mr.getProperty)(w)}`:void 0});t.fail$data(p(m))}function p(w){return(0,mr._)`${w}.compare(${r}, ${n}) ${Sl[o].fail} 0`}},dependencies:["format"]};var uF=t=>(t.addKeyword(os.formatLimitDefinition),t);os.default=uF});var XT=B((Li,YT)=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});var ss=KT(),dF=WT(),Rg=me(),GT=new Rg.Name("fullFormats"),pF=new Rg.Name("fastFormats"),Eg=(t,e={keywords:!0})=>{if(Array.isArray(e))return JT(t,e,ss.fullFormats,GT),t;let[r,n]=e.mode==="fast"?[ss.fastFormats,pF]:[ss.fullFormats,GT],o=e.formats||ss.formatNames;return JT(t,o,r,n),e.keywords&&(0,dF.default)(t),t};Eg.get=(t,e="full")=>{let n=(e==="fast"?ss.fastFormats:ss.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function JT(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Rg._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}YT.exports=Li=Eg;Object.defineProperty(Li,"__esModule",{value:!0});Li.default=Eg});function hF(){let t=new QT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,eR.default)(t),t}var QT,eR,$l,tR=L(()=>{QT=Ml(vg(),1),eR=Ml(XT(),1);$l=class{constructor(e){this._ajv=e??hF()}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 Tl,rR=L(()=>{Fo();Tl=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},oi,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},qo,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 nR(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 oR(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 sR=L(()=>{});var Rl,iR=L(()=>{Yx();Fo();tR();Hs();rR();sR();Rl=class extends Uc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ni.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 $l,this.setRequestHandler(jh,n=>this._oninitialize(n)),this.setNotificationHandler(zh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Zh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ni.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Tl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Jx(this._capabilities,e)}setRequestHandler(e,r){let o=sn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=jo(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=on(Uo,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new G(Q.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,w=await Promise.resolve(r(c,l));if(p.task){let m=on(Do,w);if(!m.success){let b=m.error instanceof Error?m.error.message:String(m.error);throw new G(Q.InvalidParams,`Invalid task creation result: ${b}`)}return m.data}let f=on(Ec,w);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new G(Q.InvalidParams,`Invalid tools/call result: ${m}`)}return f.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){oR(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&nR(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:Jk.includes(r)?r:Ch,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"},pc)}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},Vh,r):this.request({method:"sampling/createMessage",params:e},oi,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},qo,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},qo,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(Q.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof G?i:new G(Q.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},Hh,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 Pg(t){return!!t&&typeof t=="object"&&cR in t}function lR(t){return t[cR]?.complete}var cR,aR,uR=L(()=>{cR=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(aR||(aR={}))});var dR=L(()=>{});function fF(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"),!mF.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 gF(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 Ag(t){let e=fF(t);return gF(t,e.warnings),e.isValid}var mF,pR=L(()=>{mF=/^[A-Za-z0-9._-]{1,128}$/});var El,hR=L(()=>{El=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 yF(t,e){let r=0,n=[t];for(;n.length>0;){let o=n.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let s of o){if(++r>e)return r;s!==null&&typeof s=="object"&&n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>e)return r;let i=o[s];i!==null&&typeof i=="object"&&n.push(i)}}return r}function bF(t){if(!(t===void 0||t===1/0)){if(typeof t!="number"||Number.isNaN(t)||t<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(t)}`);return t}}function gR(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function yR(t){return"_def"in t||"_zod"in t||gR(t)}function Cg(t){return typeof t!="object"||t===null||yR(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(gR)}function mR(t){if(t){if(Cg(t))return Kn(t);if(!yR(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function _F(t){let e=sn(t);return e?Object.entries(e).map(([r,n])=>{let o=vk(n),s=kk(n);return{name:r,description:o,required:!s}}):[]}function bn(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=jo(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function fR(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Pl,wF,ji,bR=L(()=>{iR();Hs();Pm();Fo();uR();dR();pR();hR();zn();Pl=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 Rl(e,r),this._maxToolInputElements=bF(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new El(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(bn(Rc)),this.server.assertCanSetRequestHandler(bn(Uo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Rc,()=>({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=Lo(r.inputSchema);return o?Tm(o,{strictUnions:!0,pipeStrategy:"input"}):wF})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Lo(r.outputSchema);o&&(n.outputSchema=Tm(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Uo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new G(Q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new G(Q.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(Q.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new G(Q.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===Q.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(this._maxToolInputElements!==void 0&&yF(r,this._maxToolInputElements)>this._maxToolInputElements)throw new G(Q.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=Lo(e.inputSchema)??e.inputSchema,i=await sc(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",c=ic(a);throw new G(Q.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(Q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Lo(e.outputSchema),s=await sc(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ic(i);throw new G(Q.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(Q.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(bn(Pc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Pc,async e=>{switch(e.params.ref.type){case"ref/prompt":return px(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return hx(e),this.handleResourceCompletion(e,e.params.ref);default:throw new G(Q.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(Q.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new G(Q.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ji;let s=sn(n.argsSchema)?.[e.params.argument.name];if(!Pg(s))return ji;let i=lR(s);if(!i)return ji;let a=await i(e.params.argument.value,e.params.context);return fR(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 ji;throw new G(Q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ji;let s=await o(e.params.argument.value,e.params.context);return fR(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(bn(kc)),this.server.assertCanSetRequestHandler(bn(xc)),this.server.assertCanSetRequestHandler(bn(Sc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(kc,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(xc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Sc,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new G(Q.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(Q.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(bn($c)),this.server.assertCanSetRequestHandler(bn(Tc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($c,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?_F(r.argsSchema):void 0}))})),this.server.setRequestHandler(Tc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new G(Q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new G(Q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Lo(n.argsSchema),s=await sc(o,e.params.arguments??{});if(!s.success){let c="error"in s?s.error:"Unknown error",l=ic(c);throw new G(Q.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:Kn(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=Kn(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 $t?c._def?.innerType:c;return Pg(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){Ag(e);let u={title:r,description:n,inputSchema:mR(o),outputSchema:mR(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"&&Ag(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=Kn(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Kn(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(Cg(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Cg(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()}},wF={type:"object",properties:{}};ji={completion:{values:[],hasMore:!1}}});function kF(t){return ox.parse(JSON.parse(t))}function wR(t){return JSON.stringify(t)+`
2522
+ `}var vF,Al,_R=L(()=>{Fo();vF=10*1024*1024,Al=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??vF}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(`
2523
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),kF(r)}clear(){this._buffer=void 0}}});import vR from"node:process";var Cl,kR=L(()=>{_R();Cl=class{constructor(e=vR.stdin,r=vR.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 Al({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=wR(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var xR,SR=L(()=>{xR=[]});var OR={};ls(OR,{AUTHORING_MCP_SERVER_NAME:()=>ER,AUTHORING_MCP_SERVER_VERSION:()=>PR,AUTHORING_RESOURCES:()=>PF,AUTHORING_TOOLS:()=>EF,AUTHORING_TOOLS_PUBLIC:()=>IR,buildAuthoringMcpServer:()=>CR,resolveSamplesDir:()=>AR,runAuthoringMcpServer:()=>AF});import{promises as xF}from"node:fs";import{isAbsolute as SF,resolve as Il,sep as $F}from"node:path";function RR(){return TR??=import("../mcp/grounding.js").then(e=>e,()=>null),TR}function AR(t,e){if(e===void 0)return Il(process.cwd(),t??"samples");let r=Il(e);if(t===void 0)return r;if(SF(t))return null;let n=Il(r,t);return n===r||n.startsWith(r+$F)?n:null}function Fe(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function RF(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 CR(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let f=await nr(t.baseUrl);if(!f)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:f.baseUrl,token:f.token}}let r=t.grounding??{},n=await RR(),o=null;if(n)try{let f=await e();o={surface:"mcp-authoring",baseUrl:f.baseUrl,token:f.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(f=>({id:f.id,record_type:f.record_type,intent:f.intent}))}catch{c=[]}}let l=o?await RF(o,r):null,u=new Pl({name:ER,version:PR},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(f=>f.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let f=o;for(let m of a)u.registerPrompt(m.id,{title:m.name,description:m.description},async()=>{let b=await n.getMcpPromptSkill(f,m.id,r);if(!b)throw new Error(`unknown prompt: ${m.id}`);return{description:b.description,messages:[{role:"user",content:{type:"text",text:(b.prompts??[]).join(`
2493
2524
 
2494
- `)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:f,token:m}=await e(),b=await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${m}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog fetch failed: ${b.status}`);return Fe(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:P.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:P.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:f,source:m})=>{let{baseUrl:b,token:$}=await e(),R=m?`?source=${encodeURIComponent(m)}`:"",A=await fetch(`${b}/v1/catalog/records/${encodeURIComponent(f)}${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(A.status===404)throw new Error(`unknown record type "${f}" \u2014 list them with catalog_get.`);if(!A.ok)throw new Error(`record anatomy fetch failed: ${A.status}`);return Fe(await A.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:P.array(P.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:P.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:f,source:m})=>{let{baseUrl:b,token:$}=await e(),R=new URLSearchParams({types:f.join(",")});m&&R.set("source",m);let A=await fetch(`${b}/v1/catalog/columns?${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(A.status===404)throw new Error(`none of those record types resolved: ${f.join(", ")} \u2014 list them with catalog_get.`);if(!A.ok)throw new Error(`common columns fetch failed: ${A.status}`);return Fe(await A.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:f,token:m}=await e(),b=await fetch(`${f}/v1/catalog/census`,{headers:{Authorization:`Bearer ${m}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog census failed: ${b.status}`);return Fe(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:P.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:P.enum(SR).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:P.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:f,kind:m,limit:b})=>{let{baseUrl:$,token:R}=await e(),A=new URLSearchParams({q:f});m&&A.set("kind",m),b!==void 0&&A.set("limit",String(b));let O=await fetch(`${$}/v1/catalog/objects?${A}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!O.ok)throw new Error(`catalog object search failed: ${O.status}`);return Fe(await O.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:P.enum(SR),externalId:P.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:f,externalId:m})=>{let{baseUrl:b,token:$}=await e(),R=await fetch(`${b}/v1/catalog/objects/${encodeURIComponent(f)}/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(R.status===404)throw new Error(`unknown object ${f}:${m} \u2014 find it with search_catalog.`);if(!R.ok)throw new Error(`catalog object fetch failed: ${R.status}`);return Fe(await R.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:P.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:P.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:f,limit:m})=>{let{baseUrl:b,token:$}=await e(),R=new URLSearchParams({q:f});m!==void 0&&R.set("limit",String(m));let A=await fetch(`${b}/v1/kb/search?${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!A.ok)throw new Error(`kb search failed: ${A.status}`);return Fe(await A.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:P.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:f})=>{let{baseUrl:m,token:b}=await e(),$=await fetch(`${m}/v1/kb/document/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return Fe(await $.json())}),u.registerTool("search_turbobase_docs",{title:"Search Turbobase's documentation",description:'Search Turbobase\'s own published documentation \u2014 the product manual the instance you are connected to shipped with: hooks, conduits, apps, the source sync, the CLI, the REST surface. Route questions about the PLATFORM here ("how do I read the mirror from an app", "what does a hook receive"), as opposed to search_documentation, which searches the TENANT\'s own processes and policies. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_turbobase_doc for the whole page. The answer names the release the pages came from.',inputSchema:{query:P.string().describe('Words or a phrase, e.g. "writing hooks".'),limit:P.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:f,limit:m})=>{let{baseUrl:b,token:$}=await e(),R=new URLSearchParams({q:f});m!==void 0&&R.set("limit",String(m));let A=await fetch(`${b}/v1/catalog/docs/search?${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!A.ok)throw new Error(`turbobase docs search failed: ${A.status}`);return Fe(await A.json())}),u.registerTool("read_turbobase_doc",{title:"Read a page of Turbobase's documentation",description:"Read one page of Turbobase's own published documentation in full by its slug (from a search_turbobase_docs hit). Returns {found, slug, title, body_markdown, currentVersion}. A slug that is not one of our pages comes back as found:false rather than as an error. Distinct from read_document, which reads a page of the TENANT's own knowledge base.",inputSchema:{slug:P.string().describe("The page slug, e.g. one returned by search_turbobase_docs.")}},async({slug:f})=>{let{baseUrl:m,token:b}=await e(),$=await fetch(`${m}/v1/catalog/docs/document/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`turbobase doc fetch failed: ${$.status}`);return Fe(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:P.boolean().optional()}},async({recordsOnly:f})=>{let{baseUrl:m,token:b}=await e();return{content:[{type:"text",text:await Dn({baseUrl:m,token:b,recordsOnly:f})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:P.string(),event:P.string().optional(),template:P.enum(["require-field","enforce-format","blank"]).optional(),field:P.string().optional(),regex:P.string().optional(),source:P.string().optional(),id:P.string().optional()}},async f=>{let m=_r("hook",{recordType:f.recordType,event:f.event,template:f.template,field:f.field,regex:f.regex,source:f.source,id:f.id});return Fe({path:m.relativePath,content:m.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:P.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:P.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:P.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:P.string().optional().describe("Target record type (defaults to the trigger record type)."),event:P.enum(bo).optional().describe("Conduit lifecycle event (default after_canonicalize_inbound)."),id:P.string().optional()}},async f=>{let m=_r("conduit",{recordType:f.recordType,source:f.source,to:f.to,toRecordType:f.toRecordType,event:f.event,id:f.id});return Fe({path:m.relativePath,content:m.content})}),u.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:P.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:P.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:P.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:P.string().optional()}},async f=>{let m=_r("process",{recordType:f.recordType,then:f.then,onFailure:f.onFailure,id:f.id});return Fe({path:m.relativePath,content:m.content})}),u.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:P.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:P.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:P.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:P.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:P.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:P.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:P.array(P.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async f=>{let{baseUrl:m,token:b}=await e(),$=new K({baseUrl:m,token:b});return Fe(await $.authorConduit({intent:f.intent,from:{source:f.fromSource,recordType:f.fromRecordType},to:{source:f.toSource,recordType:f.toRecordType},...f.intentId?{intentId:f.intentId}:{},...f.columns?.length?{columns:f.columns}:{}}))}),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:P.string().describe("The extension TS source."),samplesDir:P.string().optional().describe('Samples directory (default "samples").')}},async({source:f,samplesDir:m})=>{let b=PR(m,t.samplesRoot);if(b===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:$F})}],isError:!0};let $;try{$=await _s(b)}catch(O){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw O}let R=await ya(f,$.map(O=>O.fixture)),A=R.filter(O=>!O.pass).length;return Fe({total:R.length,passed:R.length-A,results:R})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:P.string(),recordType:P.string(),event:P.string(),source:P.string().describe('Adapter id or "standalone".'),sourceCode:P.string().describe("The verbatim extension TS."),extensionKind:P.string().optional()}},async f=>{let{baseUrl:m,token:b}=await e(),R=await new K({baseUrl:m,token:b}).deploy({id:f.id,recordType:f.recordType,event:f.event,source:f.source,sourceCode:f.sourceCode,extensionKind:f.extensionKind});return Fe(R)}),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:P.string(),limit:P.number().int().positive().optional()}},async({id:f,limit:m})=>{let{baseUrl:b,token:$}=await e(),R=new K({baseUrl:b,token:$});return Fe({id:f,logs:await R.logs(f,m)})}),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:f,token:m}=await e(),b=new K({baseUrl:f,token:m});return Fe(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:P.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:P.string().optional().describe("Display name (defaults to the slug)."),description:P.string().optional().describe("Short description.")}},async({slug:f,name:m,description:b})=>{let{baseUrl:$,token:R}=await e(),A=new K({baseUrl:$,token:R});return Fe(await A.appsCreate({slug:f,name:m,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:P.string().describe("App slug or id.")}},async({app:f})=>{let{baseUrl:m,token:b}=await e(),$=new K({baseUrl:m,token:b});return Fe(await $.appsPull(f))}),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:P.string().describe("App slug or id."),files:P.record(P.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:P.string().optional().describe("Short note stored with the revision.")}},async({app:f,files:m,note:b})=>{let{baseUrl:$,token:R}=await e(),A=new K({baseUrl:$,token:R});return Fe(await A.appsPush(f,m,{note:b}))});let p=P.object({name:P.string().describe("Field name (lowercase identifier)."),type:P.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:P.boolean().optional()}),w=P.object({slug:P.string().describe("Table slug; the physical table is cr_<slug>."),displayName:P.string().optional(),fields:P.array(p).describe("At least one field."),rowLevelOwner:P.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:f,token:m}=await e(),b=new K({baseUrl:f,token:m});return Fe(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:P.array(w),claimedBy:P.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:m})=>{let{baseUrl:b,token:$}=await e(),R=new K({baseUrl:b,token:$});return Fe(await R.tablesPlan({tables:f,claimedBy:m}))}),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:P.array(w),claimedBy:P.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:m})=>{let{baseUrl:b,token:$}=await e(),R=new K({baseUrl:b,token:$});return Fe(await R.tablesApply({tables:f,claimedBy:m}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async f=>{let{baseUrl:m,token:b}=await e(),R=await(await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}})).text();return{contents:[{uri:f.href,mimeType:"application/json",text:R}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async f=>{let{baseUrl:m,token:b}=await e(),$=await Dn({baseUrl:m,token:b});return{contents:[{uri:f.href,mimeType:"text/plain",text:$}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async f=>{let m=Il(process.cwd(),"samples"),b=[];try{b=(await xF.readdir(m)).filter(R=>R.endsWith(".json"))}catch{b=[]}let $=await _s(m);return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({files:b,samples:$.map(R=>R.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 f=>{let m=await TR(),b=[];if(m){let{baseUrl:$,token:R}=await e();b=await m.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:R},r)}return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({recipes:b})}]}}),u}async function PF(t={}){let e=await AR(t),r=new Cl;await e.connect(r)}var SR,$R,RR,ER,$F,CR,RF,EF,OR=L(()=>{yR();vR();zn();fu();ys();or();Tu();ka();kR();SR=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];RR="turbobase-authoring",ER="0.1.0";$F="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";CR=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_turbobase_docs","read_turbobase_doc","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],RF=[...CR,...xR],EF=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as jg}from"node:child_process";import{promises as be}from"node:fs";import{homedir as AF}from"node:os";import{basename as jR,dirname as Zr,join as jt,relative as Nl,resolve as fe,sep as Lg}from"node:path";var ny=Dl(ry(),1),{program:eB,createCommand:tB,createArgument:rB,createOption:nB,CommanderError:oB,InvalidArgumentError:sB,InvalidOptionArgumentError:iB,Command:oy,Argument:aB,Option:cB,Help:lB}=ny.default;fu();ys();or();Tu();ga();import{promises as cb}from"node:fs";var kP=/^[a-z][a-z0-9_]+$/;function nb(t,e){if(typeof t!="string"||!kP.test(t))throw new Error(`${e} ${JSON.stringify(t)} must match /^[a-z][a-z0-9_]+$/ (NS scriptid form). This restriction is what lets reconcile safely splice it as a SQL identifier; refusing to emit DDL.`);return t}var SP="customrecord",$P="customlist";function TP(t){return t.startsWith("customrecord_")?t.slice(13):t}function RP(t){return t.startsWith("customlist_")?t.slice(11):t}function EP(t){return nb(t,"custom_record scriptId"),`cr_${TP(t)}`}function PP(t){return nb(t,"custom_list scriptId"),`cl_${RP(t)}`}function ob(t){return t.startsWith(SP)?EP(t):t.startsWith($P)?PP(t):null}var AP={salesOrder:{table:"order"},invoice:{table:"invoice"},itemFulfillment:{table:"order_fulfillment"},customerPayment:{table:"customer_payment"},cashSale:{table:"cash_sale"},cashRefund:{table:"cash_refund"},opportunity:{table:"opportunity"},estimate:{table:"estimate"},customerDeposit:{table:"customer_deposit"},creditMemo:{table:"credit_memo"},customer:{table:"entity",typeColumn:"entity_type",typeValue:"customer"},vendor:{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},contact:{table:"entity",typeColumn:"entity_type",typeValue:"contact"},employee:{table:"entity",typeColumn:"entity_type",typeValue:"employee"},partner:{table:"entity",typeColumn:"entity_type",typeValue:"partner"},inventoryItem:{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},serviceSaleItem:{table:"item",typeColumn:"item_type",typeValue:"serviceSaleItem"},nonInventoryResaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventoryResaleItem"},kitItem:{table:"item",typeColumn:"item_type",typeValue:"kitItem"},assemblyItem:{table:"item",typeColumn:"item_type",typeValue:"assemblyItem"},lotNumberedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedInventoryItem"},serializedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"serializedInventoryItem"},lotNumberedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedAssemblyItem"},serializedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"serializedAssemblyItem"},nonInventorySaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventorySaleItem"},otherChargeSaleItem:{table:"item",typeColumn:"item_type",typeValue:"otherChargeSaleItem"},discountItem:{table:"item",typeColumn:"item_type",typeValue:"discountItem"},location:{table:"segment_value",typeColumn:"canonical_segment",typeValue:"location",capabilityTable:"location"},department:{table:"segment_value",typeColumn:"canonical_segment",typeValue:"department",capabilityTable:"department"},classification:{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class",capabilityTable:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_entry"},expenseReport:{table:"expense_report"},itemReceipt:{table:"item_receipt"},vendorReturnAuthorization:{table:"vendor_return_authorization"},transferOrder:{table:"transfer_order"},check:{table:"check"},customerRefund:{table:"customer_refund"},project:{table:"project"},projectTask:{table:"work_item",typeColumn:"item_type",typeValue:"project_task"},supportCase:{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},caseMessage:{table:"activity",typeColumn:"activity_type",typeValue:"case_message_outgoing",alsoAddresses:["case_message_incoming"]},shippingItem:{table:"shipping_item"},unitsType:{table:"units_type"},returnAuthorization:{table:"return_authorization"},inventoryAdjustment:{table:"inventory_adjustment"},vendorCredit:{table:"vendor_credit"},deposit:{table:"deposit"},account:{table:"account"},channel_message:{table:"activity",typeColumn:"activity_type",typeValue:"message"},social_post:{table:"activity",typeColumn:"activity_type",typeValue:"social_post"},reaction:{table:"reaction"},esignSubmission:{table:"esign_submission"},esignSubmitter:{table:"esign_submitter"},workflow_run:{table:"automation_run"},printer:{table:"printer"},printJob:{table:"print_job"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},creditCardCharge:{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"charge"},creditCardRefund:{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"refund"},request:{table:"request"}};function sb(t,e){let r=e?IP[`${e}:${t}`]:void 0;if(r)return r;let n=AP[t];if(n)return n;let o=ob(t);return o?{table:o}:void 0}var CP={accountingPeriod:"accounting_period",printer:"printer"};var IP={...Object.fromEntries(Object.entries(CP).map(([t,e])=>[`standalone:${t}`,{table:e}])),"google_workspace:doc":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"google_workspace:email":{table:"memory_document",typeColumn:"kind",typeValue:"email"},"google_workspace:file":{table:"memory_document",typeColumn:"kind",typeValue:"file"},"google_workspace:sheet":{table:"memory_document",typeColumn:"kind",typeValue:"sheet"},"google_workspace:slide":{table:"memory_document",typeColumn:"kind",typeValue:"slide"},"salesforce:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"salesforce:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"salesforce:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"salesforce:user":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"salesforce:queue":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"salesforce:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"salesforce:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"intercom:admin":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:owner":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"intercom:ticket":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"github:issue":{table:"work_item",typeColumn:"item_type",typeValue:"issue"},"github:pull_request":{table:"work_item",typeColumn:"item_type",typeValue:"pull_request"},"github:comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"zendesk:organization":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"getsales:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"xero:supplier":{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},"xero:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"quickbooks:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"billdotcom:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"workday:organization":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"department"},"zoho_crm:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"zoho_crm:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"zoho_crm:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"slack:user":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"slack:channel":{table:"channel"},"slack:reaction":{table:"reaction"},"quickbooks:bill":{table:"vendor_bill"},"quickbooks:payment":{table:"customer_payment"},"quickbooks:billPayment":{table:"vendor_payment"},"quickbooks:item":{table:"item"},"zoho_crm:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"zoho_crm:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"zoho_crm:product":{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},"xero:bill":{table:"vendor_bill"},"xero:billPayment":{table:"vendor_payment"},"xero:creditNote":{table:"credit_memo"},"xero:item":{table:"item"},"xero:manualJournal":{table:"journal_entry"},"xero:payment":{table:"customer_payment"},"xero:receiveMoney":{table:"deposit"},"xero:spendMoney":{table:"check"},"xero:supplierCreditNote":{table:"vendor_credit"},"github:project":{table:"board",typeColumn:"kind",typeValue:"project"},"zendesk:ticket_comment":{table:"activity",typeColumn:"activity_type",typeValue:"ticket_comment"},"intercom:conversation_part":{table:"activity",typeColumn:"activity_type",typeValue:"message"},"notion:notion_comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"jira:board":{table:"board",typeColumn:"kind",typeValue:"board"},"jira:project":{table:"board",typeColumn:"kind",typeValue:"project"},"asana:asanaProject":{table:"board",typeColumn:"kind",typeValue:"project"},"asana:asanaSection":{table:"board_field"},"workday:worker":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"notion:notion_document":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"ramp:card_transaction":{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"charge"},"azure_blob:file":{table:"source_file"},"whatsapp:contact":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"whatsapp:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"whatsapp:message":{table:"activity",typeColumn:"activity_type",typeValue:"message"},"whatsapp:phoneNumber":{table:"whatsapp_phone_number"},"whatsapp:messageTemplate":{table:"whatsapp_message_template"},"slack:file":{table:"source_file"}};function ib(t,e){let r=sb(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function ab(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=ib(t,n),i=ib(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var lb=4;function Ru(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=vo(t,"id"),r=vo(t,"on"),n=vo(t,"source"),o=vo(t,"recordType"),s=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let u=vo(l[1]??"","source"),p=vo(l[1]??"","recordType");u&&p&&s.push({source:u,recordType:p})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t),c=/^[ \t]*reads\s*:\s*\[\s*\{/m.test(t);if(!e||!n||!o||!i)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.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):lb,declaresReads:c}}function vo(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function OP(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??{}}}function NP(t,e){let r=t.queryRows;if(!(!r||!Object.prototype.hasOwnProperty.call(r,e)))return r[e]}async function ub(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=Ru(t)}catch(p){return{fixtureName:o,conduit:jP(),guards:s,whenPassed:!1,atlasResolutions:[],queryReads:[],wouldWriteBindings:[],targets:[],logs:[],error:p instanceof Error?p.message:String(p)}}let a=OP(e),c=Object.entries(e.atlasLinks??{}).map(([p,w])=>({key:p,resolved:w})),l=[],u=i.declaresReads?async p=>{let w=NP(e,p);return l.push({query:p,served:w!==void 0,rowCount:w?.length??0}),w??[]}:void 0;try{for(let[O,q]of Object.entries(e.queryRows??{}))if(!Array.isArray(q))throw new Error(`fixture queryRows['${O}'] must be an array of rows \u2014 ctx.query answers a row list, and a ${q===null?"null":typeof q} reaches the conduit as one`);let p=await fa(t,{resolveDir:n.resolveDir}),f=!!(await ws(p,a,{member:"when",timeoutMs:ma,query:u})).whenResult;s.push({name:"from.when",status:f?"passed":"failed",detail:f?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let m=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${m} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.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)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!f)return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:c,queryReads:l,wouldWriteBindings:[],targets:[],logs:[]};let b=[],$=[],R=[];for(let O=0;O<i.targets.length;O+=1){let q=i.targets[O],Y=await ws(p,{...a,materialized:R.map(Hr=>({...Hr}))},{member:"transform",stepIndex:O,timeoutMs:ma,query:u});b.push(...Y.effects.logs);let De=Y.effects.result;if(!De||typeof De!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${O+1})`:""} returned no result (expected { patch, createdFrom? })`);let Qe=De,zt=ab(i.fromRecordType,q.recordType,{fromSource:i.fromSource,toSource:q.source}),{wouldWriteBindings:Vr,masterAction:fr}=LP(i,q,zt,e);$.push({to:q,transformResult:Qe,applyBranch:zt,wouldWriteBindings:Vr,masterAction:fr}),R.push({source:q.source,recordType:q.recordType,masterTable:`<${q.recordType} master, dry-run>`,masterRowId:`<dry-run target ${O+1}>`,externalId:null})}let A=$[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:c,queryReads:l,transformResult:A.transformResult,applyBranch:A.applyBranch,wouldWriteBindings:A.wouldWriteBindings,masterAction:A.masterAction,targets:$,logs:b}}catch(p){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:c,queryReads:l,wouldWriteBindings:[],targets:[],logs:[],error:p instanceof Error?p.message:String(p)}}}function LP(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function jP(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:lb,declaresReads:!1}}async function db(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 pb(t){let e=await cb.readFile(t,"utf8");return JSON.parse(e)}function hb(t){return cb.readFile(t,"utf8")}function mb(t,e){let r=t.conduit,n=`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`,o=t.targets.length>1;if(!e){if(t.error)return n;if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(o){let c=t.targets.reduce((l,u)=>l+u.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${c} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}if(t.error&&!r.id)return n;let s=[];s.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),s.push(`conduit: ${r.id}`);let i=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(c=>`${c.source}.${c.recordType}`).join(" \u2192 ");s.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${i}${r.on?` on=${r.on}`:""}`),s.push(""),s.push("guards (dispatch order):"),t.guards.length===0&&s.push(" (none ran \u2014 the replay stopped before dispatch)");for(let c of t.guards){let l=c.status==="passed"?"\u2713":c.status==="failed"?"\u2717":"\u2298";s.push(` ${l} ${c.name} [${c.status}] \u2014 ${c.detail}`)}if(s.push(""),s.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let c of t.atlasResolutions)s.push(` ${c.key} \u2192 ${c.resolved===null?"null (no Atlas link \u2014 noted)":c.resolved}`);if(s.push(""),s.push("ctx.query (declared reads):"),!r.declaresReads)s.push(" (no `reads` declared \u2014 ctx.query is not defined in the isolate, exactly as in production)");else if(t.queryReads.length===0)s.push(" (declared, but this replay made no read)");else for(let c of t.queryReads)s.push(` ${c.query} \u2192 ${c.served?"served":"not served by the fixture"}, ${c.rowCount} row(s)`);if(t.error)return s.push(""),s.push(`ERROR \u2014 ${t.error}`),s.join(`
2525
+ `)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:f,token:m}=await e(),b=await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${m}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog fetch failed: ${b.status}`);return Fe(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:P.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:P.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:f,source:m})=>{let{baseUrl:b,token:$}=await e(),R=m?`?source=${encodeURIComponent(m)}`:"",A=await fetch(`${b}/v1/catalog/records/${encodeURIComponent(f)}${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(A.status===404)throw new Error(`unknown record type "${f}" \u2014 list them with catalog_get.`);if(!A.ok)throw new Error(`record anatomy fetch failed: ${A.status}`);return Fe(await A.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:P.array(P.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:P.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:f,source:m})=>{let{baseUrl:b,token:$}=await e(),R=new URLSearchParams({types:f.join(",")});m&&R.set("source",m);let A=await fetch(`${b}/v1/catalog/columns?${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(A.status===404)throw new Error(`none of those record types resolved: ${f.join(", ")} \u2014 list them with catalog_get.`);if(!A.ok)throw new Error(`common columns fetch failed: ${A.status}`);return Fe(await A.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:f,token:m}=await e(),b=await fetch(`${f}/v1/catalog/census`,{headers:{Authorization:`Bearer ${m}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog census failed: ${b.status}`);return Fe(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:P.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:P.enum($R).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:P.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:f,kind:m,limit:b})=>{let{baseUrl:$,token:R}=await e(),A=new URLSearchParams({q:f});m&&A.set("kind",m),b!==void 0&&A.set("limit",String(b));let O=await fetch(`${$}/v1/catalog/objects?${A}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!O.ok)throw new Error(`catalog object search failed: ${O.status}`);return Fe(await O.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:P.enum($R),externalId:P.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:f,externalId:m})=>{let{baseUrl:b,token:$}=await e(),R=await fetch(`${b}/v1/catalog/objects/${encodeURIComponent(f)}/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(R.status===404)throw new Error(`unknown object ${f}:${m} \u2014 find it with search_catalog.`);if(!R.ok)throw new Error(`catalog object fetch failed: ${R.status}`);return Fe(await R.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:P.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:P.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:f,limit:m})=>{let{baseUrl:b,token:$}=await e(),R=new URLSearchParams({q:f});m!==void 0&&R.set("limit",String(m));let A=await fetch(`${b}/v1/kb/search?${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!A.ok)throw new Error(`kb search failed: ${A.status}`);return Fe(await A.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:P.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:f})=>{let{baseUrl:m,token:b}=await e(),$=await fetch(`${m}/v1/kb/document/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return Fe(await $.json())}),u.registerTool("search_turbobase_docs",{title:"Search Turbobase's documentation",description:'Search Turbobase\'s own published documentation \u2014 the product manual the instance you are connected to shipped with: hooks, conduits, apps, the source sync, the CLI, the REST surface. Route questions about the PLATFORM here ("how do I read the mirror from an app", "what does a hook receive"), as opposed to search_documentation, which searches the TENANT\'s own processes and policies. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_turbobase_doc for the whole page. The answer names the release the pages came from.',inputSchema:{query:P.string().describe('Words or a phrase, e.g. "writing hooks".'),limit:P.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:f,limit:m})=>{let{baseUrl:b,token:$}=await e(),R=new URLSearchParams({q:f});m!==void 0&&R.set("limit",String(m));let A=await fetch(`${b}/v1/catalog/docs/search?${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!A.ok)throw new Error(`turbobase docs search failed: ${A.status}`);return Fe(await A.json())}),u.registerTool("read_turbobase_doc",{title:"Read a page of Turbobase's documentation",description:"Read one page of Turbobase's own published documentation in full by its slug (from a search_turbobase_docs hit). Returns {found, slug, title, body_markdown, currentVersion}. A slug that is not one of our pages comes back as found:false rather than as an error. Distinct from read_document, which reads a page of the TENANT's own knowledge base.",inputSchema:{slug:P.string().describe("The page slug, e.g. one returned by search_turbobase_docs.")}},async({slug:f})=>{let{baseUrl:m,token:b}=await e(),$=await fetch(`${m}/v1/catalog/docs/document/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`turbobase doc fetch failed: ${$.status}`);return Fe(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:P.boolean().optional()}},async({recordsOnly:f})=>{let{baseUrl:m,token:b}=await e();return{content:[{type:"text",text:await Dn({baseUrl:m,token:b,recordsOnly:f})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:P.string(),event:P.string().optional(),template:P.enum(["require-field","enforce-format","blank"]).optional(),field:P.string().optional(),regex:P.string().optional(),source:P.string().optional(),id:P.string().optional()}},async f=>{let m=_r("hook",{recordType:f.recordType,event:f.event,template:f.template,field:f.field,regex:f.regex,source:f.source,id:f.id});return Fe({path:m.relativePath,content:m.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:P.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:P.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:P.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:P.string().optional().describe("Target record type (defaults to the trigger record type)."),event:P.enum(yo).optional().describe("Conduit lifecycle event (default after_canonicalize_inbound)."),id:P.string().optional()}},async f=>{let m=_r("conduit",{recordType:f.recordType,source:f.source,to:f.to,toRecordType:f.toRecordType,event:f.event,id:f.id});return Fe({path:m.relativePath,content:m.content})}),u.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:P.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:P.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:P.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:P.string().optional()}},async f=>{let m=_r("process",{recordType:f.recordType,then:f.then,onFailure:f.onFailure,id:f.id});return Fe({path:m.relativePath,content:m.content})}),u.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:P.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:P.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:P.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:P.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:P.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:P.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:P.array(P.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async f=>{let{baseUrl:m,token:b}=await e(),$=new K({baseUrl:m,token:b});return Fe(await $.authorConduit({intent:f.intent,from:{source:f.fromSource,recordType:f.fromRecordType},to:{source:f.toSource,recordType:f.toRecordType},...f.intentId?{intentId:f.intentId}:{},...f.columns?.length?{columns:f.columns}:{}}))}),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:P.string().describe("The extension TS source."),samplesDir:P.string().optional().describe('Samples directory (default "samples").')}},async({source:f,samplesDir:m})=>{let b=AR(m,t.samplesRoot);if(b===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:TF})}],isError:!0};let $;try{$=await _s(b)}catch(O){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw O}let R=await ya(f,$.map(O=>O.fixture)),A=R.filter(O=>!O.pass).length;return Fe({total:R.length,passed:R.length-A,results:R})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:P.string(),recordType:P.string(),event:P.string(),source:P.string().describe('Adapter id or "standalone".'),sourceCode:P.string().describe("The verbatim extension TS."),extensionKind:P.string().optional()}},async f=>{let{baseUrl:m,token:b}=await e(),R=await new K({baseUrl:m,token:b}).deploy({id:f.id,recordType:f.recordType,event:f.event,source:f.source,sourceCode:f.sourceCode,extensionKind:f.extensionKind});return Fe(R)}),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:P.string(),limit:P.number().int().positive().optional()}},async({id:f,limit:m})=>{let{baseUrl:b,token:$}=await e(),R=new K({baseUrl:b,token:$});return Fe({id:f,logs:await R.logs(f,m)})}),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:f,token:m}=await e(),b=new K({baseUrl:f,token:m});return Fe(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:P.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:P.string().optional().describe("Display name (defaults to the slug)."),description:P.string().optional().describe("Short description.")}},async({slug:f,name:m,description:b})=>{let{baseUrl:$,token:R}=await e(),A=new K({baseUrl:$,token:R});return Fe(await A.appsCreate({slug:f,name:m,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:P.string().describe("App slug or id.")}},async({app:f})=>{let{baseUrl:m,token:b}=await e(),$=new K({baseUrl:m,token:b});return Fe(await $.appsPull(f))}),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:P.string().describe("App slug or id."),files:P.record(P.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:P.string().optional().describe("Short note stored with the revision.")}},async({app:f,files:m,note:b})=>{let{baseUrl:$,token:R}=await e(),A=new K({baseUrl:$,token:R});return Fe(await A.appsPush(f,m,{note:b}))});let p=P.object({name:P.string().describe("Field name (lowercase identifier)."),type:P.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:P.boolean().optional()}),w=P.object({slug:P.string().describe("Table slug; the physical table is cr_<slug>."),displayName:P.string().optional(),fields:P.array(p).describe("At least one field."),rowLevelOwner:P.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:f,token:m}=await e(),b=new K({baseUrl:f,token:m});return Fe(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:P.array(w),claimedBy:P.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:m})=>{let{baseUrl:b,token:$}=await e(),R=new K({baseUrl:b,token:$});return Fe(await R.tablesPlan({tables:f,claimedBy:m}))}),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:P.array(w),claimedBy:P.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:m})=>{let{baseUrl:b,token:$}=await e(),R=new K({baseUrl:b,token:$});return Fe(await R.tablesApply({tables:f,claimedBy:m}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async f=>{let{baseUrl:m,token:b}=await e(),R=await(await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}})).text();return{contents:[{uri:f.href,mimeType:"application/json",text:R}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async f=>{let{baseUrl:m,token:b}=await e(),$=await Dn({baseUrl:m,token:b});return{contents:[{uri:f.href,mimeType:"text/plain",text:$}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async f=>{let m=Il(process.cwd(),"samples"),b=[];try{b=(await xF.readdir(m)).filter(R=>R.endsWith(".json"))}catch{b=[]}let $=await _s(m);return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({files:b,samples:$.map(R=>R.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 f=>{let m=await RR(),b=[];if(m){let{baseUrl:$,token:R}=await e();b=await m.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:R},r)}return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({recipes:b})}]}}),u}async function AF(t={}){let e=await CR(t),r=new Cl;await e.connect(r)}var $R,TR,ER,PR,TF,IR,EF,PF,NR=L(()=>{bR();kR();zn();gu();ys();or();Ru();xa();SR();$R=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];ER="turbobase-authoring",PR="0.1.0";TF="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";IR=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_turbobase_docs","read_turbobase_doc","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],EF=[...IR,...xR],PF=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as zg}from"node:child_process";import{promises as be}from"node:fs";import{homedir as CF}from"node:os";import{basename as zR,dirname as Zr,join as jt,relative as Nl,resolve as fe,sep as jg}from"node:path";var oy=Ml(ny(),1),{program:tB,createCommand:rB,createArgument:nB,createOption:oB,CommanderError:sB,InvalidArgumentError:iB,InvalidOptionArgumentError:aB,Command:sy,Argument:cB,Option:lB,Help:uB}=oy.default;gu();ys();or();Ru();ga();import{promises as lb}from"node:fs";var SP=/^[a-z][a-z0-9_]+$/;function ob(t,e){if(typeof t!="string"||!SP.test(t))throw new Error(`${e} ${JSON.stringify(t)} must match /^[a-z][a-z0-9_]+$/ (NS scriptid form). This restriction is what lets reconcile safely splice it as a SQL identifier; refusing to emit DDL.`);return t}var $P="customrecord",TP="customlist";function RP(t){return t.startsWith("customrecord_")?t.slice(13):t}function EP(t){return t.startsWith("customlist_")?t.slice(11):t}function PP(t){return ob(t,"custom_record scriptId"),`cr_${RP(t)}`}function AP(t){return ob(t,"custom_list scriptId"),`cl_${EP(t)}`}function sb(t){return t.startsWith($P)?PP(t):t.startsWith(TP)?AP(t):null}var CP={salesOrder:{table:"order"},invoice:{table:"invoice"},itemFulfillment:{table:"order_fulfillment"},customerPayment:{table:"customer_payment"},cashSale:{table:"cash_sale"},cashRefund:{table:"cash_refund"},opportunity:{table:"opportunity"},estimate:{table:"estimate"},customerDeposit:{table:"customer_deposit"},creditMemo:{table:"credit_memo"},customer:{table:"entity",typeColumn:"entity_type",typeValue:"customer"},vendor:{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},contact:{table:"entity",typeColumn:"entity_type",typeValue:"contact"},employee:{table:"entity",typeColumn:"entity_type",typeValue:"employee"},partner:{table:"entity",typeColumn:"entity_type",typeValue:"partner"},inventoryItem:{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},serviceSaleItem:{table:"item",typeColumn:"item_type",typeValue:"serviceSaleItem"},nonInventoryResaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventoryResaleItem"},kitItem:{table:"item",typeColumn:"item_type",typeValue:"kitItem"},assemblyItem:{table:"item",typeColumn:"item_type",typeValue:"assemblyItem"},lotNumberedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedInventoryItem"},serializedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"serializedInventoryItem"},lotNumberedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedAssemblyItem"},serializedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"serializedAssemblyItem"},nonInventorySaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventorySaleItem"},otherChargeSaleItem:{table:"item",typeColumn:"item_type",typeValue:"otherChargeSaleItem"},discountItem:{table:"item",typeColumn:"item_type",typeValue:"discountItem"},location:{table:"segment_value",typeColumn:"canonical_segment",typeValue:"location",capabilityTable:"location"},department:{table:"segment_value",typeColumn:"canonical_segment",typeValue:"department",capabilityTable:"department"},classification:{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class",capabilityTable:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_entry"},expenseReport:{table:"expense_report"},itemReceipt:{table:"item_receipt"},vendorReturnAuthorization:{table:"vendor_return_authorization"},transferOrder:{table:"transfer_order"},check:{table:"check"},customerRefund:{table:"customer_refund"},project:{table:"project"},projectTask:{table:"work_item",typeColumn:"item_type",typeValue:"project_task"},supportCase:{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},caseMessage:{table:"activity",typeColumn:"activity_type",typeValue:"case_message_outgoing",alsoAddresses:["case_message_incoming"]},shippingItem:{table:"shipping_item"},unitsType:{table:"units_type"},returnAuthorization:{table:"return_authorization"},inventoryAdjustment:{table:"inventory_adjustment"},vendorCredit:{table:"vendor_credit"},deposit:{table:"deposit"},account:{table:"account"},channel_message:{table:"activity",typeColumn:"activity_type",typeValue:"message"},social_post:{table:"activity",typeColumn:"activity_type",typeValue:"social_post"},reaction:{table:"reaction"},esignSubmission:{table:"esign_submission"},esignSubmitter:{table:"esign_submitter"},workflow_run:{table:"automation_run"},printer:{table:"printer"},printJob:{table:"print_job"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},creditCardCharge:{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"charge"},creditCardRefund:{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"refund"},request:{table:"request"}};function ib(t,e){let r=e?OP[`${e}:${t}`]:void 0;if(r)return r;let n=CP[t];if(n)return n;let o=sb(t);return o?{table:o}:void 0}var IP={accountingPeriod:"accounting_period",printer:"printer"};var OP={...Object.fromEntries(Object.entries(IP).map(([t,e])=>[`standalone:${t}`,{table:e}])),"google_workspace:doc":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"google_workspace:email":{table:"memory_document",typeColumn:"kind",typeValue:"email"},"google_workspace:file":{table:"memory_document",typeColumn:"kind",typeValue:"file"},"google_workspace:sheet":{table:"memory_document",typeColumn:"kind",typeValue:"sheet"},"google_workspace:slide":{table:"memory_document",typeColumn:"kind",typeValue:"slide"},"salesforce:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"salesforce:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"salesforce:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"salesforce:user":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"salesforce:queue":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"salesforce:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"salesforce:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"intercom:admin":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:owner":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"intercom:ticket":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"github:issue":{table:"work_item",typeColumn:"item_type",typeValue:"issue"},"github:pull_request":{table:"work_item",typeColumn:"item_type",typeValue:"pull_request"},"github:comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"zendesk:organization":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"getsales:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"xero:supplier":{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},"xero:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"quickbooks:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"billdotcom:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"workday:organization":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"department"},"zoho_crm:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"zoho_crm:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"zoho_crm:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"slack:user":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"slack:channel":{table:"channel"},"slack:reaction":{table:"reaction"},"quickbooks:bill":{table:"vendor_bill"},"quickbooks:payment":{table:"customer_payment"},"quickbooks:billPayment":{table:"vendor_payment"},"quickbooks:item":{table:"item"},"zoho_crm:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"zoho_crm:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"zoho_crm:product":{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},"xero:bill":{table:"vendor_bill"},"xero:billPayment":{table:"vendor_payment"},"xero:creditNote":{table:"credit_memo"},"xero:item":{table:"item"},"xero:manualJournal":{table:"journal_entry"},"xero:payment":{table:"customer_payment"},"xero:receiveMoney":{table:"deposit"},"xero:spendMoney":{table:"check"},"xero:supplierCreditNote":{table:"vendor_credit"},"github:project":{table:"board",typeColumn:"kind",typeValue:"project"},"zendesk:ticket_comment":{table:"activity",typeColumn:"activity_type",typeValue:"ticket_comment"},"intercom:conversation_part":{table:"activity",typeColumn:"activity_type",typeValue:"message"},"notion:notion_comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"jira:board":{table:"board",typeColumn:"kind",typeValue:"board"},"jira:project":{table:"board",typeColumn:"kind",typeValue:"project"},"asana:asanaProject":{table:"board",typeColumn:"kind",typeValue:"project"},"asana:asanaSection":{table:"board_field"},"workday:worker":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"notion:notion_document":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"ramp:card_transaction":{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"charge"},"azure_blob:file":{table:"source_file"},"whatsapp:contact":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"whatsapp:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"whatsapp:message":{table:"activity",typeColumn:"activity_type",typeValue:"message"},"whatsapp:phoneNumber":{table:"whatsapp_phone_number"},"whatsapp:messageTemplate":{table:"whatsapp_message_template"},"slack:file":{table:"source_file"}};function ab(t,e){let r=ib(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function cb(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=ab(t,n),i=ab(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var ub=4;function Eu(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=_o(t,"id"),r=_o(t,"on"),n=_o(t,"source"),o=_o(t,"recordType"),s=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let u=_o(l[1]??"","source"),p=_o(l[1]??"","recordType");u&&p&&s.push({source:u,recordType:p})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t),c=/^[ \t]*reads\s*:\s*\[\s*\{/m.test(t);if(!e||!n||!o||!i)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.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):ub,declaresReads:c}}function _o(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function NP(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??{}}}function LP(t,e){let r=t.queryRows;if(!(!r||!Object.prototype.hasOwnProperty.call(r,e)))return r[e]}async function db(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=Eu(t)}catch(p){return{fixtureName:o,conduit:zP(),guards:s,whenPassed:!1,atlasResolutions:[],queryReads:[],wouldWriteBindings:[],targets:[],logs:[],error:p instanceof Error?p.message:String(p)}}let a=NP(e),c=Object.entries(e.atlasLinks??{}).map(([p,w])=>({key:p,resolved:w})),l=[],u=i.declaresReads?async p=>{let w=LP(e,p);return l.push({query:p,served:w!==void 0,rowCount:w?.length??0}),w??[]}:void 0;try{for(let[O,q]of Object.entries(e.queryRows??{}))if(!Array.isArray(q))throw new Error(`fixture queryRows['${O}'] must be an array of rows \u2014 ctx.query answers a row list, and a ${q===null?"null":typeof q} reaches the conduit as one`);let p=await fa(t,{resolveDir:n.resolveDir}),f=!!(await ws(p,a,{member:"when",timeoutMs:ma,query:u})).whenResult;s.push({name:"from.when",status:f?"passed":"failed",detail:f?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let m=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${m} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.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)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!f)return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:c,queryReads:l,wouldWriteBindings:[],targets:[],logs:[]};let b=[],$=[],R=[];for(let O=0;O<i.targets.length;O+=1){let q=i.targets[O],J=await ws(p,{...a,materialized:R.map(Hr=>({...Hr}))},{member:"transform",stepIndex:O,timeoutMs:ma,query:u});b.push(...J.effects.logs);let De=J.effects.result;if(!De||typeof De!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${O+1})`:""} returned no result (expected { patch, createdFrom? })`);let Qe=De,zt=cb(i.fromRecordType,q.recordType,{fromSource:i.fromSource,toSource:q.source}),{wouldWriteBindings:Vr,masterAction:fr}=jP(i,q,zt,e);$.push({to:q,transformResult:Qe,applyBranch:zt,wouldWriteBindings:Vr,masterAction:fr}),R.push({source:q.source,recordType:q.recordType,masterTable:`<${q.recordType} master, dry-run>`,masterRowId:`<dry-run target ${O+1}>`,externalId:null})}let A=$[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:c,queryReads:l,transformResult:A.transformResult,applyBranch:A.applyBranch,wouldWriteBindings:A.wouldWriteBindings,masterAction:A.masterAction,targets:$,logs:b}}catch(p){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:c,queryReads:l,wouldWriteBindings:[],targets:[],logs:[],error:p instanceof Error?p.message:String(p)}}}function jP(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function zP(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:ub,declaresReads:!1}}async function pb(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 hb(t){let e=await lb.readFile(t,"utf8");return JSON.parse(e)}function mb(t){return lb.readFile(t,"utf8")}function fb(t,e){let r=t.conduit,n=`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`,o=t.targets.length>1;if(!e){if(t.error)return n;if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(o){let c=t.targets.reduce((l,u)=>l+u.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${c} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}if(t.error&&!r.id)return n;let s=[];s.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),s.push(`conduit: ${r.id}`);let i=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(c=>`${c.source}.${c.recordType}`).join(" \u2192 ");s.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${i}${r.on?` on=${r.on}`:""}`),s.push(""),s.push("guards (dispatch order):"),t.guards.length===0&&s.push(" (none ran \u2014 the replay stopped before dispatch)");for(let c of t.guards){let l=c.status==="passed"?"\u2713":c.status==="failed"?"\u2717":"\u2298";s.push(` ${l} ${c.name} [${c.status}] \u2014 ${c.detail}`)}if(s.push(""),s.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let c of t.atlasResolutions)s.push(` ${c.key} \u2192 ${c.resolved===null?"null (no Atlas link \u2014 noted)":c.resolved}`);if(s.push(""),s.push("ctx.query (declared reads):"),!r.declaresReads)s.push(" (no `reads` declared \u2014 ctx.query is not defined in the isolate, exactly as in production)");else if(t.queryReads.length===0)s.push(" (declared, but this replay made no read)");else for(let c of t.queryReads)s.push(` ${c.query} \u2192 ${c.served?"served":"not served by the fixture"}, ${c.rowCount} row(s)`);if(t.error)return s.push(""),s.push(`ERROR \u2014 ${t.error}`),s.join(`
2495
2526
  `);if(!t.whenPassed)return s.push(""),s.push("transform: SKIPPED (from.when gate did not fire)."),s.join(`
2496
- `);let a=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(a.forEach((c,l)=>{let u=o?` (target ${l+1}/${a.length}: ${c.to.source}.${c.to.recordType})`:"";s.push(""),s.push(`transform${u} \u2192 patch:`),s.push(zP(JSON.stringify(c.transformResult.patch??{},null,2)," ")),c.transformResult.createdFrom&&s.push(` createdFrom: ${JSON.stringify(c.transformResult.createdFrom)}`),s.push(""),s.push(`apply-branch${u}: ${c.applyBranch}`),s.push(` ${c.masterAction}`),s.push(""),s.push(`bindings that WOULD be written (txn_source_link)${u}:`);for(let p of c.wouldWriteBindings)s.push(` ${p.source} role=${p.role} external_id=${p.externalId??"null"} \u2014 ${p.why}`)}),t.logs.length>0){s.push(""),s.push("conduit logs:");for(let c of t.logs)s.push(` [${c.level}] ${c.message}${c.meta?` ${JSON.stringify(c.meta)}`:""}`)}return s.join(`
2497
- `)}function zP(t,e){return t.split(`
2527
+ `);let a=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(a.forEach((c,l)=>{let u=o?` (target ${l+1}/${a.length}: ${c.to.source}.${c.to.recordType})`:"";s.push(""),s.push(`transform${u} \u2192 patch:`),s.push(DP(JSON.stringify(c.transformResult.patch??{},null,2)," ")),c.transformResult.createdFrom&&s.push(` createdFrom: ${JSON.stringify(c.transformResult.createdFrom)}`),s.push(""),s.push(`apply-branch${u}: ${c.applyBranch}`),s.push(` ${c.masterAction}`),s.push(""),s.push(`bindings that WOULD be written (txn_source_link)${u}:`);for(let p of c.wouldWriteBindings)s.push(` ${p.source} role=${p.role} external_id=${p.externalId??"null"} \u2014 ${p.why}`)}),t.logs.length>0){s.push(""),s.push("conduit logs:");for(let c of t.logs)s.push(` [${c.level}] ${c.message}${c.meta?` ${JSON.stringify(c.meta)}`:""}`)}return s.join(`
2528
+ `)}function DP(t,e){return t.split(`
2498
2529
  `).map(r=>e+r).join(`
2499
- `)}var DP="2026-01-01",fb="2026-01-01T00:00:00.000Z";function MP(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"?DP:r.startsWith("timestamp")?fb: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:fb}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function UP(t){let e={};for(let r of t.columns)e[r.name]=MP(r.pgType,r.name);return e}function qP(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:UP(t)},expect:e.expect??"pass"}}function gb(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:qP(r,e)}))}import{promises as yb}from"node:fs";import{join as bb,relative as FP,sep as BP}from"node:path";var ZP=67324752,VP=33639248,HP=101010256,KP=(()=>{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 WP(t){let e=4294967295;for(let r=0;r<t.length;r++)e=KP[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function GP(t){let e=[];async function r(n){let o=await yb.readdir(n,{withFileTypes:!0});for(let s of o){let i=bb(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(FP(t,i).split(BP).join("/"))}}return await r(t),e.sort(),e}async function wb(t){let e=await GP(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await yb.readFile(bb(t,a)),u=WP(l),p=Buffer.alloc(30+c.length);p.writeUInt32LE(ZP,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(VP,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(HP,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}}vu();function JP(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function ba(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}var YP=new Set(["after_save","after_delete"]);function _b(t){let e=/(?:^|[\s{,(;])on\s*:\s*(['"`])([^'"`]+)\1/.exec(t);return e?e[2]:void 0}function XP(t){let e=QP(t,"from"),n=vb(t,"to").map(o=>({source:ba(o,"source"),recordType:ba(o,"recordType")}));return{fromSource:e?ba(e,"source"):void 0,fromRecordType:e?ba(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function QP(t,e){return vb(t,e)[0]??null}function vb(t,e){let r=[],n=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(t))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<t.length;a+=1){let c=t[a];if(c==="{")s+=1;else if(c==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function eA(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 tA(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function rA(t){return/\bcreatedFrom\b/.test(t)}function nA(t){let e=/\bdefine(?:Hook|Conduit|Process)\s*(?:<[^>]*>)?\s*\(\s*\{/.exec(t);if(!e)return null;let r=0,n=null,o=!1;for(let s=e.index+e[0].length-1;s<t.length;s+=1){let i=t[s];if(n){i==="\\"?s+=1:i===n&&(n=null);continue}if(i==="/"&&t[s+1]==="/"){let a=t.indexOf(`
2500
- `,s);s=a<0?t.length:a;continue}if(i==="/"&&t[s+1]==="*"){let a=t.indexOf("*/",s+2);s=a<0?t.length:a+1;continue}if(i==="'"||i==='"'||i==="`"){n=i,o=!1;continue}if(i==="{"||i==="("||i==="["){r+=1,o=r===1;continue}if(i==="}"||i===")"||i==="]"){if(r-=1,r===0)return{};continue}if(r===1&&i===","){o=!0;continue}if(!(r===1&&o&&/\s/.test(i))&&r===1&&o){o=!1;let a=/^id\s*:\s*/.exec(t.slice(s));if(!a)continue;let c=/^(['"`])([^'"`]+)\1/.exec(t.slice(s+a[0].length));return c?{literal:c[2],index:s}:{}}}return{}}function oA(t){let e=/id\s*:\s*(['"`])([^'"`]+)\1/.exec(t),r=nA(t);if(!e||!r||r.index===e.index)return null;let n=e[2];return{rule:"id-not-first-literal",message:r.literal===void 0?`the define call's own \`id\` is not a string literal, so the deploy keys this file on the first \`id:\` literal it finds, '${n}' \u2014 the deploy will refuse it with extension_id_mismatch unless that is the module's id.`:`the first \`id:\` literal in the file is '${n}', not the define call's own '${r.literal}' \u2014 the deploy keys the file on the first one and refuses the mismatch (extension_id_mismatch).`,fix:"Write the extension's own id as a string literal on the define call (`id: '<your-id>'`), and keep any comment, constant, step or helper that carries an `id:` literal below it."}}function xb(t){let e=JP(t),r=[],n=oA(t);if(n&&r.push(n),e!=="conduit")return{kind:e,warnings:r};let{fromSource:o,fromRecordType:s,toRecordType:i,targets:a}=XP(t);for(let p of a)if(o&&p.source&&o===p.source){r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${o}' \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.`});break}let c=eA(t);if(c!==null){let p=/\bexternalId\b/.test(c),w=/\bfromSource\b/.test(c),f=/\bchange\b/.test(c);!p&&!w?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}``."}):YP.has(_b(t)??"")&&!f&&r.push({rule:"lifetime-idempotency-key",message:`this conduit fires on '${_b(t)}' and its idempotencyKey carries nothing about the save \u2014 on a save trigger ctx.externalId is the same string for the whole of a record's life, so every later save dedupes into the first one and the conduit fires ONCE per record and never again.`,fix:"Omit `idempotencyKey` entirely \u2014 the engine derives a per-save token for this trigger \u2014 or include something about the change, e.g. `idempotencyKey: (ctx) => `${ctx.externalId}:${(ctx.change?.fields ?? []).join(`,`)}``."})}let l=a.find(p=>p.recordType&&s&&p.recordType!==s)?.recordType??(s!==i?i:void 0);s&&l&&!rA(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${l}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${l} 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 u=tA(t,"cycleBudget");return u!==void 0&&(u<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${u} 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)."}):u>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${u} 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 kb(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(`
2530
+ `)}var MP="2026-01-01",gb="2026-01-01T00:00:00.000Z";function UP(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"?MP:r.startsWith("timestamp")?gb: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:gb}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function qP(t){let e={};for(let r of t.columns)e[r.name]=UP(r.pgType,r.name);return e}function FP(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:qP(t)},expect:e.expect??"pass"}}function yb(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:FP(r,e)}))}import{promises as bb}from"node:fs";import{join as wb,relative as BP,sep as ZP}from"node:path";var VP=67324752,HP=33639248,KP=101010256,WP=(()=>{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 GP(t){let e=4294967295;for(let r=0;r<t.length;r++)e=WP[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function JP(t){let e=[];async function r(n){let o=await bb.readdir(n,{withFileTypes:!0});for(let s of o){let i=wb(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(BP(t,i).split(ZP).join("/"))}}return await r(t),e.sort(),e}async function _b(t){let e=await JP(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await bb.readFile(wb(t,a)),u=GP(l),p=Buffer.alloc(30+c.length);p.writeUInt32LE(VP,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(HP,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(KP,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}}ku();function YP(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function ba(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}var XP=new Set(["after_save","after_delete"]);function vb(t){let e=/(?:^|[\s{,(;])on\s*:\s*(['"`])([^'"`]+)\1/.exec(t);return e?e[2]:void 0}function QP(t){let e=eA(t,"from"),n=kb(t,"to").map(o=>({source:ba(o,"source"),recordType:ba(o,"recordType")}));return{fromSource:e?ba(e,"source"):void 0,fromRecordType:e?ba(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function eA(t,e){return kb(t,e)[0]??null}function kb(t,e){let r=[],n=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(t))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<t.length;a+=1){let c=t[a];if(c==="{")s+=1;else if(c==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function tA(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 rA(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function nA(t){return/\bcreatedFrom\b/.test(t)}function oA(t){let e=/\bdefine(?:Hook|Conduit|Process)\s*(?:<[^>]*>)?\s*\(\s*\{/.exec(t);if(!e)return null;let r=0,n=null,o=!1;for(let s=e.index+e[0].length-1;s<t.length;s+=1){let i=t[s];if(n){i==="\\"?s+=1:i===n&&(n=null);continue}if(i==="/"&&t[s+1]==="/"){let a=t.indexOf(`
2531
+ `,s);s=a<0?t.length:a;continue}if(i==="/"&&t[s+1]==="*"){let a=t.indexOf("*/",s+2);s=a<0?t.length:a+1;continue}if(i==="'"||i==='"'||i==="`"){n=i,o=!1;continue}if(i==="{"||i==="("||i==="["){r+=1,o=r===1;continue}if(i==="}"||i===")"||i==="]"){if(r-=1,r===0)return{};continue}if(r===1&&i===","){o=!0;continue}if(!(r===1&&o&&/\s/.test(i))&&r===1&&o){o=!1;let a=/^id\s*:\s*/.exec(t.slice(s));if(!a)continue;let c=/^(['"`])([^'"`]+)\1/.exec(t.slice(s+a[0].length));return c?{literal:c[2],index:s}:{}}}return{}}function sA(t){let e=/id\s*:\s*(['"`])([^'"`]+)\1/.exec(t),r=oA(t);if(!e||!r||r.index===e.index)return null;let n=e[2];return{rule:"id-not-first-literal",message:r.literal===void 0?`the define call's own \`id\` is not a string literal, so the deploy keys this file on the first \`id:\` literal it finds, '${n}' \u2014 the deploy will refuse it with extension_id_mismatch unless that is the module's id.`:`the first \`id:\` literal in the file is '${n}', not the define call's own '${r.literal}' \u2014 the deploy keys the file on the first one and refuses the mismatch (extension_id_mismatch).`,fix:"Write the extension's own id as a string literal on the define call (`id: '<your-id>'`), and keep any comment, constant, step or helper that carries an `id:` literal below it."}}function xb(t){let e=YP(t),r=[],n=sA(t);if(n&&r.push(n),e!=="conduit")return{kind:e,warnings:r};let{fromSource:o,fromRecordType:s,toRecordType:i,targets:a}=QP(t);for(let p of a)if(o&&p.source&&o===p.source){r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${o}' \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.`});break}let c=tA(t);if(c!==null){let p=/\bexternalId\b/.test(c),w=/\bfromSource\b/.test(c),f=/\bchange\b/.test(c);!p&&!w?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}``."}):XP.has(vb(t)??"")&&!f&&r.push({rule:"lifetime-idempotency-key",message:`this conduit fires on '${vb(t)}' and its idempotencyKey carries nothing about the save \u2014 on a save trigger ctx.externalId is the same string for the whole of a record's life, so every later save dedupes into the first one and the conduit fires ONCE per record and never again.`,fix:"Omit `idempotencyKey` entirely \u2014 the engine derives a per-save token for this trigger \u2014 or include something about the change, e.g. `idempotencyKey: (ctx) => `${ctx.externalId}:${(ctx.change?.fields ?? []).join(`,`)}``."})}let l=a.find(p=>p.recordType&&s&&p.recordType!==s)?.recordType??(s!==i?i:void 0);s&&l&&!nA(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${l}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${l} 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 u=rA(t,"cycleBudget");return u!==void 0&&(u<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${u} 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)."}):u>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${u} 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 Sb(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(`
2501
2532
  `);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(`
2502
2533
  lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
2503
- `)}function Sb(t){return t.cases.filter(e=>e.status==="failed").length}function xs(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function sA(t){let e=Sb(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${xs(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${xs(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${xs(n.type)}"`:"";r.push(` <failure${i} message="${xs(s)}">${xs(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
2534
+ `)}function $b(t){return t.cases.filter(e=>e.status==="failed").length}function ks(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function iA(t){let e=$b(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${ks(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${ks(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${ks(n.type)}"`:"";r.push(` <failure${i} message="${ks(s)}">${ks(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
2504
2535
  `)}
2505
- `}function iA(t){let e={suite:t.name,tests:t.cases.length,failures:Sb(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2506
- `}function wa(t,e){return e==="junit"?sA(t):iA(t)}var Rt={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"},Ye={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},xo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Zt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},$b=/\x1b\[[0-9;]*m/g;function jr(t){return t.replace($b,"").length}function Eu(t,e){return e<=0?1:Math.max(1,Math.ceil(jr(t)/e))}function aA(){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 Pu=aA();function ot(){return Pu}function Au(t){Pu=t}function at(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Vt(t,e){return Pu?`${t}${e}${Rt.reset}`:e}var g={bold:t=>Vt(Rt.bold,t),dim:t=>Vt(Rt.dim,t),red:t=>Vt(Rt.red,t),green:t=>Vt(Rt.green,t),yellow:t=>Vt(Rt.yellow,t),blue:t=>Vt(Rt.blue,t),magenta:t=>Vt(Rt.magenta,t),cyan:t=>Vt(Rt.cyan,t),grey:t=>Vt(Rt.grey,t)};var Ne={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}`},Xr={add:t=>g.green(`+ ${t}`),change:t=>g.yellow(`~ ${t}`),destroy:t=>g.red(`- ${t}`)},cA=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),lA=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),uA=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function ko(t){let e=t.toLowerCase();return cA.has(e)?g.green(t):lA.has(e)?g.red(t):uA.has(e)?g.yellow(t):t}function Qr(t,e=[]){let r=Math.max(jr(t),...e.map(jr),0),n=r+2,o=g.cyan(Zt.v),s=a=>` ${a}${" ".repeat(r-jr(a))} `,i=[g.cyan(`${Zt.tl}${Zt.h.repeat(n)}${Zt.tr}`),`${o}${g.bold(s(t))}${o}`];if(e.length){i.push(`${g.cyan(Zt.ml)}${g.dim(Zt.h.repeat(n))}${g.cyan(Zt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(g.cyan(`${Zt.bl}${Zt.h.repeat(n)}${Zt.br}`)),i.join(`
2536
+ `}function aA(t){let e={suite:t.name,tests:t.cases.length,failures:$b(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2537
+ `}function wa(t,e){return e==="junit"?iA(t):aA(t)}var Rt={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"},Ye={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},vo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Zt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Tb=/\x1b\[[0-9;]*m/g;function jr(t){return t.replace(Tb,"").length}function Pu(t,e){return e<=0?1:Math.max(1,Math.ceil(jr(t)/e))}function cA(){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 Au=cA();function ot(){return Au}function Cu(t){Au=t}function at(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Vt(t,e){return Au?`${t}${e}${Rt.reset}`:e}var g={bold:t=>Vt(Rt.bold,t),dim:t=>Vt(Rt.dim,t),red:t=>Vt(Rt.red,t),green:t=>Vt(Rt.green,t),yellow:t=>Vt(Rt.yellow,t),blue:t=>Vt(Rt.blue,t),magenta:t=>Vt(Rt.magenta,t),cyan:t=>Vt(Rt.cyan,t),grey:t=>Vt(Rt.grey,t)};var Ne={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}`},Xr={add:t=>g.green(`+ ${t}`),change:t=>g.yellow(`~ ${t}`),destroy:t=>g.red(`- ${t}`)},lA=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),uA=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),dA=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function ko(t){let e=t.toLowerCase();return lA.has(e)?g.green(t):uA.has(e)?g.red(t):dA.has(e)?g.yellow(t):t}function Qr(t,e=[]){let r=Math.max(jr(t),...e.map(jr),0),n=r+2,o=g.cyan(Zt.v),s=a=>` ${a}${" ".repeat(r-jr(a))} `,i=[g.cyan(`${Zt.tl}${Zt.h.repeat(n)}${Zt.tr}`),`${o}${g.bold(s(t))}${o}`];if(e.length){i.push(`${g.cyan(Zt.ml)}${g.dim(Zt.h.repeat(n))}${g.cyan(Zt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(g.cyan(`${Zt.bl}${Zt.h.repeat(n)}${Zt.br}`)),i.join(`
2507
2538
  `)}function Ht(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=>jr(u[l]??"")));let a=l=>{let u=l.map((p,w)=>{let f=p??"";return w===l.length-1?f:f+" ".repeat(Math.max(0,i[w]-jr(f)))});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]??jr(l)))))));for(let l of t)c.push(a(l));return c.join(`
2508
- `)}function Cu(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`${ot()?e.map(n=>Vt(Rt.cyan,n)).join(`
2539
+ `)}function Iu(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`${ot()?e.map(n=>Vt(Rt.cyan,n)).join(`
2509
2540
  `):e.join(`
2510
2541
  `)}
2511
- ${g.dim(` ${t}`)}`}var Kt=t=>{process.stderr.write(t)};function _a(){return ot()&&process.stderr.isTTY===!0}function Tb(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 ie(t,e){let r=_a(),n=0,o;r&&(Kt(Ye.hideCursor),o=setInterval(()=>{Kt(`${Ye.col0}${Ye.clearLine}${g.magenta(xo[n++%xo.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Kt(`${Ye.col0}${Ye.clearLine}${Ye.showCursor}`)};try{let i=await e();return s(),r&&Kt(`${Ne.success(t)}
2542
+ ${g.dim(` ${t}`)}`}var Kt=t=>{process.stderr.write(t)};function _a(){return ot()&&process.stderr.isTTY===!0}function Rb(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 ie(t,e){let r=_a(),n=0,o;r&&(Kt(Ye.hideCursor),o=setInterval(()=>{Kt(`${Ye.col0}${Ye.clearLine}${g.magenta(vo[n++%vo.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Kt(`${Ye.col0}${Ye.clearLine}${Ye.showCursor}`)};try{let i=await e();return s(),r&&Kt(`${Ne.success(t)}
2512
2543
  `),i}catch(i){throw s(),r&&Kt(`${Ne.error(t)}
2513
- `),i}}function Iu(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=g.magenta(xo[e%xo.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} ${Tb(r.percent)} ${p}`},s=()=>{Kt(`${Ye.col0}${Ye.clearLine}${o()}`),n=!0},i=()=>{n&&Kt(`${Ye.col0}${Ye.clearLine}`),n=!1};Kt(Ye.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Kt(`${c}
2514
- `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Kt(Ye.showCursor);let l=c.stage!=="failed",u=`${t} ${g.dim("\u25B8")} ${dA(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Kt(`${l?Ne.success(u):Ne.error(u)}
2515
- `)},stop(){clearInterval(a),i(),Kt(Ye.showCursor)}}}function dA(t){return t==="completed"?g.green(t):t==="failed"?g.red(t):g.cyan(t)}function ct(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)}
2544
+ `),i}}function Ou(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=g.magenta(vo[e%vo.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} ${Rb(r.percent)} ${p}`},s=()=>{Kt(`${Ye.col0}${Ye.clearLine}${o()}`),n=!0},i=()=>{n&&Kt(`${Ye.col0}${Ye.clearLine}`),n=!1};Kt(Ye.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Kt(`${c}
2545
+ `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Kt(Ye.showCursor);let l=c.stage!=="failed",u=`${t} ${g.dim("\u25B8")} ${pA(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Kt(`${l?Ne.success(u):Ne.error(u)}
2546
+ `)},stop(){clearInterval(a),i(),Kt(Ye.showCursor)}}}function pA(t){return t==="completed"?g.green(t):t==="failed"?g.red(t):g.cyan(t)}function ct(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)}
2516
2547
  `),a(`${g.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
2517
- `),a(Ye.hideCursor);let u=0,p=()=>{let b=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Ye.cursorUp(u)),a(Ye.clearToEnd));let $=0;for(let R=0;R<e.length;R+=1){let A=e[R],O=R===i,q=O?g.cyan("\u25B6"):" ",Y=A.disabled?g.grey(A.label):O?g.bold(g.cyan(A.label)):A.label,De=A.description?` ${g.dim(A.description)}`:"",Qe=` ${q} ${Y}${De}`;a(`\r${Qe}
2518
- `),$+=Eu(Qe,b)}u=$},w=()=>{c.removeListener("data",m),c.setRawMode?.(l??!1),c.pause(),a(Ye.showCursor)},f=b=>{let $=i;for(let R=0;R<e.length;R+=1)if($=($+b+e.length)%e.length,!e[$].disabled){i=$;return}},m=b=>{let $=b.toString("utf8");if($===""||$==="q"){w(),a(`
2548
+ `),a(Ye.hideCursor);let u=0,p=()=>{let b=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Ye.cursorUp(u)),a(Ye.clearToEnd));let $=0;for(let R=0;R<e.length;R+=1){let A=e[R],O=R===i,q=O?g.cyan("\u25B6"):" ",J=A.disabled?g.grey(A.label):O?g.bold(g.cyan(A.label)):A.label,De=A.description?` ${g.dim(A.description)}`:"",Qe=` ${q} ${J}${De}`;a(`\r${Qe}
2549
+ `),$+=Pu(Qe,b)}u=$},w=()=>{c.removeListener("data",m),c.setRawMode?.(l??!1),c.pause(),a(Ye.showCursor)},f=b=>{let $=i;for(let R=0;R<e.length;R+=1)if($=($+b+e.length)%e.length,!e[$].disabled){i=$;return}},m=b=>{let $=b.toString("utf8");if($===""||$==="q"){w(),a(`
2519
2550
  `),o(new Error("aborted"));return}if($==="\r"||$===`
2520
- `){let A=e[i];if(A.disabled)return;w(),n(A.value);return}if($==="\x1B[A"||$==="k"){f(-1),p();return}if($==="\x1B[B"||$==="j"){f(1),p();return}let R=Number($);Number.isFinite(R)&&R>=1&&R<=e.length&&!e[R-1].disabled&&(i=R-1,p())};c.on("data",m),p()})}function va(t,e){return`${ko(t)}${" ".repeat(Math.max(0,e-t.length))}`}var Eb=t=>new Promise(e=>setTimeout(e,t));function Rb(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}`:"",s=t.toExternalId?` to_ext=${t.toExternalId}`:"";return`[${t.updatedAt}] ${va(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${s}${r}`}async function Pb(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
2521
- `)}),o=r.sleep??Eb,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(Rb(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(Rb(w)),a+=1,w.updatedAt>c&&(c=w.updatedAt)}return a}function pA(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${va(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function Ab(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
2522
- `)});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(pA(o));return r(`
2523
- binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function hA(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}] ${va(t.severity,5)} ${va(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function Cb(t,e={}){let r=e.sink??(R=>{process.stdout.write(`${R}
2524
- `)}),n=e.sleep??Eb,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:c,sleep:l,intervalMs:u,...p}=e,w=R=>{r(a?JSON.stringify(R):hA(R))},f=await t.platformEvents({...p,limit:p.limit??100});if(f.length===0&&!s)return r("logs: no events matched."),0;let m=0,b="";for(let R of[...f].reverse())w(R),m+=1,R.ts>b&&(b=R.ts);if(!s)return m;let $=i??Number.POSITIVE_INFINITY;for(let R=0;R<$;R+=1){await n(o);let A=await t.platformEvents({...p,...b?{after:b,since:void 0}:{},limit:200});for(let O of[...A].reverse())w(O),m+=1,O.ts>b&&(b=O.ts)}return m}var Ib=new Set(["committed","failed","rolled_back","cancelled"]),ks=t=>{process.stdout.write(`${t}
2525
- `)},mA=t=>new Promise(e=>setTimeout(e,t));function fA(t){return t==null?"\u2014":t<1e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}m${Math.round(t%6e4/1e3)}s`}function Ob(t){let e=t.startedAt??"not started",r=t.outcome&&t.outcome!==t.state?` ${t.outcome}`:"",n=t.scheduleId?" (scheduled)":"";return` ${t.runId} ${t.state.padEnd(11)} ${e} ${fA(t.durationMs)}${n}${r}`}function gA(t){if(t.trigger.kind!=="scheduled")return"manual";let e=t.trigger.timezone?` ${t.trigger.timezone}`:"",r=t.trigger.status&&t.trigger.status!=="active"?` (${t.trigger.status})`:"";return`scheduled ${t.trigger.cron??"?"}${e}${r}`}function Nb(t,e=ks){if(t.length===0){e("No processes are deployed on this instance."),e("Author one with `turbobase ext new process` and ship it with `turbobase ext deploy`.");return}for(let r of t){if(e(`${r.id}${r.enabled?"":" [off]"}`),e(` trigger: ${gA(r)}`),r.runs.length===0)e(" never run");else for(let n of r.runs)e(Ob(n));e("")}e(`${t.length} process(es).`)}function Lb(t,e,r=ks){if(r(t),e.length===0){r(" no runs yet.");return}for(let n of e)r(Ob(n));r(`
2526
- ${e.length} run(s).`)}function xa(t,e=ks){let r=t.run?.runId??t.runId??"(unknown run)",n=t.run?.processId??t.processId??"",o=t.run?.state??t.state??"",s=t.run?.reason??t.reason??null,i=t.run?.outstanding??t.outstanding??null;e(`${r} ${o}${n?` ${n}`:""}`),s&&e(` ${s}`),i!==null&&i>0&&e(` ${i} still outstanding`);let a=t.steps??[];if(a.length===0){e(" no steps recorded yet.");return}for(let c of a){let l=c.externalId??c.pgRowId??"\u2014",u=c.refusal?.message?` ${c.refusal.message}`:"";e(` ${String(c.sequence).padStart(3)} ${c.stepId.padEnd(16)} ${c.disposition.padEnd(12)} ${c.recordType}/${l}${u}`)}}async function jb(t,e,r={}){let n=r.sink??ks,o=r.sleep??mA,s=r.intervalMs??2e3,i=r.maxPolls??Number.POSITIVE_INFINITY,a=new Set,c=u=>{let p=[];xa(u,w=>p.push(w));for(let w of p)a.has(w)||(a.add(w),n(w));return u.run?.state??u.state??""},l=c(await t.processRun(e));if(!r.follow)return l;for(let u=0;u<i;u+=1){if(Ib.has(l))return l;await o(s),l=c(await t.processRun(e))}return Ib.has(l)?l:null}function zb(t,e){let r;try{r=JSON.parse(t)}catch(n){return{ok:!1,message:`${e} must be valid JSON: ${n instanceof Error?n.message:String(n)}`}}return typeof r!="object"||r===null||Array.isArray(r)?{ok:!1,message:`${e} must be a JSON object (the process input), e.g. '{"customerId":"42"}'.`}:{ok:!0,input:r}}function Db(t,e,r,n=ks){let o=t.runId??"(unknown run)",s=`${r} logs --process-run ${o} --follow`;if(t.error==="sync_budget_exceeded"){n(`${o} still running ${t.processId??e}`),n(" It did not settle within the instance's synchronous budget. It has not failed \u2014 it is still going."),n(` Watch it: ${s}`);return}if(t.steps!==void 0){xa(t,n);return}n(`${o} ${t.state??"queued"} ${t.processId??e}`),n(` Watch it: ${s}`)}ka();ga();function Ub(t,e={}){if(t.learningIngestError)return{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.`};if(t.learningIngestTaskId){let r=typeof e.recordedSourceRev=="number"?e.recordedSourceRev:null,n=r??t.learningSourceRev;return n===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 n=="number"?r===null&&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 ${n} 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 ${n}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}}return null}var Bb=9,Ss=" ".repeat(2+Bb);function So(t,e=r=>r){return e(t)+" ".repeat(Math.max(1,Bb-t.length))}function vA(t,e,r){return t===1?e:r}function Zb(t){return t?g.dim(` (${t} holder${t===1?"":"s"} re-stamped)`):""}function Vb(t){return t.length>0?`[${t.join(", ")}]`:"unrestricted"}function xA(t){if(!t)return[];let e=[],r=t.addedGrants??[],n=t.removedGrants??[];if(r.length>0||n.length>0){let s=[...r.map(i=>`+${i}`),...n.map(i=>`\u2212${i}`)];e.push(`content ${s.join(" ")}`)}let o=t.setRestrictions??{};for(let s of Object.keys(o).sort())e.push(`${s} \u2192 ${Vb(o[s]??[])}`);return e}function qb(t){let e=[],r=t.scopeChanges?.adoptedGrants??[];r.length>0&&e.push({stream:"out",text:g.dim(`${Ss}adopted (already on the role \u2014 the admin's, never retired by this app): ${r.join(", ")}`)});let n=t.scopeChanges?.adoptedRestrictions??{};for(let s of Object.keys(n).sort())e.push({stream:"out",text:g.dim(`${Ss}adopted ${s} ${Vb(n[s]??[])} (already on the role \u2014 the admin's, never cleared or widened by this app)`)});let o=[...t.keptRemovedCapabilities??[],...t.scopeChanges?.keptRemovedGrants??[]];o.length>0&&e.push({stream:"out",text:g.dim(`${Ss}kept (admin removed): ${o.join(", ")}`)});for(let s of t.scopeChanges?.keptAdminRestrictions??[])e.push({stream:"out",text:g.dim(`${Ss}kept admin value for ${s}`)});for(let s of t.warnings??[])e.push({stream:"out",text:g.yellow(`${Ss}! ${s}`)});return e}function Hb(t){return(t.warnings?.length??0)>0||(t.keptRemovedCapabilities?.length??0)>0||(t.scopeChanges?.keptRemovedGrants?.length??0)>0||(t.scopeChanges?.keptAdminRestrictions?.length??0)>0}function Fb(t){return Hb(t)||(t.scopeChanges?.adoptedGrants?.length??0)>0||Object.keys(t.scopeChanges?.adoptedRestrictions??{}).length>0}function kA(t,e,r){let n=r==="applied",o=xA(t.scopeChanges),s=n?Zb(t.holdersRestamped):"",i=c=>{let l=[...c,...o];return l.length>0?` ${g.dim(l.join(" "))}`:""};if(t.action==="error")return[{stream:"err",text:` ${So("ERROR",g.bold)}${e} \u2014 ${t.message??"cannot be created"}`},...qb(t)];let a;if(t.action==="create"){let c=t.addCapabilities?.length??0;a=` ${So(n?"created":"create")}${e}${i([`${c} ${vA(c,"capability","capabilities")}`])}${s}`}else if(t.action==="add_capabilities"){let c=(t.addCapabilities??[]).map(l=>`+${l}`).join(", ");a=` ${So(n?"updated":"add")}${e}${i([c])}${s}`}else t.action==="update_scopes"?a=` ${So(n?"updated":"update")}${e}${o.length>0?i([]):` ${g.dim("scopes changed")}`}${s}`:t.action==="noop"?a=` ${So("ok",g.dim)}${e} ${g.dim("already up to date")}`:a=` ${So(n?"changed":"change")}${e}${i([])} ${g.dim("(upgrade the CLI to see details)")}${s}`;return[{stream:"out",text:a},...qb(t)]}function SA(t,e){let r=[];for(let n of t){if(!n.removedGrants||n.removedGrants.length===0)continue;let o=n.removedGrants.map(i=>`\u2212${i}`).join(" "),s=e==="applied"?"retired":"retire";r.push({stream:"out",text:` ${s} grants on ${n.name}: ${g.dim(o)}${e==="applied"?Zb(n.holdersRestamped):""}`})}return r}function Kb(t){let{mode:e}=t,r=t.verdicts??[],n=e==="plan"?r:r.filter(l=>l.action!=="noop"||Fb(l)),o=SA(t.retired??[],e);if(n.length===0&&o.length===0)return[];let s=[{stream:"out",text:""},{stream:"out",text:g.bold(e==="preview"?"roles (preview \u2014 not applied)":"roles")}],i=n.length>0?Math.max(...n.map(l=>l.name.length)):0;for(let l of n)s.push(...kA(l,l.name.padEnd(i),e));s.push(...o);let a=n.some(l=>$A.has(l.action)),c=n.every(l=>l.action==="noop");if(a){let l=e==="plan"?" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users.":e==="preview"?" nothing was created \u2014 promoting this preview applies them.":" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.";s.push({stream:"out",text:g.dim(l)})}else if(o.length===0&&c&&n.some(l=>Fb(l))){let l=e==="applied"?"no role changed":e==="preview"?"no role would change on promote":"no role would change",u=n.some(p=>Hb(p))?"each note above recurs on every deploy until the manifest or the role is changed.":"the adopted values were already on the roles.";s.push({stream:"out",text:g.dim(` ${l} \u2014 ${u}`)})}return s}var $A=new Set(["create","add_capabilities","update_scopes"]);function Ou(t){let{app:e,roles:r}=t;if(r===null)return[];let n=(o,s)=>[{stream:"out",text:""},{stream:"out",text:g.yellow(`! ${o}`)},{stream:"out",text:g.dim(` ${s}`)}];if(r.length===0){let o='"roles": [] retires the content values this app added to roles on an earlier deploy.';return e===null?n(o,"pass --app <slug> so the plan can name them."):Array.isArray(t.retired)?t.retired.some(s=>(s.removedGrants?.length??0)>0)?[]:[{stream:"out",text:""},{stream:"out",text:g.dim(' "roles": [] \u2014 no content value this app added is on a role, so a deploy retires nothing.')}]:n(o,"this instance's plan does not list them \u2014 read the roles section the deploy prints.")}return e===null&&r.some(o=>o.scopes!==void 0&&o.scopes!==null)?n("a declared role carries scopes, but no app was named \u2014 pass --app <slug> (or --as app:<slug>).","without it this plan cannot tell this app's earlier declarations from another app's: a scope another deploy declared on the same role is not planned (the deploy decides it, and may refuse), and content values the deploy would retire are not listed."):[]}function Wb(t){let e=t.roles;return Array.isArray(e)?{verdicts:e,retired:t.rolesRetired??[]}:e&&typeof e=="object"?{verdicts:e.verdicts??[],retired:e.retired??t.rolesRetired??[]}:{verdicts:[],retired:t.rolesRetired??[]}}var Nu=".github/workflows/turbobase-release-deploy.yml",TA=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2551
+ `){let A=e[i];if(A.disabled)return;w(),n(A.value);return}if($==="\x1B[A"||$==="k"){f(-1),p();return}if($==="\x1B[B"||$==="j"){f(1),p();return}let R=Number($);Number.isFinite(R)&&R>=1&&R<=e.length&&!e[R-1].disabled&&(i=R-1,p())};c.on("data",m),p()})}function va(t,e){return`${ko(t)}${" ".repeat(Math.max(0,e-t.length))}`}var Pb=t=>new Promise(e=>setTimeout(e,t));function Eb(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}`:"",s=t.toExternalId?` to_ext=${t.toExternalId}`:"";return`[${t.updatedAt}] ${va(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${s}${r}`}async function Ab(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
2552
+ `)}),o=r.sleep??Pb,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(Eb(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(Eb(w)),a+=1,w.updatedAt>c&&(c=w.updatedAt)}return a}function hA(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${va(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function Cb(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
2553
+ `)});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(hA(o));return r(`
2554
+ binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function mA(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}] ${va(t.severity,5)} ${va(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function Ib(t,e={}){let r=e.sink??(R=>{process.stdout.write(`${R}
2555
+ `)}),n=e.sleep??Pb,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:c,sleep:l,intervalMs:u,...p}=e,w=R=>{r(a?JSON.stringify(R):mA(R))},f=await t.platformEvents({...p,limit:p.limit??100});if(f.length===0&&!s)return r("logs: no events matched."),0;let m=0,b="";for(let R of[...f].reverse())w(R),m+=1,R.ts>b&&(b=R.ts);if(!s)return m;let $=i??Number.POSITIVE_INFINITY;for(let R=0;R<$;R+=1){await n(o);let A=await t.platformEvents({...p,...b?{after:b,since:void 0}:{},limit:200});for(let O of[...A].reverse())w(O),m+=1,O.ts>b&&(b=O.ts)}return m}var Ob=new Set(["committed","failed","rolled_back","cancelled"]),xs=t=>{process.stdout.write(`${t}
2556
+ `)},fA=t=>new Promise(e=>setTimeout(e,t));function gA(t){return t==null?"\u2014":t<1e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}m${Math.round(t%6e4/1e3)}s`}function Nb(t){let e=t.startedAt??"not started",r=t.outcome&&t.outcome!==t.state?` ${t.outcome}`:"",n=t.scheduleId?" (scheduled)":"";return` ${t.runId} ${t.state.padEnd(11)} ${e} ${gA(t.durationMs)}${n}${r}`}function yA(t){if(t.trigger.kind!=="scheduled")return"manual";let e=t.trigger.timezone?` ${t.trigger.timezone}`:"",r=t.trigger.status&&t.trigger.status!=="active"?` (${t.trigger.status})`:"";return`scheduled ${t.trigger.cron??"?"}${e}${r}`}function Lb(t,e=xs){if(t.length===0){e("No processes are deployed on this instance."),e("Author one with `turbobase ext new process` and ship it with `turbobase ext deploy`.");return}for(let r of t){if(e(`${r.id}${r.enabled?"":" [off]"}`),e(` trigger: ${yA(r)}`),r.runs.length===0)e(" never run");else for(let n of r.runs)e(Nb(n));e("")}e(`${t.length} process(es).`)}function jb(t,e,r=xs){if(r(t),e.length===0){r(" no runs yet.");return}for(let n of e)r(Nb(n));r(`
2557
+ ${e.length} run(s).`)}function ka(t,e=xs){let r=t.run?.runId??t.runId??"(unknown run)",n=t.run?.processId??t.processId??"",o=t.run?.state??t.state??"",s=t.run?.reason??t.reason??null,i=t.run?.outstanding??t.outstanding??null;e(`${r} ${o}${n?` ${n}`:""}`),s&&e(` ${s}`),i!==null&&i>0&&e(` ${i} still outstanding`);let a=t.steps??[];if(a.length===0){e(" no steps recorded yet.");return}for(let c of a){let l=c.externalId??c.pgRowId??"\u2014",u=c.refusal?.message?` ${c.refusal.message}`:"";e(` ${String(c.sequence).padStart(3)} ${c.stepId.padEnd(16)} ${c.disposition.padEnd(12)} ${c.recordType}/${l}${u}`)}}async function zb(t,e,r={}){let n=r.sink??xs,o=r.sleep??fA,s=r.intervalMs??2e3,i=r.maxPolls??Number.POSITIVE_INFINITY,a=new Set,c=u=>{let p=[];ka(u,w=>p.push(w));for(let w of p)a.has(w)||(a.add(w),n(w));return u.run?.state??u.state??""},l=c(await t.processRun(e));if(!r.follow)return l;for(let u=0;u<i;u+=1){if(Ob.has(l))return l;await o(s),l=c(await t.processRun(e))}return Ob.has(l)?l:null}function Db(t,e){let r;try{r=JSON.parse(t)}catch(n){return{ok:!1,message:`${e} must be valid JSON: ${n instanceof Error?n.message:String(n)}`}}return typeof r!="object"||r===null||Array.isArray(r)?{ok:!1,message:`${e} must be a JSON object (the process input), e.g. '{"customerId":"42"}'.`}:{ok:!0,input:r}}function Mb(t,e,r,n=xs){let o=t.runId??"(unknown run)",s=`${r} logs --process-run ${o} --follow`;if(t.error==="sync_budget_exceeded"){n(`${o} still running ${t.processId??e}`),n(" It did not settle within the instance's synchronous budget. It has not failed \u2014 it is still going."),n(` Watch it: ${s}`);return}if(t.steps!==void 0){ka(t,n);return}n(`${o} ${t.state??"queued"} ${t.processId??e}`),n(` Watch it: ${s}`)}xa();ga();function qb(t,e={}){if(t.learningIngestError)return{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.`};if(t.learningIngestTaskId){let r=typeof e.recordedSourceRev=="number"?e.recordedSourceRev:null,n=r??t.learningSourceRev;return n===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 n=="number"?r===null&&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 ${n} 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 ${n}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}}return null}var Zb=9,Ss=" ".repeat(2+Zb);function xo(t,e=r=>r){return e(t)+" ".repeat(Math.max(1,Zb-t.length))}function kA(t,e,r){return t===1?e:r}function Vb(t){return t?g.dim(` (${t} holder${t===1?"":"s"} re-stamped)`):""}function Hb(t){return t.length>0?`[${t.join(", ")}]`:"unrestricted"}function xA(t){if(!t)return[];let e=[],r=t.addedGrants??[],n=t.removedGrants??[];if(r.length>0||n.length>0){let s=[...r.map(i=>`+${i}`),...n.map(i=>`\u2212${i}`)];e.push(`content ${s.join(" ")}`)}let o=t.setRestrictions??{};for(let s of Object.keys(o).sort())e.push(`${s} \u2192 ${Hb(o[s]??[])}`);return e}function Fb(t){let e=[],r=t.scopeChanges?.adoptedGrants??[];r.length>0&&e.push({stream:"out",text:g.dim(`${Ss}adopted (already on the role \u2014 the admin's, never retired by this app): ${r.join(", ")}`)});let n=t.scopeChanges?.adoptedRestrictions??{};for(let s of Object.keys(n).sort())e.push({stream:"out",text:g.dim(`${Ss}adopted ${s} ${Hb(n[s]??[])} (already on the role \u2014 the admin's, never cleared or widened by this app)`)});let o=[...t.keptRemovedCapabilities??[],...t.scopeChanges?.keptRemovedGrants??[]];o.length>0&&e.push({stream:"out",text:g.dim(`${Ss}kept (admin removed): ${o.join(", ")}`)});for(let s of t.scopeChanges?.keptAdminRestrictions??[])e.push({stream:"out",text:g.dim(`${Ss}kept admin value for ${s}`)});for(let s of t.warnings??[])e.push({stream:"out",text:g.yellow(`${Ss}! ${s}`)});return e}function Kb(t){return(t.warnings?.length??0)>0||(t.keptRemovedCapabilities?.length??0)>0||(t.scopeChanges?.keptRemovedGrants?.length??0)>0||(t.scopeChanges?.keptAdminRestrictions?.length??0)>0}function Bb(t){return Kb(t)||(t.scopeChanges?.adoptedGrants?.length??0)>0||Object.keys(t.scopeChanges?.adoptedRestrictions??{}).length>0}function SA(t,e,r){let n=r==="applied",o=xA(t.scopeChanges),s=n?Vb(t.holdersRestamped):"",i=c=>{let l=[...c,...o];return l.length>0?` ${g.dim(l.join(" "))}`:""};if(t.action==="error")return[{stream:"err",text:` ${xo("ERROR",g.bold)}${e} \u2014 ${t.message??"cannot be created"}`},...Fb(t)];let a;if(t.action==="create"){let c=t.addCapabilities?.length??0;a=` ${xo(n?"created":"create")}${e}${i([`${c} ${kA(c,"capability","capabilities")}`])}${s}`}else if(t.action==="add_capabilities"){let c=(t.addCapabilities??[]).map(l=>`+${l}`).join(", ");a=` ${xo(n?"updated":"add")}${e}${i([c])}${s}`}else t.action==="update_scopes"?a=` ${xo(n?"updated":"update")}${e}${o.length>0?i([]):` ${g.dim("scopes changed")}`}${s}`:t.action==="noop"?a=` ${xo("ok",g.dim)}${e} ${g.dim("already up to date")}`:a=` ${xo(n?"changed":"change")}${e}${i([])} ${g.dim("(upgrade the CLI to see details)")}${s}`;return[{stream:"out",text:a},...Fb(t)]}function $A(t,e){let r=[];for(let n of t){if(!n.removedGrants||n.removedGrants.length===0)continue;let o=n.removedGrants.map(i=>`\u2212${i}`).join(" "),s=e==="applied"?"retired":"retire";r.push({stream:"out",text:` ${s} grants on ${n.name}: ${g.dim(o)}${e==="applied"?Vb(n.holdersRestamped):""}`})}return r}function Wb(t){let{mode:e}=t,r=t.verdicts??[],n=e==="plan"?r:r.filter(l=>l.action!=="noop"||Bb(l)),o=$A(t.retired??[],e);if(n.length===0&&o.length===0)return[];let s=[{stream:"out",text:""},{stream:"out",text:g.bold(e==="preview"?"roles (preview \u2014 not applied)":"roles")}],i=n.length>0?Math.max(...n.map(l=>l.name.length)):0;for(let l of n)s.push(...SA(l,l.name.padEnd(i),e));s.push(...o);let a=n.some(l=>TA.has(l.action)),c=n.every(l=>l.action==="noop");if(a){let l=e==="plan"?" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users.":e==="preview"?" nothing was created \u2014 promoting this preview applies them.":" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.";s.push({stream:"out",text:g.dim(l)})}else if(o.length===0&&c&&n.some(l=>Bb(l))){let l=e==="applied"?"no role changed":e==="preview"?"no role would change on promote":"no role would change",u=n.some(p=>Kb(p))?"each note above recurs on every deploy until the manifest or the role is changed.":"the adopted values were already on the roles.";s.push({stream:"out",text:g.dim(` ${l} \u2014 ${u}`)})}return s}var TA=new Set(["create","add_capabilities","update_scopes"]);function Nu(t){let{app:e,roles:r}=t;if(r===null)return[];let n=(o,s)=>[{stream:"out",text:""},{stream:"out",text:g.yellow(`! ${o}`)},{stream:"out",text:g.dim(` ${s}`)}];if(r.length===0){let o='"roles": [] retires the content values this app added to roles on an earlier deploy.';return e===null?n(o,"pass --app <slug> so the plan can name them."):Array.isArray(t.retired)?t.retired.some(s=>(s.removedGrants?.length??0)>0)?[]:[{stream:"out",text:""},{stream:"out",text:g.dim(' "roles": [] \u2014 no content value this app added is on a role, so a deploy retires nothing.')}]:n(o,"this instance's plan does not list them \u2014 read the roles section the deploy prints.")}return e===null&&r.some(o=>o.scopes!==void 0&&o.scopes!==null)?n("a declared role carries scopes, but no app was named \u2014 pass --app <slug> (or --as app:<slug>).","without it this plan cannot tell this app's earlier declarations from another app's: a scope another deploy declared on the same role is not planned (the deploy decides it, and may refuse), and content values the deploy would retire are not listed."):[]}function Gb(t){let e=t.roles;return Array.isArray(e)?{verdicts:e,retired:t.rolesRetired??[]}:e&&typeof e=="object"?{verdicts:e.verdicts??[],retired:e.retired??t.rolesRetired??[]}:{verdicts:[],retired:t.rolesRetired??[]}}var Lu=".github/workflows/turbobase-release-deploy.yml",RA=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2527
2558
  # Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
2528
2559
  #
2529
2560
  # Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
@@ -2625,7 +2656,7 @@ jobs:
2625
2656
  --ref "\${{ github.sha }}" \\
2626
2657
  --project . \\
2627
2658
  --follow
2628
- `,RA=".github/workflows/turbobase-app-deploy.yml",EA=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2659
+ `,EA=".github/workflows/turbobase-app-deploy.yml",PA=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2629
2660
  # Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
2630
2661
  #
2631
2662
  # What ships from this repo, and when:
@@ -2845,14 +2876,14 @@ jobs:
2845
2876
  else
2846
2877
  echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
2847
2878
  fi
2848
- `;function Gb(){return[{path:Nu,content:TA}]}function Jb(){return[{path:RA,content:EA}]}ka();var PA=[".mcp.json"];function ew(t,e=PA){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
2879
+ `;function Jb(){return[{path:Lu,content:RA}]}function Yb(){return[{path:EA,content:PA}]}xa();var AA=[".mcp.json"];function tw(t,e=AA){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
2849
2880
  `).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(`
2850
2881
  `)?t:`${t}
2851
2882
  `}
2852
2883
  # Added by the Turbobase scaffold.
2853
2884
  ${o.join(`
2854
2885
  `)}
2855
- `}var AA=`# Turbobase Extensions \u2014 extension project
2886
+ `}var CA=`# Turbobase Extensions \u2014 extension project
2856
2887
 
2857
2888
  This directory authors **Turbobase extensions** (hooks today; conduits later)
2858
2889
  against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
@@ -2921,8 +2952,8 @@ order is the signal, and it is the part the product team reads first.
2921
2952
 
2922
2953
  Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
2923
2954
  updating a test. It is checked into the repo so the whole team sees it.
2924
- `,CA=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)+`
2925
- `;function IA(t){return`---
2955
+ `,IA=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)+`
2956
+ `;function OA(t){return`---
2926
2957
  name: generate-types
2927
2958
  description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
2928
2959
  ---
@@ -2933,7 +2964,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
2933
2964
 
2934
2965
  The OpenAPI half is cookie-session-gated, so a headless run with a stored token
2935
2966
  degrades to record shapes only and says so \u2014 that is expected, not a failure.
2936
- `}var OA=`---
2967
+ `}var NA=`---
2937
2968
  name: mock-test
2938
2969
  description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
2939
2970
  ---
@@ -2942,7 +2973,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
2942
2973
  self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
2943
2974
  against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
2944
2975
  fixture for each branch (a passing record and a rejecting record).
2945
- `,NA=`---
2976
+ `,LA=`---
2946
2977
  name: deploy
2947
2978
  description: Deploy a hook to your instance. Use only after mock-test is green.
2948
2979
  ---
@@ -2950,7 +2981,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
2950
2981
  Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
2951
2982
  /v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
2952
2983
  the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
2953
- `;function LA(t){return`# ${t} \u2014 Turbobase app
2984
+ `;function jA(t){return`# ${t} \u2014 Turbobase app
2954
2985
 
2955
2986
  This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
2956
2987
  same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
@@ -3326,7 +3357,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
3326
3357
  review, so what you write reaches the knowledge base and the product team instead
3327
3358
  of evaporating at the end of the session. Keep the section headings exactly as
3328
3359
  they are \u2014 the ingest finds entries by heading, not by filename.
3329
- `}var $o="customer",Mn="email",jA="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",zA=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
3360
+ `}var So="customer",Mn="email",zA="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",DA=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
3330
3361
  //
3331
3362
  // It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
3332
3363
  // the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
@@ -3345,8 +3376,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
3345
3376
  // Pure and credentials-free: no secrets, no network, no Node builtins, one
3346
3377
  // concern per file, nothing factored into a shared module (the sandbox fences
3347
3378
  // every import except the SDK).
3348
- `;function DA(){let t=_r("hook",{recordType:$o,event:"before_save",template:"enforce-format",field:Mn,regex:jA,id:`app:${$o}:${Mn}-format`,description:`Reject a ${$o} write whose ${Mn} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:$o,event:"before_save",payload:r},expect:n},null,2)+`
3349
- `;return[{path:t.relativePath,content:`${zA}${t.content}`},{path:`samples/${$o}.${Mn}-ok.json`,content:e({company_name:"Acme Supply",[Mn]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${$o}.${Mn}-malformed.json`,content:e({company_name:"Acme Supply",[Mn]:"ada-at-example"},"reject","a malformed address is rejected")}]}var MA="---\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",UA=`---
3379
+ `;function MA(){let t=_r("hook",{recordType:So,event:"before_save",template:"enforce-format",field:Mn,regex:zA,id:`app:${So}:${Mn}-format`,description:`Reject a ${So} write whose ${Mn} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:So,event:"before_save",payload:r},expect:n},null,2)+`
3380
+ `;return[{path:t.relativePath,content:`${DA}${t.content}`},{path:`samples/${So}.${Mn}-ok.json`,content:e({company_name:"Acme Supply",[Mn]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${So}.${Mn}-malformed.json`,content:e({company_name:"Acme Supply",[Mn]:"ada-at-example"},"reject","a malformed address is rejected")}]}var UA="---\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",qA=`---
3350
3381
  name: ship-app
3351
3382
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
3352
3383
  ---
@@ -3389,12 +3420,12 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
3389
3420
  non-text, so images and fonts belong in the build pipeline or object storage, not
3390
3421
  the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
3391
3422
  project root and DO travel \u2014 deploy reads them.
3392
- `,Lu="<!-- platform-maintained: rewritten every session by `turbobase project skills` from the installed CLI. Do not edit \u2014 your own lessons go in INSTANCE-LEARNINGS.md. -->";function Yb(t){let e=t.indexOf(`
3423
+ `,ju="<!-- platform-maintained: rewritten every session by `turbobase project skills` from the installed CLI. Do not edit \u2014 your own lessons go in INSTANCE-LEARNINGS.md. -->";function Xb(t){let e=t.indexOf(`
3393
3424
  ---
3394
3425
  `,4);if(!t.startsWith(`---
3395
3426
  `)||e<0)throw new Error("a platform skill must open with frontmatter");let r=e+5;return`${t.slice(0,r)}
3396
- ${Lu}
3397
- ${t.slice(r)}`}var qA=`---
3427
+ ${ju}
3428
+ ${t.slice(r)}`}var FA=`---
3398
3429
  name: business-rule-to-hook
3399
3430
  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.
3400
3431
  ---
@@ -3462,7 +3493,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
3462
3493
  standing rules for every agent on the instance \u2014 see the record-learning skill.
3463
3494
  A rule enforced in code and nowhere written down gets re-litigated by the next
3464
3495
  person.
3465
- `,FA="---\nname: write-a-process\ndescription: Write, deploy and run a Turbobase process (defineProcess) \u2014 a chain of record writes, or an eachRow migration that moves many records. Use whenever you create or change a file under processes/, call POST /v1/processes/:id, or debug a process run.\n---\n\nThe contract is the published guide \u2014 read it before writing one:\n`https://docs.turbobase.io/extending/writing-processes/`, and for moving data\nbetween connected systems `https://docs.turbobase.io/extending/migrating-between-systems/`.\nStart from its **A migration recipe** section for any `eachRow` process.\n\nCheck these before you conclude the platform is wrong:\n\n1. **Instance version.** `update` steps, `ctx.row` in a deployed process,\n slices that queue themselves and `{ kind: 'process' }` schedules all need\n **v1.38.0** or later. On an older instance an `update` step CREATES a row.\n2. **Changing a row = `update:` on the step**, e.g.\n `update: { pgRowId: (ctx) => ctx.row.pg_row_id }`, with `pg_row_id` in the\n `outstanding` select. `build` returns `{ parent, lines? }` only \u2014 an id\n returned from `build` is ignored and the step creates.\n3. **The first `id: '\u2026'` in the file must be the process id**, as a literal.\n `ext deploy` stores the file under that string and refuses it with\n `extension_id_mismatch` when the module defines another id \u2014 fix the file,\n do not rename the deploy. `(replaced existing)` in its output means an\n existing copy was replaced, and the line names the id it used.\n4. **The invoke body IS the input** \u2014 no `{ input: \u2026 }` envelope.\n5. **A run continues itself.** Invoke once (async); it queues its own next\n slice. For unattended runs use a `{ kind: 'process' }` entry in\n `turbobase/schedules.json`. From a terminal, `turbobase processes invoke\n <id> --input '<json>'` starts one (an administrator's `extensions:deploy`\n token; the run writes as that person). A process cannot start a process.\n6. **`outstanding` is read once per slice**, and must stop returning a row once\n it is done \u2014 otherwise update steps re-run every slice.\n7. **NetSuite transaction creates need `lines`** (`ATOMIC_WRITE_REQUIRED`).\n On `write_settle_conflict` the record EXISTS upstream: never re-save it; the\n id is on `record_write_state.external_id`. Link the row to it with\n `turbobase data settle <recordType> <pgRowId>`\n (`POST /v1/data/<recordType>/settle`).\n8. **Undo a finished run with `turbobase processes rollback <runId>`** \u2014 it\n deletes only records that run created (never one an `update` step changed),\n paced by its own rollback cap rather than the customer delete cap. Until\n every source delete is sent, the run's `reason` says so. `rolled_back`\n means removed here and ACCEPTED for sending \u2014 never tell a reader it is gone\n upstream from the state alone. A rollback also deletes a record whose create\n has not reached the source yet (a step that did not await, or whose wait ran\n out), so roll back a stopped run only once those have landed.\n9. **A chain that stops cannot be resumed.** An `awaitSource` step waits five\n minutes; past that the run ends `committed` with `outstanding > 0`.\n Invoking again starts at step one and CREATES AGAIN \u2014 a chain's step keys are\n per run (an `eachRow` process is different: its keys are per row). Give\n every step a `when` that reads whether its record already stands, so the\n same invoke carries on instead of duplicating.\n10. **Invoking takes no idempotency key.** After a 502/504 the run may exist;\n retry only a 429 and `503 enqueue_failed`, and otherwise read the\n process's runs before starting another.\n11. **A create the source applied but could not link back** ends its step\n `SOURCE_APPLIED_UNLINKED`, with the source's id on the step: the row is\n kept by every rollback. Link it (item 7). On an older instance it read\n `SOURCE_REFUSED` and a rollback deleted the row \u2014 check `ADOPT.md`.\n12. **An update address may be `async`.** Read the row's current\n `sync_version` with `ctx.query` inside `expectedSyncVersion` itself.\n13. **Only a delete step takes `onRefused: 'continue'`.** A refused create or\n update ends the run. A refusal for a location, class, department or segment\n outside the user's scope is a bare `WRITE_REFUSED` / `forbidden`, naming\n no field.\n14. **A preview cannot run a new or changed process.** Processes are installed\n on merge, so a preview answers `404 process_not_found` (or runs the\n installed version). Say so on screen. `turbobase ext test` runs hooks and\n cannot run a process \u2014 `ext lint`, then invoke it and read the run.\n",ju=[{path:".claude/skills/business-rule-to-hook/SKILL.md",content:Yb(qA)},{path:".claude/skills/write-a-process/SKILL.md",content:Yb(FA)}];function BA(t){return`---
3496
+ `,BA="---\nname: write-a-process\ndescription: Write, deploy and run a Turbobase process (defineProcess) \u2014 a chain of record writes, or an eachRow migration that moves many records. Use whenever you create or change a file under processes/, call POST /v1/processes/:id, or debug a process run.\n---\n\nThe contract is the published guide \u2014 read it before writing one:\n`https://docs.turbobase.io/extending/writing-processes/`, and for moving data\nbetween connected systems `https://docs.turbobase.io/extending/migrating-between-systems/`.\nStart from its **A migration recipe** section for any `eachRow` process.\n\nCheck these before you conclude the platform is wrong:\n\n1. **Instance version.** `update` steps, `ctx.row` in a deployed process,\n slices that queue themselves and `{ kind: 'process' }` schedules all need\n **v1.38.0** or later. On an older instance an `update` step CREATES a row.\n2. **Changing a row = `update:` on the step**, e.g.\n `update: { pgRowId: (ctx) => ctx.row.pg_row_id }`, with `pg_row_id` in the\n `outstanding` select. `build` returns `{ parent, lines? }` only \u2014 an id\n returned from `build` is ignored and the step creates.\n3. **The first `id: '\u2026'` in the file must be the process id**, as a literal.\n `ext deploy` stores the file under that string and refuses it with\n `extension_id_mismatch` when the module defines another id \u2014 fix the file,\n do not rename the deploy. `(replaced existing)` in its output means an\n existing copy was replaced, and the line names the id it used.\n4. **The invoke body IS the input** \u2014 no `{ input: \u2026 }` envelope.\n5. **A run continues itself.** Invoke once (async); it queues its own next\n slice. For unattended runs use a `{ kind: 'process' }` entry in\n `turbobase/schedules.json`. From a terminal, `turbobase processes invoke\n <id> --input '<json>'` starts one (an administrator's `extensions:deploy`\n token; the run writes as that person). A process cannot start a process.\n6. **`outstanding` is read once per slice**, and must stop returning a row once\n it is done \u2014 otherwise update steps re-run every slice.\n7. **NetSuite transaction creates need `lines`** (`ATOMIC_WRITE_REQUIRED`).\n On `write_settle_conflict` the record EXISTS upstream: never re-save it; the\n id is on `record_write_state.external_id`. Link the row to it with\n `turbobase data settle <recordType> <pgRowId>`\n (`POST /v1/data/<recordType>/settle`).\n8. **Undo a finished run with `turbobase processes rollback <runId>`** \u2014 it\n deletes only records that run created (never one an `update` step changed),\n paced by its own rollback cap rather than the customer delete cap. Until\n every source delete is sent, the run's `reason` says so. `rolled_back`\n means removed here and ACCEPTED for sending \u2014 never tell a reader it is gone\n upstream from the state alone. A rollback also deletes a record whose create\n has not reached the source yet (a step that did not await, or whose wait ran\n out), so a run that merely stopped on a wait is RESUMED (item 9) and rolled\n back only when the work is to be undone.\n9. **A chain that stops is RESUMED, never invoked again.** An `awaitSource`\n step waits five minutes; past that the run ends `committed` with\n `outstanding > 0`. Invoking again starts at step one and CREATES AGAIN \u2014 a\n chain's step keys are per run (an `eachRow` process is different: its keys\n are per row, so that one IS invoked again). Carry the same run on with\n `resumeProcessRun(runId)` (`POST /v1/processes/runs/<runId>/resume`, or\n `turbobase processes resume <runId>`): it picks up at the step it stopped\n on and writes nothing twice. Only a run `committed` with work outstanding \u2014\n anything else answers `409` naming the state.\n10. **Invoking takes no idempotency key.** After a 502/504 the run may exist;\n retry only a 429 and `503 enqueue_failed`, and otherwise read the\n process's runs before starting another.\n11. **A create the source applied but could not link back** ends its step\n `SOURCE_APPLIED_UNLINKED`, with the source's id on the step: the row is\n kept by every rollback. Link it (item 7). On an older instance it read\n `SOURCE_REFUSED` and a rollback deleted the row \u2014 check `ADOPT.md`.\n12. **An update address may be `async`.** Read the row's current\n `sync_version` with `ctx.query` inside `expectedSyncVersion` itself.\n13. **Only a delete step takes `onRefused: 'continue'`.** A refused create or\n update ends the run. A refusal for a location, class, department or segment\n outside the user's scope is a bare `WRITE_REFUSED` / `forbidden`, naming\n no field.\n14. **A preview cannot run a new or changed process.** Processes are installed\n on merge, so a preview answers `404 process_not_found` (or runs the\n installed version). Say so on screen. `turbobase ext test` runs hooks and\n cannot run a process \u2014 `ext lint`, then invoke it and read the run.\n",zu=[{path:".claude/skills/business-rule-to-hook/SKILL.md",content:Xb(FA)},{path:".claude/skills/write-a-process/SKILL.md",content:Xb(BA)}];function ZA(t){return`---
3466
3497
  name: record-learning
3467
3498
  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.
3468
3499
  ---
@@ -3517,7 +3548,7 @@ earlier claim" and still publish.
3517
3548
 
3518
3549
  Do not reword the three headings. The deploy-side ingest recognises entries by
3519
3550
  heading, not by filename, so a renamed section is a finding nobody receives.
3520
- `}function ZA(t){return`# What this instance's source system actually does
3551
+ `}function VA(t){return`# What this instance's source system actually does
3521
3552
 
3522
3553
  Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
3523
3554
  Written for the knowledge base, and **everything here is verified against real
@@ -3648,7 +3679,7 @@ finding has not been handed to the knowledge base yet.
3648
3679
  and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
3649
3680
  already live, which is worth reading before adding another rule. -->
3650
3681
 
3651
- `}function VA(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
3682
+ `}function HA(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
3652
3683
 
3653
3684
  Everything below cost time or produced a wrong result. Not speculation, and not
3654
3685
  a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
@@ -3728,7 +3759,7 @@ Expected / happened / cost / fix.
3728
3759
  and what it would replace. These are the highest-signal entries in the file:
3729
3760
  each one is a page downloading rows to fold that it could have asked for
3730
3761
  folded. -->
3731
- `}function HA(t,e){let r=e?`
3762
+ `}function KA(t,e){let r=e?`
3732
3763
  # INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
3733
3764
  # --records focus a previous run stamped into the file, so a refresh never
3734
3765
  # narrows what an agent deliberately widened.
@@ -3769,8 +3800,8 @@ if turbobase project --help 2>&1 | grep -qE '^ +skills( |$)'; then
3769
3800
  turbobase project skills >/dev/null \\
3770
3801
  || echo "turbobase: \\\`turbobase project skills\\\` failed (its error is above) \u2014 the platform skills were NOT refreshed." >&2
3771
3802
  fi
3772
- `}var tw="Turbobase consultant",KA="turbobase-consultant",WA=`---
3773
- name: ${tw}
3803
+ `}var rw="Turbobase consultant",WA="turbobase-consultant",GA=`---
3804
+ name: ${rw}
3774
3805
  description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
3775
3806
  keep-coding-instructions: true
3776
3807
  ---
@@ -3843,8 +3874,8 @@ exists on purpose.
3843
3874
  - Do not show a stack trace. Say what broke and what you are doing about it.
3844
3875
  - Do not apologise repeatedly or pad with "great question".
3845
3876
  - Do not use a table when a sentence works.
3846
- `;function GA(t){let e=[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"},...t?[{type:"command",command:`bash ${rw}`}]:[]];return JSON.stringify({outputStyle:tw,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:e}]}},null,2)+`
3847
- `}var rw=".claude/hooks/format-edited-file.sh",JA=`#!/usr/bin/env bash
3877
+ `;function JA(t){let e=[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"},...t?[{type:"command",command:`bash ${nw}`}]:[]];return JSON.stringify({outputStyle:rw,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:e}]}},null,2)+`
3878
+ `}var nw=".claude/hooks/format-edited-file.sh",YA=`#!/usr/bin/env bash
3848
3879
  # PostToolUse (Edit|Write) \u2014 put the edited file in the house format.
3849
3880
  #
3850
3881
  # Runs \`code-standards fix --files <file>\` from this project's node_modules.
@@ -3855,7 +3886,7 @@ set -uo pipefail
3855
3886
  command -v node >/dev/null 2>&1 || exit 0
3856
3887
 
3857
3888
  exec node "$(dirname "$0")/format-edited-file.mjs"
3858
- `,YA=String.raw`/**
3889
+ `,XA=String.raw`/**
3859
3890
  * Format the file that was just edited, with the project's own
3860
3891
  * @turbobase/code-standards. Reads the PostToolUse payload on stdin. Exit 0
3861
3892
  * always: this hook formats, it never gates.
@@ -3897,7 +3928,7 @@ try {
3897
3928
  // A formatter that fails leaves the file as written.
3898
3929
  }
3899
3930
  bail();
3900
- `,XA=`#!/usr/bin/env bash
3931
+ `,QA=`#!/usr/bin/env bash
3901
3932
  # PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
3902
3933
  #
3903
3934
  # Advisory only: exits 0 always, and adds a note for the agent when the edited
@@ -3914,7 +3945,7 @@ set -uo pipefail
3914
3945
  command -v node >/dev/null 2>&1 || exit 0
3915
3946
 
3916
3947
  exec node "$(dirname "$0")/check-rule-placement.mjs"
3917
- `,QA=String.raw`/**
3948
+ `,eC=String.raw`/**
3918
3949
  * Is the file that was just edited enforcing a business rule inside the SPA?
3919
3950
  *
3920
3951
  * Reads the PostToolUse payload on stdin, and when BOTH signals are present —
@@ -3983,7 +4014,7 @@ process.stdout.write(
3983
4014
  },
3984
4015
  }),
3985
4016
  );
3986
- `,eC=`---
4017
+ `,tC=`---
3987
4018
  name: roles-and-permissions
3988
4019
  description: Decide who can open a screen and who can change a record \u2014 declare roles (and their scopes \u2014 row restrictions and Slack channel content grants) 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, a scope, a screen that reads Slack history, or answering "who can see/do X".
3989
4020
  ---
@@ -4216,7 +4247,7 @@ a denial look like emptiness.
4216
4247
  - Does every write catch \`TurbobasePermissionError\`?
4217
4248
  - Did you run \`turbobase apps plan . --app <slug>\`?
4218
4249
  - Did you tell the user their administrator still has to ASSIGN the role?
4219
- `,tC=`---
4250
+ `,rC=`---
4220
4251
  name: app-design
4221
4252
  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.
4222
4253
  ---
@@ -4311,7 +4342,7 @@ The design system covers the look. Two rules it does not:
4311
4342
  Load it in the browser and check: does it render with ZERO rows, with ONE row,
4312
4343
  and with several hundred? Does it survive the query failing? Does tab reach every
4313
4344
  control, with a visible focus ring? A green \`npm run build\` proves none of these.
4314
- `,Sa="",Xb=String.raw`{
4345
+ `,Sa="",Qb=String.raw`{
4315
4346
  "_comment": [
4316
4347
  "Declarative sync config — part of this repo's desired state.",
4317
4348
  " turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
@@ -4333,7 +4364,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
4333
4364
  "fields": [],
4334
4365
  "tables": []
4335
4366
  }
4336
- `,Qb=String.raw`{
4367
+ `,ew=String.raw`{
4337
4368
  "_comment": [
4338
4369
  "Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
4339
4370
  "Removing an entry does NOT remove the schedule unless you pass --prune.",
@@ -4349,60 +4380,60 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
4349
4380
  ],
4350
4381
  "schedules": []
4351
4382
  }
4352
- `,rC=t=>`node_modules/
4383
+ `,nC=t=>`node_modules/
4353
4384
 
4354
4385
  # Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
4355
4386
  .mcp.json
4356
4387
 
4357
4388
  .DS_Store
4358
- `;function zu(t={}){let e=CA.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:rC(r)},{path:"INSTANCE-LEARNINGS.md",content:ZA(o)},{path:"TURBOBASE-FEEDBACK.md",content:VA(o)},{path:".claude/settings.json",content:GA(r)},{path:`.claude/output-styles/${KA}.md`,content:WA},{path:".claude/skills/generate-types/SKILL.md",content:IA(n)},{path:".claude/skills/record-learning/SKILL.md",content:BA(o)},...ju,{path:".claude/hooks/session-start-refresh-types.sh",content:HA(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:XA,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:QA}];return r?[{path:"CLAUDE.md",content:LA(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:MA},{path:".claude/skills/ship-app/SKILL.md",content:UA},{path:".claude/skills/app-design/SKILL.md",content:tC},{path:".claude/skills/roles-and-permissions/SKILL.md",content:eC},{path:rw,content:JA,executable:!0},{path:".claude/hooks/format-edited-file.mjs",content:YA},...DA(),{path:"conduits/.gitkeep",content:Sa},{path:"turbobase/sync.json",content:Xb},{path:"turbobase/schedules.json",content:Qb},...Jb()]:[{path:"CLAUDE.md",content:AA},...s,{path:".claude/skills/mock-test/SKILL.md",content:OA},{path:".claude/skills/deploy/SKILL.md",content:NA},{path:"hooks/.gitkeep",content:Sa},{path:"conduits/.gitkeep",content:Sa},{path:"samples/.gitkeep",content:Sa},{path:"turbobase/sync.json",content:Xb},{path:"turbobase/schedules.json",content:Qb}]}import{promises as Mu}from"node:fs";import{dirname as nC,join as sr,resolve as aw}from"node:path";function ow(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var $s="bundle.json",$a="turbobase";function sw(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)}`,{cause: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 Du(a)}function Du(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(nw)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(nw)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function nw(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function iw(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",Ea="conduits",cw="processes",en="turbobase/sync.json",tn="turbobase/schedules.json";function Uu(t){let e=l=>{let u=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return u?u[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineProcess\s*[<(]/.test(t),o=/\bdefineHook\s*[<(]/.test(t);if(!r&&!o&&!n)return null;let s=e("id"),i=e("recordType");if(n){let l=e("source")??"standalone";return s?{id:s,recordType:"*",event:"invoke",source:l,extensionKind:"process"}:null}if(r){let l=e("on"),u=e("source");return!s||!i||!l||!u?null:{id:s,recordType:i,event:l,source:u,extensionKind:"conduit"}}let a=e("event"),c=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:c,extensionKind:"hook"}}function qu(t,e){if(!t||typeof t!="object")return null;let r=t;if(r.error!=="extension_id_mismatch")return null;let n=String(r.claimed??""),o=String(r.definitionId??"");return`${e?`${e}: `:""}refused (extension_id_mismatch) \u2014 the first \`id:\` literal in the file is '${n}', but the module defines '${o}'. Nothing was deployed.
4389
+ `;function Du(t={}){let e=IA.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:nC(r)},{path:"INSTANCE-LEARNINGS.md",content:VA(o)},{path:"TURBOBASE-FEEDBACK.md",content:HA(o)},{path:".claude/settings.json",content:JA(r)},{path:`.claude/output-styles/${WA}.md`,content:GA},{path:".claude/skills/generate-types/SKILL.md",content:OA(n)},{path:".claude/skills/record-learning/SKILL.md",content:ZA(o)},...zu,{path:".claude/hooks/session-start-refresh-types.sh",content:KA(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:QA,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:eC}];return r?[{path:"CLAUDE.md",content:jA(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:UA},{path:".claude/skills/ship-app/SKILL.md",content:qA},{path:".claude/skills/app-design/SKILL.md",content:rC},{path:".claude/skills/roles-and-permissions/SKILL.md",content:tC},{path:nw,content:YA,executable:!0},{path:".claude/hooks/format-edited-file.mjs",content:XA},...MA(),{path:"conduits/.gitkeep",content:Sa},{path:"turbobase/sync.json",content:Qb},{path:"turbobase/schedules.json",content:ew},...Yb()]:[{path:"CLAUDE.md",content:CA},...s,{path:".claude/skills/mock-test/SKILL.md",content:NA},{path:".claude/skills/deploy/SKILL.md",content:LA},{path:"hooks/.gitkeep",content:Sa},{path:"conduits/.gitkeep",content:Sa},{path:"samples/.gitkeep",content:Sa},{path:"turbobase/sync.json",content:Qb},{path:"turbobase/schedules.json",content:ew}]}import{promises as Uu}from"node:fs";import{dirname as oC,join as sr,resolve as cw}from"node:path";function sw(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var $s="bundle.json",$a="turbobase";function iw(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)}`,{cause: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 Mu(a)}function Mu(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(ow)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(ow)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function ow(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function aw(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",Ea="conduits",lw="processes",en="turbobase/sync.json",tn="turbobase/schedules.json";function qu(t){let e=l=>{let u=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return u?u[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineProcess\s*[<(]/.test(t),o=/\bdefineHook\s*[<(]/.test(t);if(!r&&!o&&!n)return null;let s=e("id"),i=e("recordType");if(n){let l=e("source")??"standalone";return s?{id:s,recordType:"*",event:"invoke",source:l,extensionKind:"process"}:null}if(r){let l=e("on"),u=e("source");return!s||!i||!l||!u?null:{id:s,recordType:i,event:l,source:u,extensionKind:"conduit"}}let a=e("event"),c=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:c,extensionKind:"hook"}}function Fu(t,e){if(!t||typeof t!="object")return null;let r=t;if(r.error!=="extension_id_mismatch")return null;let n=String(r.claimed??""),o=String(r.definitionId??"");return`${e?`${e}: `:""}refused (extension_id_mismatch) \u2014 the first \`id:\` literal in the file is '${n}', but the module defines '${o}'. Nothing was deployed.
4359
4390
  The deploy is stored under the first \`id:\` literal, and the runtime serves the module's own id, so the two have to agree.
4360
- Fix: write \`id: '${o}'\` as a string literal on the define call, and make sure no comment, constant, step or inlined helper above it carries an \`id:\` literal.`}function lw(t){return t==="written"?"new":t==="duplicate"?"replaced existing":t}function Fu(t){return/\bdefineProcess\s*[<(]/.test(t)?"could not read a quoted id \u2014 is it a defineProcess({...}) file? A process binds to no single record type; its steps carry their own.":/\bdefineConduit\s*[<(]/.test(t)?"could not read id / on / from.source / from.recordType \u2014 is it a defineConduit({...}) file?":"could not read id / recordType / event \u2014 is it a defineHook({...}) file?"}async function Ts(t){let e;try{e=await Mu.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 Ts(sr(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 Mu.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)}`,{cause:n})}}function oC(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function sC(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function iC(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 uw(t=process.cwd()){let e=aw(t),[r,n,o]=await Promise.all([Ts(sr(e,Ra)),Ts(sr(e,Ea)),Ts(sr(e,cw))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([Ta(sr(e,en),en).catch(()=>{}),Ta(sr(e,tn),tn).catch(()=>{})]);return s!==void 0||i!==void 0}async function dw(t=process.cwd(),e={}){let r=aw(t),n=ow(e.tenant),o=[],s=[];for(let c of[Ra,Ea,cw])for(let l of await Ts(sr(r,c))){let u=`${c}/${l}`,p=await Mu.readFile(sr(r,c,l),"utf8"),w=e.inline?await e.inline(p,nC(sr(r,c,l))):p,f=Uu(w);if(!f){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(w)&&s.push({file:u,reason:Fu(w)});continue}let m={id:f.id,kind:f.extensionKind,recordType:f.recordType,event:f.event,source:f.source,sourceCode:w};f.extensionKind==="conduit"?n.conduits.push(m):n.hooks.push(m),o.push(u)}let i=await Ta(sr(r,en),en);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${en} 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(oC(l));for(let l of Array.isArray(c.tables)?c.tables:[])n.sync.tables.push(sC(l));o.push(en)}let a=await Ta(sr(r,tn),tn);if(a!==void 0){let c=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(c===null)throw new Error(`${tn} must be a JSON array, or an object with a "schedules" array.`);for(let l of c)n.schedules.push(iC(l));o.push(tn)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(c=>c.event==="before_save").map(c=>c.id).sort(),{manifest:Du(n),contributed:o,unparsed:s}}import{promises as Vu}from"node:fs";import{resolve as pC}from"node:path";var aC="For app developers \u2014 adopt these";function pw(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 hw(t,e){let r=pw(t),n=pw(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 cC(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var B2=cC(aC);ys();or();var lC=t=>new Promise(e=>setTimeout(e,t));function mw(t){return t.stage==="completed"||t.stage==="failed"}function uC(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function dC(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(`
4361
- `))r(i)}return n}async function Bu(t,e={}){let r=e.sink??(w=>{process.stdout.write(`${w}
4362
- `)}),n=e.sleep??lC,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(w=>r(uC(w))),a=e.onPoll,c="",l="",u=w=>{a?.(w),w.stage!==l&&i(w),c=dC(w,c,r),l=w.stage},p=await t();if(u(p),mw(p))return p;for(let w=0;w<s;w+=1)if(await n(o),p=await t(),u(p),mw(p))return p;return p}var _=t=>{process.stdout.write(`${t}
4391
+ Fix: write \`id: '${o}'\` as a string literal on the define call, and make sure no comment, constant, step or inlined helper above it carries an \`id:\` literal.`}function uw(t){return t==="written"?"new":t==="duplicate"?"replaced existing":t}function Bu(t){return/\bdefineProcess\s*[<(]/.test(t)?"could not read a quoted id \u2014 is it a defineProcess({...}) file? A process binds to no single record type; its steps carry their own.":/\bdefineConduit\s*[<(]/.test(t)?"could not read id / on / from.source / from.recordType \u2014 is it a defineConduit({...}) file?":"could not read id / recordType / event \u2014 is it a defineHook({...}) file?"}async function Ts(t){let e;try{e=await Uu.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 Ts(sr(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 Uu.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)}`,{cause:n})}}function sC(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function iC(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function aC(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 dw(t=process.cwd()){let e=cw(t),[r,n,o]=await Promise.all([Ts(sr(e,Ra)),Ts(sr(e,Ea)),Ts(sr(e,lw))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([Ta(sr(e,en),en).catch(()=>{}),Ta(sr(e,tn),tn).catch(()=>{})]);return s!==void 0||i!==void 0}async function pw(t=process.cwd(),e={}){let r=cw(t),n=sw(e.tenant),o=[],s=[];for(let c of[Ra,Ea,lw])for(let l of await Ts(sr(r,c))){let u=`${c}/${l}`,p=await Uu.readFile(sr(r,c,l),"utf8"),w=e.inline?await e.inline(p,oC(sr(r,c,l))):p,f=qu(w);if(!f){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(w)&&s.push({file:u,reason:Bu(w)});continue}let m={id:f.id,kind:f.extensionKind,recordType:f.recordType,event:f.event,source:f.source,sourceCode:w};f.extensionKind==="conduit"?n.conduits.push(m):n.hooks.push(m),o.push(u)}let i=await Ta(sr(r,en),en);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${en} 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(sC(l));for(let l of Array.isArray(c.tables)?c.tables:[])n.sync.tables.push(iC(l));o.push(en)}let a=await Ta(sr(r,tn),tn);if(a!==void 0){let c=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(c===null)throw new Error(`${tn} must be a JSON array, or an object with a "schedules" array.`);for(let l of c)n.schedules.push(aC(l));o.push(tn)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(c=>c.event==="before_save").map(c=>c.id).sort(),{manifest:Mu(n),contributed:o,unparsed:s}}import{promises as Hu}from"node:fs";import{resolve as hC}from"node:path";var cC="For app developers \u2014 adopt these";function hw(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 mw(t,e){let r=hw(t),n=hw(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 lC(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var Z2=lC(cC);ys();or();var uC=t=>new Promise(e=>setTimeout(e,t));function fw(t){return t.stage==="completed"||t.stage==="failed"}function dC(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function pC(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(`
4392
+ `))r(i)}return n}async function Zu(t,e={}){let r=e.sink??(w=>{process.stdout.write(`${w}
4393
+ `)}),n=e.sleep??uC,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(w=>r(dC(w))),a=e.onPoll,c="",l="",u=w=>{a?.(w),w.stage!==l&&i(w),c=pC(w,c,r),l=w.stage},p=await t();if(u(p),fw(p))return p;for(let w=0;w<s;w+=1)if(await n(o),p=await t(),u(p),fw(p))return p;return p}var _=t=>{process.stdout.write(`${t}
4363
4394
  `)},D=t=>{process.stderr.write(`${t}
4364
- `)};function x(t){D(g.red(`turbobase: ${t}`)),process.exit(1)}var To=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function fw(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&Au(!1)}async function G(t){let e=await nr(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Lr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";x(`not signed in to ${Bt(t)}.${n} Run \`turbobase auth login --base-url ${Bt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&x("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),at())try{let n=await ct("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await la(n);let o=await nr();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 re(t,e,r){if(!(t instanceof se)||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 Zu(t,e,r){let n=r?Number(r):void 0;if(_a()){let s=Iu(e),i;try{i=await Bu(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 Bu(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 hC=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function mC(t){try{let e=await Vu.readFile(t,"utf8");return hC.exec(e)?.[1]??null}catch{return null}}var fC=/GENERATED by `turbobase project adopt`/,yw=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,gC=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function gw(t){let e=[],r=null;for(let n of t.split(`
4365
- `)){let o=yw.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=gC.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 yC(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
4395
+ `)};function k(t){D(g.red(`turbobase: ${t}`)),process.exit(1)}var $o=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function gw(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&Cu(!1)}async function Y(t){let e=await nr(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Lr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";k(`not signed in to ${Bt(t)}.${n} Run \`turbobase auth login --base-url ${Bt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&k("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),at())try{let n=await ct("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await la(n);let o=await nr();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}k(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function re(t,e,r){if(!(t instanceof se)||t.status!==403)return;t.body?.error==="approval_required"&&k(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),k(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Vu(t,e,r){let n=r?Number(r):void 0;if(_a()){let s=Ou(e),i;try{i=await Zu(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),k(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await Zu(t,{sink:_,intervalMs:n})}catch(s){k(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&k(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),_(`${e} ${o.stage}.`)}var mC=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function fC(t){try{let e=await Hu.readFile(t,"utf8");return mC.exec(e)?.[1]??null}catch{return null}}var gC=/GENERATED by `turbobase project adopt`/,bw=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,yC=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function yw(t){let e=[],r=null;for(let n of t.split(`
4396
+ `)){let o=bw.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=yC.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 bC(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
4366
4397
  `)).join(`
4367
4398
  `);return`## v${t.version}
4368
4399
 
4369
- ${e}`}function bC(t,e){let r=gw(t);if(r.length===0&&!fC.test(t))return null;let n=new Map(r.map(u=>[u.version,u])),o=[],s=0;for(let u of gw(e)){let p=n.get(u.version);n.delete(u.version);let w=new Set(u.items.map(m=>m.key)),f=u.items.map(m=>{let b=p?.items.find($=>$.key===m.key);return b?{...m,done:b.done,extra:b.extra}:m});for(let m of p?.items??[])w.has(m.key)||m.done||(f.push(m),s+=1);o.push({version:u.version,items:f})}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)=>hw(p.version,u.version));let i=e.split(`
4370
- `),a=i.findIndex(u=>yw.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
4400
+ ${e}`}function wC(t,e){let r=yw(t);if(r.length===0&&!gC.test(t))return null;let n=new Map(r.map(u=>[u.version,u])),o=[],s=0;for(let u of yw(e)){let p=n.get(u.version);n.delete(u.version);let w=new Set(u.items.map(m=>m.key)),f=u.items.map(m=>{let b=p?.items.find($=>$.key===m.key);return b?{...m,done:b.done,extra:b.extra}:m});for(let m of p?.items??[])w.has(m.key)||m.done||(f.push(m),s+=1);o.push({version:u.version,items:f})}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)=>mw(p.version,u.version));let i=e.split(`
4401
+ `),a=i.findIndex(u=>bw.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
4371
4402
  `).replace(/\s+$/,"");return{markdown:o.length===0?`${c}
4372
4403
  `:`${c}
4373
4404
 
4374
- ${o.map(yC).join(`
4405
+ ${o.map(bC).join(`
4375
4406
 
4376
4407
  `)}
4377
- `,carried:s}}function bw(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 G(e.baseUrl),o=pC(process.cwd(),e.out),s=e.since?.trim()||await mC(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(($,R)=>$+R.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. -->
4408
+ `,carried:s}}function ww(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 Y(e.baseUrl),o=hC(process.cwd(),e.out),s=e.since?.trim()||await fC(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),c=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});c.ok||k(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){_(`${r} ships no release notes to adopt from (nothing written).`);return}let u=l.releases.reduce(($,R)=>$+R.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. -->
4378
4409
 
4379
- `,f=await Vu.readFile(o,"utf8").catch(()=>null),m=l.markdown,b=0;if(f!==null&&f.trim()!==""){let $=bC(f,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>\`.`),m=$.markdown,b=$.carried}await Vu.writeFile(o,w+m,"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`:""}.`)})}import{existsSync as wC,mkdirSync as _C,readFileSync as vC,writeFileSync as Pa}from"node:fs";import{dirname as xC,join as kC}from"node:path";function ww(t){if(!t.startsWith(`---
4410
+ `,f=await Hu.readFile(o,"utf8").catch(()=>null),m=l.markdown,b=0;if(f!==null&&f.trim()!==""){let $=wC(f,l.markdown);$||k(`${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>\`.`),m=$.markdown,b=$.carried}await Hu.writeFile(o,w+m,"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`:""}.`)})}import{existsSync as _C,mkdirSync as vC,readFileSync as kC,writeFileSync as Pa}from"node:fs";import{dirname as xC,join as SC}from"node:path";function _w(t){if(!t.startsWith(`---
4380
4411
  `))return null;let e=t.indexOf(`
4381
4412
  ---
4382
- `,4);return e<0?null:t.slice(0,e+5)}function _w(t,e=ju){let r=[];for(let n of e){let o=kC(t,n.path);if(!wC(o)){_C(xC(o),{recursive:!0}),Pa(o,n.content),r.push({path:n.path,outcome:"written"});continue}let s=vC(o,"utf8");if(s===n.content){r.push({path:n.path,outcome:"unchanged"});continue}if(s.includes(Lu)){Pa(o,n.content),r.push({path:n.path,outcome:"updated"});continue}let i=ww(n.content);if(i!==null&&ww(s)===i){Pa(`${o}.bak`,s),Pa(o,n.content),r.push({path:n.path,outcome:"replaced-legacy"});continue}r.push({path:n.path,outcome:"kept-edited"})}return r}function vw(t){switch(t.outcome){case"written":return`${t.path}: written`;case"updated":return`${t.path}: updated to this CLI's version`;case"unchanged":return`${t.path}: current`;case"replaced-legacy":return`${t.path}: replaced an older platform copy (saved as SKILL.md.bak)`;case"kept-edited":return`${t.path}: NOT updated \u2014 it was edited in this project. Move your notes to INSTANCE-LEARNINGS.md and delete the file to receive the platform version.`}}or();var Rs=["suggested_kb_edit","kb_correction"];var SC=[{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 $C(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var i4=new Map(SC.map(t=>[$C(t.heading),t]));var a4=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 TC(t){return t.diff??!!t.dryRun}var RC={update_page:"append to the existing page",new_page:"create a NEW page"},zr=(t,e)=>` ${g.dim(t.padEnd(11))}${e}`,Sw=t=>t.ownerEmail??t.ownerId;function Ro(t){return!t.needsPageRef&&!t.blockedBy}var Aa=t=>g.green(t?` + ${t}`:" +"),EC=t=>g.red(t?` - ${t}`:" -"),Un=t=>g.dim(` ${t}`),PC=` ${g.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Hu=80;function AC(t){let e=[PC];t.target?(e.push(Un(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(EC(`visibility: ${t.target.visibility}`)),e.push(Aa("visibility: admin"))):e.push(Un(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(Un("title, slug, evidence: untouched")),e.push(Un("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(Un("turbobase.document \xB7 new")),e.push(Aa(`title: ${t.pageTitle}`)),e.push(Aa("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(Un('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(Un('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
4383
- `);for(let n of r.slice(0,Hu))e.push(Aa(n?` ${n}`:""));return r.length>Hu&&e.push(g.yellow(` \u2026 ${r.length-Hu} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function CC(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(zr("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:g.dim("new \u2014 no existing page matches"))),r.push(zr("action",Ro(n)?RC[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(zr("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(zr("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(zr("confidence",n.withdraws?g.red("WITHDRAWN from readers (text untouched)"):g.dim("untouched"))),n.supersedes&&r.push(zr("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(zr("blocked",g.red(`unpublished work on this page belongs to ${Sw(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(zr("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(zr("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&&Ro(n)&&r.push(...AC(n)),r.push("")}),r}function IC(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(Ro)} page(s)`,`${e(l=>l.action==="update_page"&&Ro(l))} appended`,`${e(l=>l.action==="new_page"&&Ro(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 OC(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?Sw(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 xw(t){if(t instanceof se){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.")}re(t,"extensions:deploy","learnings push-kb")}async function Es(t,e){let r;try{r=await ie("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof se&&o.status===404?D(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`.")):Jy(o)?D(g.yellow(kw(o))):D(g.yellow(`could not re-read the pushed markdown: ${kw(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return D(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`)),D(g.dim(n.join(" \xB7 "))),r}function kw(t){return t instanceof Error?t.message:String(t)}async function $w(t,e=r=>new K(r)){t.section&&!Rs.includes(t.section.trim())&&x(`unknown --section "${t.section}" \u2014 expected one of ${Rs.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&x("--limit must be a positive integer.");let r=await G(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 Es(n,t.app),i;try{i=await ie("reading the pending queue",()=>n.learningsPending(o))}catch(l){xw(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){D(`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}D(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(_(CC(i.items,{diff:TC(t)}).join(`
4384
- `)),_(IC(i.items)),t.dryRun){D(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(Ro);if(a.length===0){D(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(!at()){D(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 ct(`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"){D("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await ie("writing pages",()=>n.learningsPushKb(i.planToken,o));_(OC(l.applied,i.items).join(`
4385
- `))}catch(l){if(l instanceof se&&l.status===409){D(g.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),D(`re-run \`${To} kb push\` to review the current plan.`),process.exitCode=2;return}xw(l),D(g.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}or();var Eo=t=>new K(t);async function Po(t,e){let r=await G(t.baseUrl);return e(r)}async function Ca(t,e,r,n){return n.yes?!0:at()?await ct(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(D("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(D(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function NC(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function Tw(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function LC(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(`${Tw(g.bold(s.slug),e)} ${Tw(NC(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 Rw(t,e=Eo){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 Po(t,e),o;try{o=await ie("reading the knowledge base",()=>n.docsList(r))}catch(s){re(s,"docs:publish","read the knowledge base"),x(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}_(LC(o).join(`
4386
- `))}async function Ew(t,e,r=Eo){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 Po(e,r);if(!await Ca(`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 ie("publishing",()=>o.docsPublish(n))}catch(c){re(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&&(D(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),D(g.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Pw(t,e,r=Eo){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 Po(e,r);if(!await Ca(`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 ie("unpublishing",()=>o.docsUnpublish(n))}catch(c){re(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.`)),D(g.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(D(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Aw(t,e=Eo){let r=await Po(t,e),n;try{n=await ie("reading the releases",()=>r.docsVersions())}catch(o){re(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 Cw(t,e,r=Eo){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 Po(e,r);if(await Ca(`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 ie("rolling back",()=>o.docsRollback(n));_(g.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){re(i,"docs:publish","roll the knowledge base back"),x(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Iw(t,e,r=Eo){let n=(t??"").trim();n||x("name the page slug to delete. `turbobase kb list` shows them.");let o=await Po(e,r);if(await Ca(`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 ie("deleting",()=>o.docsDelete(n));_(g.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){re(i,"docs:publish","delete a page"),x(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}or();function jC(t){return t.diff??!!t.dryRun}function zC(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(`
4387
- `))r.push(` ${g.dim("|")} ${a}`)}r.push("")}),r}function DC(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 Ow(t,e=r=>new K(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&x("--limit must be a positive integer.");let r=await G(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 Es(n,t.app),i;try{i=await ie("reading the pending rules",()=>n.rulesPending(o))}catch(c){re(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){D(`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}D(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(_(zC(i.items,{diff:jC(t)}).join(`
4388
- `)),_(DC(i.items)),t.dryRun){D(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(!at()){D(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 ct(`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"){D("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await ie("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof se&&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).`)),D(g.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as ZC,readFile as VC,stat as HC}from"node:fs/promises";import{join as jw,resolve as KC}from"node:path";var Dr=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},MC=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function Nw(t){let e=t.replace(/^/,""),r=MC.exec(e);if(!r)throw new Dr("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=UC(n??""),i=s.name,a=s.description;if(!i)throw new Dr("SKILL.md frontmatter is missing required `name`");if(!a)throw new Dr("SKILL.md frontmatter is missing required `description`");let c=new Set(["name","description","license","version"]),l=Object.entries(s).filter(([p])=>!c.has(p));return{frontmatter:{name:i,description:a,...s.license?{license:s.license}:{},...s.version?{version:s.version}:{},...l.length?{extra:Object.fromEntries(l)}:{}},body:(o??"").trim()}}function UC(t){let e={},r=t.split(/\r?\n/),n=0;for(;n<r.length;){let o=r[n]??"";if(!o.trim()||o.trim().startsWith("#")){n+=1;continue}if(/^\s/.test(o))throw new Dr(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new Dr(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=FC(a),a===">"||a==="|"){let c=[];for(n+=1;n<r.length;){let l=r[n]??"";if(l.length===0||/^\s/.test(l))c.push(l.replace(/^\s{0,2}/,"")),n+=1;else break}e[i]=(a===">"?c.join(" "):c.join(`
4389
- `)).trim();continue}e[i]=qC(a),n+=1}return e}function qC(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function FC(t){let e=!1,r=!1;for(let n=0;n<t.length;n+=1){let o=t[n];if(o==="'"&&!r)e=!e;else if(o==='"'&&!e)r=!r;else if(o==="#"&&!e&&!r)return t.slice(0,n).trim()}return t}var BC=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function Lw(t){let e=[];t.length===0&&e.push("no skill files: expected <dir>/<slug>/SKILL.md"),t.length>50&&e.push(`${t.length} skill files; at most 50 per push`);let r=new Set;for(let n of t){let o=n.slug||"(unnamed)";BC.test(n.slug??"")||e.push(`${o}: the directory name must be lowercase letters, digits and hyphens (3\u201360 characters)`),r.has(n.slug)&&e.push(`${o}: two files share this slug`),r.add(n.slug),n.name?.trim()?n.name.length>200&&e.push(`${o}: \`name\` is over 200 characters`):e.push(`${o}: frontmatter \`name\` is empty`),n.description?.trim()?n.description.length>1024&&e.push(`${o}: \`description\` is over 1024 characters`):e.push(`${o}: frontmatter \`description\` is empty \u2014 it is what an MCP client reads to choose the skill`),n.body?.trim()?Buffer.byteLength(n.body,"utf8")>65536&&e.push(`${o}: the body is over ${65536/1024} KB`):e.push(`${o}: the body after the frontmatter is empty`)}return e}or();async function WC(t){let e=KC(t),r;try{r=(await ZC(e)).sort()}catch{x(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=jw(e,o,"SKILL.md");if(await HC(s).then(a=>a.isFile()).catch(()=>!1))try{let a=Nw(await VC(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof Dr&&x(`${jw(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var Ia={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},GC={slug_taken:"a skill with this slug exists and was not written by this app \u2014 rename the directory",owned_by_another_app:"another app owns a skill with this slug \u2014 rename the directory"};function JC(t){let e=[];for(let r of t.items){let n=r.action==="refused"?g.red(Ia.refused):r.action==="unchanged"?g.dim(Ia.unchanged):r.action==="new"?g.green(Ia.new):g.yellow(Ia.update),o=r.targetPublished?` ${g.yellow("[currently live]")}`:"";e.push(`${n} ${g.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&e.push(` ${g.red(GC[r.reason]??r.reason)}`)}for(let r of t.orphans)e.push(`${g.yellow("orphan")} ${g.bold(r)} \u2014 this app wrote it and no file names it now; left as it is (\`skills unpublish\` / \`skills delete\` to remove it)`);return e}async function zw(t,e=r=>new K(r)){t.app||x("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let r=await WC(t.from),n=Lw(r);n.length>0&&x(`nothing was sent:
4413
+ `,4);return e<0?null:t.slice(0,e+5)}function vw(t,e=zu){let r=[];for(let n of e){let o=SC(t,n.path);if(!_C(o)){vC(xC(o),{recursive:!0}),Pa(o,n.content),r.push({path:n.path,outcome:"written"});continue}let s=kC(o,"utf8");if(s===n.content){r.push({path:n.path,outcome:"unchanged"});continue}if(s.includes(ju)){Pa(o,n.content),r.push({path:n.path,outcome:"updated"});continue}let i=_w(n.content);if(i!==null&&_w(s)===i){Pa(`${o}.bak`,s),Pa(o,n.content),r.push({path:n.path,outcome:"replaced-legacy"});continue}r.push({path:n.path,outcome:"kept-edited"})}return r}function kw(t){switch(t.outcome){case"written":return`${t.path}: written`;case"updated":return`${t.path}: updated to this CLI's version`;case"unchanged":return`${t.path}: current`;case"replaced-legacy":return`${t.path}: replaced an older platform copy (saved as SKILL.md.bak)`;case"kept-edited":return`${t.path}: NOT updated \u2014 it was edited in this project. Move your notes to INSTANCE-LEARNINGS.md and delete the file to receive the platform version.`}}or();var Rs=["suggested_kb_edit","kb_correction"];var $C=[{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 TC(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var a4=new Map($C.map(t=>[TC(t.heading),t]));var c4=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 RC(t){return t.diff??!!t.dryRun}var EC={update_page:"append to the existing page",new_page:"create a NEW page"},zr=(t,e)=>` ${g.dim(t.padEnd(11))}${e}`,$w=t=>t.ownerEmail??t.ownerId;function To(t){return!t.needsPageRef&&!t.blockedBy}var Aa=t=>g.green(t?` + ${t}`:" +"),PC=t=>g.red(t?` - ${t}`:" -"),Un=t=>g.dim(` ${t}`),AC=` ${g.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Ku=80;function CC(t){let e=[AC];t.target?(e.push(Un(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(PC(`visibility: ${t.target.visibility}`)),e.push(Aa("visibility: admin"))):e.push(Un(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(Un("title, slug, evidence: untouched")),e.push(Un("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(Un("turbobase.document \xB7 new")),e.push(Aa(`title: ${t.pageTitle}`)),e.push(Aa("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(Un('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(Un('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
4414
+ `);for(let n of r.slice(0,Ku))e.push(Aa(n?` ${n}`:""));return r.length>Ku&&e.push(g.yellow(` \u2026 ${r.length-Ku} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function IC(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(zr("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:g.dim("new \u2014 no existing page matches"))),r.push(zr("action",To(n)?EC[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(zr("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(zr("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(zr("confidence",n.withdraws?g.red("WITHDRAWN from readers (text untouched)"):g.dim("untouched"))),n.supersedes&&r.push(zr("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(zr("blocked",g.red(`unpublished work on this page belongs to ${$w(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(zr("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(zr("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&&To(n)&&r.push(...CC(n)),r.push("")}),r}function OC(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(To)} page(s)`,`${e(l=>l.action==="update_page"&&To(l))} appended`,`${e(l=>l.action==="new_page"&&To(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 NC(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?$w(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 xw(t){if(t instanceof se){let e=t.body;t.status===403&&e?.reason==="admin_required"&&k("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&k("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}re(t,"extensions:deploy","learnings push-kb")}async function Es(t,e){let r;try{r=await ie("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof se&&o.status===404?D(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`.")):Yy(o)?D(g.yellow(Sw(o))):D(g.yellow(`could not re-read the pushed markdown: ${Sw(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return D(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`)),D(g.dim(n.join(" \xB7 "))),r}function Sw(t){return t instanceof Error?t.message:String(t)}async function Tw(t,e=r=>new K(r)){t.section&&!Rs.includes(t.section.trim())&&k(`unknown --section "${t.section}" \u2014 expected one of ${Rs.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await Y(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 Es(n,t.app),i;try{i=await ie("reading the pending queue",()=>n.learningsPending(o))}catch(l){xw(l),k(`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){D(`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}D(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(_(IC(i.items,{diff:RC(t)}).join(`
4415
+ `)),_(OC(i.items)),t.dryRun){D(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(To);if(a.length===0){D(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(!at()){D(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 ct(`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"){D("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await ie("writing pages",()=>n.learningsPushKb(i.planToken,o));_(NC(l.applied,i.items).join(`
4416
+ `))}catch(l){if(l instanceof se&&l.status===409){D(g.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),D(`re-run \`${$o} kb push\` to review the current plan.`),process.exitCode=2;return}xw(l),D(g.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}or();var Ro=t=>new K(t);async function Eo(t,e){let r=await Y(t.baseUrl);return e(r)}async function Ca(t,e,r,n){return n.yes?!0:at()?await ct(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(D("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(D(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function LC(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function Rw(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function jC(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(`${Rw(g.bold(s.slug),e)} ${Rw(LC(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 Ew(t,e=Ro){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Eo(t,e),o;try{o=await ie("reading the knowledge base",()=>n.docsList(r))}catch(s){re(s,"docs:publish","read the knowledge base"),k(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}_(jC(o).join(`
4417
+ `))}async function Pw(t,e,r=Ro){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let o=await Eo(e,r);if(!await Ca(`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 ie("publishing",()=>o.docsPublish(n))}catch(c){re(c,"docs:publish","publish a page"),k(`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&&(D(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),D(g.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Aw(t,e,r=Ro){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let o=await Eo(e,r);if(!await Ca(`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 ie("unpublishing",()=>o.docsUnpublish(n))}catch(c){re(c,"docs:publish","unpublish a page"),k(`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.`)),D(g.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(D(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Cw(t,e=Ro){let r=await Eo(t,e),n;try{n=await ie("reading the releases",()=>r.docsVersions())}catch(o){re(o,"docs:publish","read the knowledge-base releases"),k(`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 Iw(t,e,r=Ro){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await Eo(e,r);if(await Ca(`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 ie("rolling back",()=>o.docsRollback(n));_(g.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){re(i,"docs:publish","roll the knowledge base back"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Ow(t,e,r=Ro){let n=(t??"").trim();n||k("name the page slug to delete. `turbobase kb list` shows them.");let o=await Eo(e,r);if(await Ca(`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 ie("deleting",()=>o.docsDelete(n));_(g.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){re(i,"docs:publish","delete a page"),k(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}or();function zC(t){return t.diff??!!t.dryRun}function DC(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(`
4418
+ `))r.push(` ${g.dim("|")} ${a}`)}r.push("")}),r}function MC(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 Nw(t,e=r=>new K(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await Y(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 Es(n,t.app),i;try{i=await ie("reading the pending rules",()=>n.rulesPending(o))}catch(c){re(c,"extensions:deploy","read the pending rules"),k(`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){D(`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}D(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(_(DC(i.items,{diff:zC(t)}).join(`
4419
+ `)),_(MC(i.items)),t.dryRun){D(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(!at()){D(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 ct(`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"){D("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await ie("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof se&&c.status===409&&k("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),k(`push failed: ${c instanceof Error?c.message:String(c)}`)}_(g.green(`wrote ${i.items.length} draft rule(s).`)),D(g.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as VC,readFile as HC,stat as KC}from"node:fs/promises";import{join as zw,resolve as WC}from"node:path";var Dr=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},UC=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function Lw(t){let e=t.replace(/^/,""),r=UC.exec(e);if(!r)throw new Dr("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=qC(n??""),i=s.name,a=s.description;if(!i)throw new Dr("SKILL.md frontmatter is missing required `name`");if(!a)throw new Dr("SKILL.md frontmatter is missing required `description`");let c=new Set(["name","description","license","version"]),l=Object.entries(s).filter(([p])=>!c.has(p));return{frontmatter:{name:i,description:a,...s.license?{license:s.license}:{},...s.version?{version:s.version}:{},...l.length?{extra:Object.fromEntries(l)}:{}},body:(o??"").trim()}}function qC(t){let e={},r=t.split(/\r?\n/),n=0;for(;n<r.length;){let o=r[n]??"";if(!o.trim()||o.trim().startsWith("#")){n+=1;continue}if(/^\s/.test(o))throw new Dr(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new Dr(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=BC(a),a===">"||a==="|"){let c=[];for(n+=1;n<r.length;){let l=r[n]??"";if(l.length===0||/^\s/.test(l))c.push(l.replace(/^\s{0,2}/,"")),n+=1;else break}e[i]=(a===">"?c.join(" "):c.join(`
4420
+ `)).trim();continue}e[i]=FC(a),n+=1}return e}function FC(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function BC(t){let e=!1,r=!1;for(let n=0;n<t.length;n+=1){let o=t[n];if(o==="'"&&!r)e=!e;else if(o==='"'&&!e)r=!r;else if(o==="#"&&!e&&!r)return t.slice(0,n).trim()}return t}var ZC=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function jw(t){let e=[];t.length===0&&e.push("no skill files: expected <dir>/<slug>/SKILL.md"),t.length>50&&e.push(`${t.length} skill files; at most 50 per push`);let r=new Set;for(let n of t){let o=n.slug||"(unnamed)";ZC.test(n.slug??"")||e.push(`${o}: the directory name must be lowercase letters, digits and hyphens (3\u201360 characters)`),r.has(n.slug)&&e.push(`${o}: two files share this slug`),r.add(n.slug),n.name?.trim()?n.name.length>200&&e.push(`${o}: \`name\` is over 200 characters`):e.push(`${o}: frontmatter \`name\` is empty`),n.description?.trim()?n.description.length>1024&&e.push(`${o}: \`description\` is over 1024 characters`):e.push(`${o}: frontmatter \`description\` is empty \u2014 it is what an MCP client reads to choose the skill`),n.body?.trim()?Buffer.byteLength(n.body,"utf8")>65536&&e.push(`${o}: the body is over ${65536/1024} KB`):e.push(`${o}: the body after the frontmatter is empty`)}return e}or();async function GC(t){let e=WC(t),r;try{r=(await VC(e)).sort()}catch{k(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=zw(e,o,"SKILL.md");if(await KC(s).then(a=>a.isFile()).catch(()=>!1))try{let a=Lw(await HC(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof Dr&&k(`${zw(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var Ia={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},JC={slug_taken:"a skill with this slug exists and was not written by this app \u2014 rename the directory",owned_by_another_app:"another app owns a skill with this slug \u2014 rename the directory"};function YC(t){let e=[];for(let r of t.items){let n=r.action==="refused"?g.red(Ia.refused):r.action==="unchanged"?g.dim(Ia.unchanged):r.action==="new"?g.green(Ia.new):g.yellow(Ia.update),o=r.targetPublished?` ${g.yellow("[currently live]")}`:"";e.push(`${n} ${g.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&e.push(` ${g.red(JC[r.reason]??r.reason)}`)}for(let r of t.orphans)e.push(`${g.yellow("orphan")} ${g.bold(r)} \u2014 this app wrote it and no file names it now; left as it is (\`skills unpublish\` / \`skills delete\` to remove it)`);return e}async function Dw(t,e=r=>new K(r)){t.app||k("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let r=await GC(t.from),n=jw(r);n.length>0&&k(`nothing was sent:
4390
4421
  ${n.join(`
4391
- `)}`);let o=await G(t.baseUrl),s=e(o),i=async w=>{try{return await ie(w?"reading the plan":"writing the skills",()=>s.appSkillsPush(t.app,r,w))}catch(f){if(re(f,"extensions:deploy","push skill files"),f instanceof se&&f.status===404){let m=f.body;x(m?.error==="app_not_found"?String(m.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}x(`push failed: ${f instanceof Error?f.message:String(f)}`)}},a=await i(!0);_(JC(a).join(`
4392
- `));let c=a.items.filter(w=>w.action==="new"||w.action==="update").length,l=a.items.filter(w=>w.action==="refused").length;if(t.dryRun){D(g.dim("dry run \u2014 nothing was written.")),l>0&&(process.exitCode=1);return}let u=a;if(c>0){if(!t.yes){if(!at()){D(g.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await ct(`Write ${c} skill(s)${t.publish?" and publish them":" as drafts"}?`,[{value:"yes",label:"Yes"},{value:"no",label:"No \u2014 write nothing"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){D("aborted \u2014 nothing was written."),process.exitCode=1;return}}u=await i(!1)}let p=u.items.filter(w=>w.action==="new"||w.action==="update").map(w=>w.slug);if(_(`${p.length} written, ${u.items.filter(w=>w.action==="unchanged").length} unchanged, ${u.items.filter(w=>w.action==="refused").length} refused.`),t.publish&&p.length>0){let w;try{w=await ie("publishing",()=>s.skillsPublish(p))}catch(f){re(f,"skills:publish","publish the pushed skills"),x(`the skills were written as drafts but publishing failed: ${f instanceof Error?f.message:String(f)}`)}_(g.green(`published ${w.published.join(", ")} \u2014 live as of release ${w.version.version_no}.`))}else t.publish?_(g.dim("nothing changed \u2014 nothing to publish.")):p.length>0&&D(g.dim("They are DRAFT \u2014 nothing is served yet. Publish with `turbobase skills publish <slug>` (needs `skills:publish`), or re-run with --publish."));u.items.some(w=>w.action==="refused")&&(D(g.red("one or more skill files were refused and not written.")),process.exitCode=1)}or();var YC=["proposed","active","rejected"],XC=["mechanic","operator","learning","code-baseline"],Oa=t=>new K(t);async function Na(t,e){let r=await G(t.baseUrl);return e(r)}function Dw(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 QC(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 qw(t){let e=Dw(t.status,YC,"--status"),r=Dw(t.provenance,XC,"--provenance"),n=QC(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function Mw(t){return!!(t.provenance?.length||t.recordType||t.source)}var Fw=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function eI(t){return t.status==="active"?g.green("active"):t.status==="rejected"?g.dim("rejected"):g.yellow("proposed")}function tI(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 Bw(t){return[t.hookId,eI(t),t.provenance==="learning"?g.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),tI(t)]}async function Zw(t={},e=Oa){let r=await Na(t,e),n=qw(t),o;try{o=await r.proposals(n)}catch(i){re(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.
4393
- `+g.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}_(Ht(o.map(Bw),{head:Fw})),_(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 rI(t,e,r){return r.yes?!0:at()?await ct(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(D("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(D(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function nI(t){return!(t instanceof se)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Ku(t,e){nI(t)&&re(t,"extensions:deploy",e)}function Wu(t,e){let r=e instanceof se?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);D(Ne.error(`${g.bold(t)} \u2014 ${s}`))}async function Uw(t,e){try{let r=await t.proposalPromote(e);return _(Ne.success(`${g.bold(e)} ${g.dim(`${r.previousStatus} \u2192`)} ${g.green(r.status)}`)),!0}catch(r){return Ku(r,"promote a hook proposal"),Wu(e,r),!1}}async function Vw(t,e={},r=Oa){!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 Na(e,r);if(!e.auto){let u=0;for(let p of t)await Uw(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=qw({...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){re(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${Mw(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):`),_(Ht(a.map(Bw),{head:Fw})),i.length>0&&_(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){_(""),_(Ne.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Mw(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 rI(`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 Uw(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 Hw(t,e={},r=Oa){t.length===0&&x("retract: name at least one proposal id.");let n=await Na(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);_(Ne.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.yellow(i.status)}`)),o+=1}catch(i){Ku(i,"retract a hook proposal"),Wu(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 Kw(t,e={},r=Oa){t.length===0&&x("reject: name at least one proposal id.");let n=await Na(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);_(Ne.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.dim(i.status)}`)),o+=1}catch(i){Ku(i,"reject a hook proposal"),Wu(s,i)}o<t.length&&(process.exitCode=1)}or();var Gu=t=>new K(t);async function oI(t,e){let r=await G(t.baseUrl);return e(r)}function sI(t){return!(t instanceof se)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function iI(t,e){let r=e instanceof se?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{not_found:"no extension with that id",wrong_kind:"that id is not an extension this instance manages",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",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",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);D(Ne.error(`${g.bold(t)} \u2014 ${s}`))}async function Ju(t,e,r,n,o,s,i){e.length===0&&x(`${t}: name at least one extension id.`);let a=await oI(r,n),c=[];for(let l of e)try{let u=await o(a,l);c.push(u),r.json||_(s(u))}catch(u){sI(u)&&re(u,"extensions:deploy",`${t} an extension`),iI(l,u)}if(r.json)_(JSON.stringify(c,null,2));else{let l=i(c.length);l&&_(g.dim(l))}c.length<e.length&&(process.exitCode=1)}async function Ww(t,e={},r=Gu){await Ju("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>Ne.success(`${g.bold(n.id)} ${g.dim(`${n.previousStatus} \u2192`)} ${g.yellow(n.status)}`),n=>n>0?" definition kept \u2014 the loader drops it on its next reload. Put it back with `turbobase ext enable <id>`.":null)}async function Gw(t,e={},r=Gu){await Ju("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>Ne.success(`${g.bold(n.id)} ${g.dim(`${n.previousStatus} \u2192`)} ${g.green(n.status)}`),n=>n>0?" the loader compiles it on its next reload.":null)}async function Jw(t,e={},r=Gu){await Ju("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>Ne.success(`${g.bold(n.id)} ${g.dim(`${n.previousStatus} \u2192`)} ${g.dim(n.status)}`),n=>n>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}or();var Ao=t=>new K(t);async function Co(t,e){let r=await G(t.baseUrl);return e(r)}async function La(t,e,r,n){return n.yes?!0:at()?await ct(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(D("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(D(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function aI(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function Yw(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function cI(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(`${Yw(g.bold(s.slug),e)} ${Yw(aI(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 Xw(t,e=Ao){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 Co(t,e),o;try{o=await ie("reading the skills",()=>n.skillsList(r))}catch(s){re(s,"skills:publish","read the instance skills"),x(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}_(cI(o).join(`
4394
- `))}async function Qw(t,e,r=Ao){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 Co(e,r);if(!await La(`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 ie("publishing",()=>o.skillsPublish(n))}catch(a){re(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&&(D(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),D(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function e_(t,e,r=Ao){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 Co(e,r);if(!await La(`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 ie("unpublishing",()=>o.skillsUnpublish(n))}catch(a){re(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.`)),D(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(D(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function t_(t,e,r=Ao){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 Co(e,r);if(await La(`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 ie("rolling back",()=>o.skillsRollback(n));_(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){re(i,"skills:publish","roll back a skills release"),x(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function r_(t,e=Ao){let r=await Co(t,e),n;try{n=await ie("reading the releases",()=>r.skillsReleases())}catch(o){re(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){D("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 n_(t,e,r=Ao){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 Co(e,r);if(!await La(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
4422
+ `)}`);let o=await Y(t.baseUrl),s=e(o),i=async w=>{try{return await ie(w?"reading the plan":"writing the skills",()=>s.appSkillsPush(t.app,r,w))}catch(f){if(re(f,"extensions:deploy","push skill files"),f instanceof se&&f.status===404){let m=f.body;k(m?.error==="app_not_found"?String(m.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}k(`push failed: ${f instanceof Error?f.message:String(f)}`)}},a=await i(!0);_(YC(a).join(`
4423
+ `));let c=a.items.filter(w=>w.action==="new"||w.action==="update").length,l=a.items.filter(w=>w.action==="refused").length;if(t.dryRun){D(g.dim("dry run \u2014 nothing was written.")),l>0&&(process.exitCode=1);return}let u=a;if(c>0){if(!t.yes){if(!at()){D(g.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await ct(`Write ${c} skill(s)${t.publish?" and publish them":" as drafts"}?`,[{value:"yes",label:"Yes"},{value:"no",label:"No \u2014 write nothing"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){D("aborted \u2014 nothing was written."),process.exitCode=1;return}}u=await i(!1)}let p=u.items.filter(w=>w.action==="new"||w.action==="update").map(w=>w.slug);if(_(`${p.length} written, ${u.items.filter(w=>w.action==="unchanged").length} unchanged, ${u.items.filter(w=>w.action==="refused").length} refused.`),t.publish&&p.length>0){let w;try{w=await ie("publishing",()=>s.skillsPublish(p))}catch(f){re(f,"skills:publish","publish the pushed skills"),k(`the skills were written as drafts but publishing failed: ${f instanceof Error?f.message:String(f)}`)}_(g.green(`published ${w.published.join(", ")} \u2014 live as of release ${w.version.version_no}.`))}else t.publish?_(g.dim("nothing changed \u2014 nothing to publish.")):p.length>0&&D(g.dim("They are DRAFT \u2014 nothing is served yet. Publish with `turbobase skills publish <slug>` (needs `skills:publish`), or re-run with --publish."));u.items.some(w=>w.action==="refused")&&(D(g.red("one or more skill files were refused and not written.")),process.exitCode=1)}or();var XC=["proposed","active","rejected"],QC=["mechanic","operator","learning","code-baseline"],Oa=t=>new K(t);async function Na(t,e){let r=await Y(t.baseUrl);return e(r)}function Mw(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)||k(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function eI(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&k("--limit must be a positive number."),Math.floor(e)}function Fw(t){let e=Mw(t.status,XC,"--status"),r=Mw(t.provenance,QC,"--provenance"),n=eI(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function Uw(t){return!!(t.provenance?.length||t.recordType||t.source)}var Bw=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function tI(t){return t.status==="active"?g.green("active"):t.status==="rejected"?g.dim("rejected"):g.yellow("proposed")}function rI(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 Zw(t){return[t.hookId,tI(t),t.provenance==="learning"?g.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),rI(t)]}async function Vw(t={},e=Oa){let r=await Na(t,e),n=Fw(t),o;try{o=await r.proposals(n)}catch(i){re(i,"extensions:deploy","list hook proposals"),k(`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.
4424
+ `+g.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}_(Ht(o.map(Zw),{head:Bw})),_(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 nI(t,e,r){return r.yes?!0:at()?await ct(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(D("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(D(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function oI(t){return!(t instanceof se)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Wu(t,e){oI(t)&&re(t,"extensions:deploy",e)}function Gu(t,e){let r=e instanceof se?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);D(Ne.error(`${g.bold(t)} \u2014 ${s}`))}async function qw(t,e){try{let r=await t.proposalPromote(e);return _(Ne.success(`${g.bold(e)} ${g.dim(`${r.previousStatus} \u2192`)} ${g.green(r.status)}`)),!0}catch(r){return Wu(r,"promote a hook proposal"),Gu(e,r),!1}}async function Hw(t,e={},r=Oa){!e.auto&&t.length===0&&k("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&k("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&k("promote: --apply / --all only mean something with --auto.");let n=await Na(e,r);if(!e.auto){let u=0;for(let p of t)await qw(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=Fw({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&k("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")&&k("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(u){re(u,"extensions:deploy","list hook proposals"),k(`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${Uw(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):`),_(Ht(a.map(Zw),{head:Bw})),i.length>0&&_(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){_(""),_(Ne.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Uw(o)&&!e.all&&k(`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 nI(`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 qw(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 Kw(t,e={},r=Oa){t.length===0&&k("retract: name at least one proposal id.");let n=await Na(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);_(Ne.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.yellow(i.status)}`)),o+=1}catch(i){Wu(i,"retract a hook proposal"),Gu(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 Ww(t,e={},r=Oa){t.length===0&&k("reject: name at least one proposal id.");let n=await Na(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);_(Ne.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.dim(i.status)}`)),o+=1}catch(i){Wu(i,"reject a hook proposal"),Gu(s,i)}o<t.length&&(process.exitCode=1)}or();var Ju=t=>new K(t);async function sI(t,e){let r=await Y(t.baseUrl);return e(r)}function iI(t){return!(t instanceof se)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function aI(t,e){let r=e instanceof se?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{not_found:"no extension with that id",wrong_kind:"that id is not an extension this instance manages",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",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",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);D(Ne.error(`${g.bold(t)} \u2014 ${s}`))}async function Yu(t,e,r,n,o,s,i){e.length===0&&k(`${t}: name at least one extension id.`);let a=await sI(r,n),c=[];for(let l of e)try{let u=await o(a,l);c.push(u),r.json||_(s(u))}catch(u){iI(u)&&re(u,"extensions:deploy",`${t} an extension`),aI(l,u)}if(r.json)_(JSON.stringify(c,null,2));else{let l=i(c.length);l&&_(g.dim(l))}c.length<e.length&&(process.exitCode=1)}async function Gw(t,e={},r=Ju){await Yu("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>Ne.success(`${g.bold(n.id)} ${g.dim(`${n.previousStatus} \u2192`)} ${g.yellow(n.status)}`),n=>n>0?" definition kept \u2014 the loader drops it on its next reload. Put it back with `turbobase ext enable <id>`.":null)}async function Jw(t,e={},r=Ju){await Yu("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>Ne.success(`${g.bold(n.id)} ${g.dim(`${n.previousStatus} \u2192`)} ${g.green(n.status)}`),n=>n>0?" the loader compiles it on its next reload.":null)}async function Yw(t,e={},r=Ju){await Yu("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>Ne.success(`${g.bold(n.id)} ${g.dim(`${n.previousStatus} \u2192`)} ${g.dim(n.status)}`),n=>n>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}or();var Po=t=>new K(t);async function Ao(t,e){let r=await Y(t.baseUrl);return e(r)}async function La(t,e,r,n){return n.yes?!0:at()?await ct(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(D("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(D(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function cI(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function Xw(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function lI(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(`${Xw(g.bold(s.slug),e)} ${Xw(cI(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 Qw(t,e=Po){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Ao(t,e),o;try{o=await ie("reading the skills",()=>n.skillsList(r))}catch(s){re(s,"skills:publish","read the instance skills"),k(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}_(lI(o).join(`
4425
+ `))}async function e_(t,e,r=Po){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await Ao(e,r);if(!await La(`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 ie("publishing",()=>o.skillsPublish(n))}catch(a){re(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(D(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),D(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function t_(t,e,r=Po){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await Ao(e,r);if(!await La(`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 ie("unpublishing",()=>o.skillsUnpublish(n))}catch(a){re(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),D(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(D(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function r_(t,e,r=Po){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await Ao(e,r);if(await La(`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 ie("rolling back",()=>o.skillsRollback(n));_(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){re(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function n_(t,e=Po){let r=await Ao(t,e),n;try{n=await ie("reading the releases",()=>r.skillsReleases())}catch(o){re(o,"skills:publish","read the skills releases"),k(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){D("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 o_(t,e,r=Po){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await Ao(e,r);if(!await La(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
4395
4426
  ${n.join(`
4396
- `)}`,"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 ie(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof se&&u.status===404){a.push(l);continue}i.length>0&&D(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),re(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&&D(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(D(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as o_}from"node:fs";import{join as lI,relative as uI,resolve as dI,sep as pI}from"node:path";var hI=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),mI=new Set([".mcp.json",".env"]);function fI(t){return mI.has(t)||t.startsWith(".env.")&&t!==".env.example"}function gI(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function yI(t){return t.includes(0)}async function Yu(t){let e=dI(t),r={},n=[],o=[],s=[];async function i(a){let c=await o_.readdir(a,{withFileTypes:!0});for(let l of c){let u=lI(a,l.name);if(hI.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=uI(e,u).split(pI).join("/");if(fI(l.name)){o.push(p);continue}let w=await o_.readFile(u);if(!gI(w)){n.push(p);continue}yI(w)&&s.push(p),r[p]=w.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as bI}from"node:crypto";var wI="/_tb/app-assets",_I=16,vI=/^[0-9a-f]{32}$/;function s_(){return bI(_I).toString("hex")}function xI(t){return vI.test(t)}function i_(t){if(!xI(t))throw new Error(`not a build id: ${t}`);return`${wI}/${t}/`}var a_=7;Qu();var ed=50*1024*1024;import ja from"node:fs/promises";import Ps from"node:path";var td={esbuild:"0.28.1","isolated-vm":"6.1.2"},rd="@turbobase/isolated-vm-prebuilds";function nd(t,e){return`${t}-${e}`}function od(t=process.versions){return`abi${t.modules}`}var c_=["darwin-x64","win32-arm64"];async function l_(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=nd(e,r),o=Ps.join(t.home,"node_modules"),s=Ps.join(o,...rd.split("/"),"prebuilds",n),i=Ps.join(o,"isolated-vm","prebuilds",n),a;try{a=await ja.readdir(s)}catch{return[]}let c=[];await ja.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=Ps.join(i,l);try{await ja.copyFile(Ps.join(s,l),u,ja.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as kI}from"node:os";import{join as u_}from"node:path";import{promises as sd}from"node:fs";function p_(){let t=process.env.TURBOBASE_HOME??u_(kI(),".turbobase");return{dir:t,file:u_(t,"sandboxes.json")}}var SI={s:1e3,m:6e4,h:36e5,d:864e5};function $I(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*SI[e[2]]}function TI(t,e=Date.now()){return new Date(e+$I(t)).toISOString()}function RI(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function EI(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 PI(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 AI="[REDACTED]",As=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},id=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 CI(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new id(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:AI:n[o]=s}return n}function II(t,e,r){return e.map(n=>CI(t,n,r))}var d_=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),OI=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function NI(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 ad(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 OI)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=NI(t);if(!d_.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...d_].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function LI(t,e=jI){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function jI(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function zI(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function DI(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function cd(){let{file:t}=p_();try{let e=await sd.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function h_(t){let{dir:e,file:r}=p_();await sd.mkdir(e,{recursive:!0}),await sd.writeFile(r,`${JSON.stringify(t,null,2)}
4397
- `,{mode:384})}async function MI(t){let e=await cd();e.push(t),await h_(e)}async function m_(t){let e=await cd(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await h_(e),n??null}async function za(){return cd()}function ld(t,e=Date.now()){let r=[],n=[];for(let o of t)RI(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function f_(t,e){ad(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new As(r);let n=EI(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>LI(l)))(e.fromTenant),i=zI(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=PI(l.rows,n),p=II(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:TI(e.ttl,o),sampleFraction:n,url:DI(s,e.baseUrl)};return await MI(c),c}async function g_(t,e){ad(t.target());let n=(await za()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await m_(e),n):null}async function ud(t,e=Date.now()){ad(t.target());let r=await za(),{expired:n}=ld(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await m_(s.name),o.push(s)}return o}var Cs={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],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"}},yV=Object.keys(Cs).filter(t=>Cs[t].mintable);var _V=Cs.pat.prefix,UI=Object.entries(Cs).map(([t,e])=>[e.prefix,t]),qI=/^[A-Za-z0-9_-]{20,}$/;function FI(t){if(typeof t!="string")return null;for(let[e,r]of UI)if(t.startsWith(e)&&qI.test(t.slice(e.length)))return r;return null}function y_(t){return FI(t)==="pat"}ys();var BI=8e3,ZI={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 VI(t){return ZI[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function HI(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(BI)})}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 b_(t){return t.state==="accepted"?ot()?g.green("accepted"):"accepted":t.state==="rejected"?ot()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:ot()?g.yellow("unreachable"):"unreachable"}async function w_(t={},e=fetch){let r=await Lr(),{file:n}=ca();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),D(g.dim(`no sign-ins stored in ${n}.`));return}let o=await nr(),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 HI(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(ot())_(Ht(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),b_(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${b_(i.check)} (updated ${i.updatedAt})`);D(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(D(g.red(`${i.baseUrl}: ${VI(i.check.reason)}.`)),D(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"&&D(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||D("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function CF(t){let e=await Lr();e.length===0&&x("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),at()||x("this command needs an explicit <base-url> in a non-interactive shell.");try{return await ct(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{x("cancelled.")}}async function IF(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 OF(t){D(""),D("Sharing is ON. Two things reach the Turbobase product team from this instance:"),D(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),D(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),D(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),D(" about OUR platform, with instance name, user names and ids masked before they leave."),D(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),D("")}async function NF(t,e,r){let n=await Vy({baseUrl:t,token:e}),o=(await Lr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),OF(n.baseUrl),!r)return;let s=await IF(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(D(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),D(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),D(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?D(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):D(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function LF(t){let e=await Su(await vs(t),Zr(t)),r=Uu(e);return r||x(`${t}: ${Fu(e)}`),{...r,sourceCode:e}}async function io(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Zr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function NR(t,e){if(jR(t)!==".gitignore")return io(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return io(t,e.content,e.executable,e.mode);let n=ew(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function Cg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;x(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Ol(t){process.exit(t)}function jF(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 zF(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 DF(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 LR(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function zg({includeInternal:t=!0}={}){let e=new oy;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.48.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Cu()}
4398
- `),e.hook("preAction",(d,h)=>{fw(e.opts(),h.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 h=Bt(d.baseUrl);d.token||x(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
4399
- ${To} auth login --base-url ${h} --token tb_pat_\u2026`),y_(d.token)||x("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await NF(h,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=>w_({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 h=d??await CF("Pick the active instance:"),v=await la(h);if(!v){let T=await Lr();x(`no stored sign-in for ${Bt(h)}.`+(T.length?` Stored: ${T.map(k=>k.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Bt(h)} --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 Lr();for(let k of T)await bu(k.baseUrl);_(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await bu(d.baseUrl);h||x(d.baseUrl?`no stored sign-in for ${Bt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await nr();_(`signed out of ${h}.`+(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:h,token:v}=await G(d.baseUrl),T;try{T=await Dn({baseUrl:h,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)){D("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 Dn({baseUrl:h,token:v,recordsOnly:!0})}catch(E){x(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else x(`types generation failed: ${S}`)}let k=fe(process.cwd(),d.out);await be.writeFile(k,T,"utf8"),_(`wrote ${k} (${T.split(`
4400
- `).length} lines).`)}),bw(n),n.command("skills").description("Rewrite the platform's own skills in .claude/skills from this CLI (never the project's own).").option("--dir <path>","Project directory",".").action(d=>{let h=_w(fe(process.cwd(),d.dir));for(let v of h)_(vw(v))}),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:h,token:v}=await G(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(`${h}/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 E=((await y.json()).markdown??"").trim(),I=fe(process.cwd(),d.out),j=d.records?` records=${d.records}`:"",M=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${j} \u2014 do not edit; re-run to refresh. -->
4427
+ `)}`,"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 ie(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof se&&u.status===404){a.push(l);continue}i.length>0&&D(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),re(u,"skills:publish","delete a skill"),k(`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&&D(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(D(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as s_}from"node:fs";import{join as uI,relative as dI,resolve as pI,sep as hI}from"node:path";var mI=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),fI=new Set([".mcp.json",".env"]);function gI(t){return fI.has(t)||t.startsWith(".env.")&&t!==".env.example"}function yI(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function bI(t){return t.includes(0)}async function Xu(t){let e=pI(t),r={},n=[],o=[],s=[];async function i(a){let c=await s_.readdir(a,{withFileTypes:!0});for(let l of c){let u=uI(a,l.name);if(mI.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=dI(e,u).split(hI).join("/");if(gI(l.name)){o.push(p);continue}let w=await s_.readFile(u);if(!yI(w)){n.push(p);continue}bI(w)&&s.push(p),r[p]=w.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as wI}from"node:crypto";var _I="/_tb/app-assets",vI=16,kI=/^[0-9a-f]{32}$/;function i_(){return wI(vI).toString("hex")}function xI(t){return kI.test(t)}function a_(t){if(!xI(t))throw new Error(`not a build id: ${t}`);return`${_I}/${t}/`}var c_=7;ed();var td=50*1024*1024;import ja from"node:fs/promises";import Ps from"node:path";var rd={esbuild:"0.28.1","isolated-vm":"6.1.2"},nd="@turbobase/isolated-vm-prebuilds";function od(t,e){return`${t}-${e}`}function sd(t=process.versions){return`abi${t.modules}`}var l_=["darwin-x64","win32-arm64"];async function u_(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=od(e,r),o=Ps.join(t.home,"node_modules"),s=Ps.join(o,...nd.split("/"),"prebuilds",n),i=Ps.join(o,"isolated-vm","prebuilds",n),a;try{a=await ja.readdir(s)}catch{return[]}let c=[];await ja.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=Ps.join(i,l);try{await ja.copyFile(Ps.join(s,l),u,ja.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as SI}from"node:os";import{join as d_}from"node:path";import{promises as id}from"node:fs";function h_(){let t=process.env.TURBOBASE_HOME??d_(SI(),".turbobase");return{dir:t,file:d_(t,"sandboxes.json")}}var $I={s:1e3,m:6e4,h:36e5,d:864e5};function TI(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*$I[e[2]]}function RI(t,e=Date.now()){return new Date(e+TI(t)).toISOString()}function EI(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function PI(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 AI(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 CI="[REDACTED]",As=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},ad=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 II(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new ad(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:CI:n[o]=s}return n}function OI(t,e,r){return e.map(n=>II(t,n,r))}var p_=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),NI=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function LI(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 cd(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 NI)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=LI(t);if(!p_.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...p_].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function jI(t,e=zI){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function zI(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function DI(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function MI(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function ld(){let{file:t}=h_();try{let e=await id.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function m_(t){let{dir:e,file:r}=h_();await id.mkdir(e,{recursive:!0}),await id.writeFile(r,`${JSON.stringify(t,null,2)}
4428
+ `,{mode:384})}async function UI(t){let e=await ld();e.push(t),await m_(e)}async function f_(t){let e=await ld(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await m_(e),n??null}async function za(){return ld()}function ud(t,e=Date.now()){let r=[],n=[];for(let o of t)EI(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function g_(t,e){cd(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new As(r);let n=PI(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>jI(l)))(e.fromTenant),i=DI(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=AI(l.rows,n),p=OI(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:RI(e.ttl,o),sampleFraction:n,url:MI(s,e.baseUrl)};return await UI(c),c}async function y_(t,e){cd(t.target());let n=(await za()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await f_(e),n):null}async function dd(t,e=Date.now()){cd(t.target());let r=await za(),{expired:n}=ud(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await f_(s.name),o.push(s)}return o}var Cs={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],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"}},bV=Object.keys(Cs).filter(t=>Cs[t].mintable);var vV=Cs.pat.prefix,qI=Object.entries(Cs).map(([t,e])=>[e.prefix,t]),FI=/^[A-Za-z0-9_-]{20,}$/;function BI(t){if(typeof t!="string")return null;for(let[e,r]of qI)if(t.startsWith(e)&&FI.test(t.slice(e.length)))return r;return null}function b_(t){return BI(t)==="pat"}ys();var ZI=8e3,VI={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 HI(t){return VI[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function KI(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(ZI)})}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 w_(t){return t.state==="accepted"?ot()?g.green("accepted"):"accepted":t.state==="rejected"?ot()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:ot()?g.yellow("unreachable"):"unreachable"}async function __(t={},e=fetch){let r=await Lr(),{file:n}=ca();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),D(g.dim(`no sign-ins stored in ${n}.`));return}let o=await nr(),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 KI(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(ot())_(Ht(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),w_(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${w_(i.check)} (updated ${i.updatedAt})`);D(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(D(g.red(`${i.baseUrl}: ${HI(i.check.reason)}.`)),D(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"&&D(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||D("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function IF(t){let e=await Lr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),at()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await ct(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function OF(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 NF(t){D(""),D("Sharing is ON. Two things reach the Turbobase product team from this instance:"),D(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),D(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),D(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),D(" about OUR platform, with instance name, user names and ids masked before they leave."),D(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),D("")}async function LF(t,e,r){let n=await Hy({baseUrl:t,token:e}),o=(await Lr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),NF(n.baseUrl),!r)return;let s=await OF(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(D(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),D(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),D(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?D(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):D(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function jF(t){let e=await $u(await vs(t),Zr(t)),r=qu(e);return r||k(`${t}: ${Bu(e)}`),{...r,sourceCode:e}}async function io(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Zr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function LR(t,e){if(zR(t)!==".gitignore")return io(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return io(t,e.content,e.executable,e.mode);let n=tw(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function Ig(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Ol(t){process.exit(t)}function zF(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 DF(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 MF(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 jR(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Dg({includeInternal:t=!0}={}){let e=new sy;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.50.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Iu()}
4429
+ `),e.hook("preAction",(d,h)=>{gw(e.opts(),h.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 h=Bt(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
4430
+ ${$o} auth login --base-url ${h} --token tb_pat_\u2026`),b_(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await LF(h,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=>__({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 h=d??await IF("Pick the active instance:"),v=await la(h);if(!v){let T=await Lr();k(`no stored sign-in for ${Bt(h)}.`+(T.length?` Stored: ${T.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Bt(h)} --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 Lr();for(let S of T)await wu(S.baseUrl);_(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await wu(d.baseUrl);h||k(d.baseUrl?`no stored sign-in for ${Bt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await nr();_(`signed out of ${h}.`+(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:h,token:v}=await Y(d.baseUrl),T;try{T=await Dn({baseUrl:h,token:v,recordsOnly:d.recordsOnly})}catch(y){let x=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(x)){D("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 Dn({baseUrl:h,token:v,recordsOnly:!0})}catch(E){k(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else k(`types generation failed: ${x}`)}let S=fe(process.cwd(),d.out);await be.writeFile(S,T,"utf8"),_(`wrote ${S} (${T.split(`
4431
+ `).length} lines).`)}),ww(n),n.command("skills").description("Rewrite the platform's own skills in .claude/skills from this CLI (never the project's own).").option("--dir <path>","Project directory",".").action(d=>{let h=vw(fe(process.cwd(),d.dir));for(let v of h)_(kw(v))}),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:h,token:v}=await Y(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let S=T.toString(),y=await fetch(`${h}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});y.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let E=((await y.json()).markdown??"").trim(),I=fe(process.cwd(),d.out),j=d.records?` records=${d.records}`:"",M=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${j} \u2014 do not edit; re-run to refresh. -->
4401
4432
 
4402
4433
  `;await be.writeFile(I,M+(E?`${E}
4403
4434
  `:`(no grounding available yet)
4404
- `),"utf8"),_(`wrote ${I}${E?"":" (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 (${Rs.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=>$w(d)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>Rw(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,h)=>Ew(d,h)),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,h)=>Pw(d,h)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Aw(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,h)=>Cw(d,h)),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,h)=>Iw(d,h)),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("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>(d.publish&&!d.from&&x("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),d.from?zw({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):Ow(d))),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>Xw(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,h)=>Qw(d,h)),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,h)=>e_(d,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>r_(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,h)=>t_(d,h)),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,h)=>n_(d,h));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 h;try{h=_r("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=fe(process.cwd(),h.relativePath);await io(v,h.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 h;try{h=_r("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=fe(process.cwd(),h.relativePath);await io(v,h.content)==="skipped"&&x(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async d=>{let h;try{h=_r("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(k){x(k instanceof Error?k.message:String(k))}let v=fe(process.cwd(),h.relativePath);await io(v,h.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,h)=>{let v=Cg(h.reporter),T=await vs(fe(process.cwd(),d)),k=fe(process.cwd(),h.samples),y=await _s(k);y.length===0&&!v&&_(`no samples found under ${k} \u2014 add JSON fixtures to dry-run against.`);let S;try{S=await ya(T,y.map(j=>j.fixture),{resolveDir:Zr(fe(process.cwd(),d))})}catch(j){x(`bundle failed: ${j instanceof Error?j.message:String(j)}`)}if(v){let j=jF(S);_(wa(j,v)),Ol(j.cases.some(M=>M.status==="failed")?1:0)}let E=0;for(let j of S){let M=j.pass?g.green("PASS"):g.red("FAIL");j.pass||(E+=1);let V=j.error?` (error: ${j.error})`:j.observed!==j.expected?` (expected ${j.expected}, observed ${j.observed})`:j.rejection?` (rejected: ${j.rejection.code??"rejected"})`:"";_(` ${M} ${j.name}${V}`)}let I=`${S.length-E}/${S.length} sample(s) passed.`;_(`
4405
- ${E===0?g.green(I):g.yellow(I)}`),Ol(E>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,h)=>{if(h.to){let S=await Ig(),{baseUrl:E,token:I}=await G(h.baseUrl),j=new K({baseUrl:E,token:I});try{let M=await ie(`applying bundle to ${h.to}`,()=>j.configApply(S,{prune:h.prune}));_(`applied bundle to ${h.to}: +${M.applied.add} ~${M.applied.change} -${M.applied.destroy}`+(M.backfillsQueued.length?` (${M.backfillsQueued.length} backfill(s) queued)`:""));let V=M.skippedDestroys??[];if(V.length>0){D(`${V.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let F of V)D(` ${F.kind} ${F.id}`);D("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(M){M instanceof se&&M.status===403&&x("apply forbidden (403) \u2014 the stored PAT is not for an admin.");let V=M instanceof se?qu(M.body):null;V&&x(`bundle apply failed \u2014 ${V}`),x(`bundle apply failed: ${M instanceof Error?M.message:String(M)}`)}return}d||x("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:v,token:T}=await G(h.baseUrl),k=await LF(fe(process.cwd(),d)),y=new K({baseUrl:v,token:T});try{let S=await ie(`deploying ${jR(d)}`,()=>y.deploy(k)),E=lw(S.outcome);ot()?_(Qr("Deployed",[`${g.bold(S.id)} ${ko(S.status)} ${g.dim(E)}`])):_(`deployed ${S.id} \u2192 status=${S.status} (${E}).`)}catch(S){S instanceof se&&S.status===403&&x("deploy forbidden (403) \u2014 the stored PAT is not for an admin.");let E=S instanceof se?qu(S.body,d):null;E&&x(E),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("--no-source","Do not record this directory as the app's newest source revision. The app stays un-pullable and a user's change request cannot be applied to it.").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,h,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=fe(process.cwd(),h??".");await be.mkdir(k,{recursive:!0});let y=v.proposal??await $(k),{baseUrl:S,token:E}=await G(v.baseUrl),I=new K({baseUrl:S,token:E}),j=!1;try{j=(await I.appsList()).some(Se=>Se.slug===d||Se.id===d)}catch(Se){re(Se,"extensions:deploy","deploy"),x(`could not reach ${S}: ${Se instanceof Error?Se.message:String(Se)}`)}if(!j){v.create||x(`no app "${d}" on ${S} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let Se=await ie(`creating app ${d}`,()=>p(S,E,{slug:d},{tolerateExisting:!0}));Se.existed||_(`created ${Se.slug??d}.`)}let M;if(v.replace)if(typeof v.replace=="string")M=v.replace;else{let{previews:Se}=await De(S,E,d);if(Se.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\`.`),Se.length>1){for(let nt of Se)_(` ${nt.previewId} v${nt.version}${nt.label?` ${nt.label}`:""} ${nt.url}`);x(`${d} has ${Se.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${Se[0].previewId}\`.`)}M=Se[0].previewId}let V;if(v.replaceLabel){let Se=v.replaceLabel,{previews:nt}=await De(S,E,d),gr=nt.filter(jl=>jl.label===Se);gr.length>0?(M=gr[0].previewId,gr.length>1&&D(`${gr.length} open previews carry the label "${Se}"; replacing the newest (${M}). Close the others with \`turbobase apps preview discard\`.`)):_(`no open preview labelled "${Se}" \u2014 opening one.`),V=Se}let F=Se=>be.stat(jt(k,Se)).then(()=>!0).catch(()=>!1),ne=d,Ee=k,le=v.build!==!1,Ie=!1;if(le&&!await F("package.json"))if(await F("index.html"))_("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),le=!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 Se=await ie(`pulling ${d}`,()=>w(S,E,d));ne=Se.slug??d,await f(k,Se.files,!0),Ie=!0,_(`pulled generated source (rev ${Se.rev}).`)}let rt;if(le){let Se=s_();if(rt={buildId:Se,assetBase:i_(Se)},v.install!==!1&&!await F("node_modules")){_("installing dependencies\u2026");try{await O(["install"],k)}catch(nt){x(`npm install failed: ${nt instanceof Error?nt.message:String(nt)}`)}}_("building\u2026");try{await O(["run","build"],k,{TURBOBASE_ASSET_BASE:rt.assetBase})}catch(nt){x(`build failed: ${nt instanceof Error?nt.message:String(nt)}`)}await F("dist")||x(`no dist/ after build in ${k} \u2014 check the app's build script.`),Ee=jt(k,"dist")}T&&!rt&&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 Je=await Qe(S,E,ne,Ee,v.entry,y,rt,T?{label:v.label??V,replacePreviewId:M}:void 0),Fi=null;if(v.source!==!1&&!Ie&&await F("package.json")&&(Fi=await A(S,E,ne,k,y)),T){let Se=Je.previewUrl??"(no url returned)",nt=Je.expiresAt?new Date(Je.expiresAt).toLocaleDateString():`${a_} days`,gr=Je.replacedVersion==null?null:`replaced v${Je.replacedVersion} \u2014 same URL`;if(ot())_(Qr(gr?"Preview replaced":"Preview deployed",[`${g.bold(ne)} ${g.green(`v${Je.version??"?"}`)} ${g.dim("not live")}`,`${g.bold(Se)}`,...gr?[g.dim(gr)]:[],g.dim(`expires ${nt}`)]));else{let jl=gr?`; ${gr}`:"";_(`preview ${ne} v${Je.version??"?"} \u2192 ${Se} (expires ${nt}; /a/${ne} unchanged${jl}).`)}Vr(Je),_(`next: turbobase apps promote ${ne} ${Je.previewId??"<preview-id>"} # make it live`),_(` turbobase apps preview discard ${Je.previewId??"<preview-id>"}`);return}ot()?_(Qr("Deployed",[`${g.bold(ne)} ${g.green(`v${Je.version??"?"}`)} ${g.dim(Je.url??`/a/${ne}`)}`])):_(`deployed ${ne} \u2192 v${Je.version??"?"} (${Je.url??`/a/${ne}`}).`),Vr(Je),fr(Je),await Hr(Je,k,Fi)}),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>`.").option("--app <slug>","The app this manifest belongs to (defaults to the slug in `--as app:<slug>`). Lets the plan tell this app's earlier role scopes from another app's, and list the content values a deploy would retire.").action(async(d,h)=>{let v=h.as?.startsWith("app:")?h.as.slice(4).trim():"";h.app!==void 0&&h.app.trim()===""&&x("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let T=h.app?.trim()??"";T&&v&&T!==v&&x(`--app ${T} and --as app:${v} name two different apps \u2014 pass one slug.`);let k=T||v||null,y=await UF(d??".");y||x(`no public/turbobase.json under ${fe(process.cwd(),d??".")}.`);let S=Array.isArray(y.manifest.tables)?y.manifest.tables:[],E=Array.isArray(y.manifest.writes)?y.manifest.writes:[],I=Array.isArray(y.manifest.roles)?y.manifest.roles:null,j=I??[],M=Array.isArray(y.manifest.labels)?y.manifest.labels:[],V=I!==null&&I.length===0;if(S.length===0&&E.length===0&&j.length===0&&M.length===0){if(!V)return _(`${y.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(k===null){for(let le of Ou({app:null,roles:I}))_(le.text);return}}let{baseUrl:F,token:ne}=await G(h.baseUrl),Ee=new K({baseUrl:F,token:ne});if(S.length>0){let le;try{le=await ie("planning tables",()=>Ee.tablesPlan({claimedBy:h.as,tables:S}))}catch(Ie){re(Ie,"extensions:deploy","plan tables"),Ui(Ie)}_(`claiming as ${g.bold(le.claimedBy)}`);for(let Ie of le.tables)Mi(Ie,{showClaimants:!0})}if(E.length>0||j.length>0||M.length>0||V&&k!==null){let le;try{le=await ie("checking declared writes, roles and labels",()=>Ee.appsPlan({writes:E,...I!==null?{roles:I}:{},labels:M,...k!==null?{app:k}:{}}))}catch(Ie){re(Ie,"extensions:deploy","plan writes"),x(`plan writes failed: ${Ie instanceof Error?Ie.message:String(Ie)}`)}le.roles&&zt("plan",le.roles.verdicts,le.roles.retired);for(let Ie of Ou({app:k,roles:I,retired:le.roles?.retired??null}))_(Ie.text);if(le.labels&&le.labels.verdicts.length>0){_(""),_(g.bold("labels"));let Ie=Math.max(...le.labels.verdicts.map(rt=>rt.name.length));for(let rt of le.labels.verdicts){let Je=rt.name.padEnd(Ie);if(rt.action==="create")_(` create ${Je} ${g.dim(rt.color)}`);else{let Fi=rt.declaredColor?`${rt.color} \u2014 declared ${rt.declaredColor}, the instance's colour is kept`:rt.color;_(` ${g.dim("ok")} ${Je} ${g.dim(Fi)}`)}}_(g.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}E.length>0&&_("");for(let Ie of le.verdicts){let rt=`${Ie.source} ${Ie.recordType}.${Ie.op}`;Ie.allowed?Ie.heldForApproval?_(`${g.dim("HELD")} ${rt} \u2014 allowed, but each write waits for operator approval.`):_(`${g.dim("ok")} ${rt}`):D(`${g.bold("DENIED")} ${rt}${Ie.rule?` \u2014 guardrail "${Ie.rule}"`:""} (${Ie.reason})`)}le.ok||(_(""),x(le.message??(le.roles&&!le.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,h,v)=>{let{baseUrl:T,token:k}=await G(v.baseUrl),y=await ie(`promoting ${h}`,()=>Y(T,k,d,"promote",{previewId:h}));ot()?_(Qr("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}`}.`);let S=Wb(y);zt("applied",S.verdicts,S.retired),fr({labels:y.labels?{applied:!0,verdicts:y.labels}:null}),await Hr(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,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=await De(v,T,d);if(h.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}`:"",E=y.expiresAt?new Date(y.expiresAt).toLocaleDateString():"?";_(`v${y.version} ${y.previewId}${S} ${y.url} (expires ${E})`)}}),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,h,v)=>{let{baseUrl:T,token:k}=await G(v.baseUrl);await ie(`discarding ${h}`,()=>Y(T,k,d,"discard",{previewId:h})),_(`discarded ${h}.`)}),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,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=await ie(`creating ${d}`,()=>p(v,T,{slug:d,name:h.name,description:h.description})),y=k.slug??d;ot()?_(Qr("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`)});let u=ua(fetch);async function p(d,h,v,T={}){let k=`${d.replace(/\/+$/,"")}/v1/apps`,y;try{y=await u(k,{method:"POST",headers:{Authorization:`Bearer ${h}`,"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 w(d,h,v){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/pull`,k;try{k=await u(T,{headers:{Authorization:`Bearer ${h}`}})}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 f(d,h,v){let T=fe(d),k=0;for(let[y,S]of Object.entries(h)){let E=fe(T,y);E!==T&&!E.startsWith(T+Lg)&&x(`refusing to write outside ${T}: ${y}`),v||await be.stat(E).then(()=>!0).catch(()=>!1)&&x(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Zr(E),{recursive:!0}),await be.writeFile(E,S,"utf8"),k+=1}return k}function m(d){let h=d.indexOf(","),v=d.startsWith("data:")?h>=0?d.slice(h+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 b(d,h,v){let T=fe(d),k=async(S,E)=>{let I=fe(T,S);I!==T&&!I.startsWith(T+Lg)&&x(`refusing to write outside ${T}: ${S}`),v||await be.stat(I).then(()=>!0).catch(()=>!1)&&x(`${I} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Zr(I),{recursive:!0}),await be.writeFile(I,E)},y=`# ${h.title||"App change request"}
4435
+ `),"utf8"),_(`wrote ${I}${E?"":" (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 (${Rs.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=>Tw(d)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>Ew(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,h)=>Pw(d,h)),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,h)=>Aw(d,h)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Cw(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,h)=>Iw(d,h)),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,h)=>Ow(d,h)),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("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>(d.publish&&!d.from&&k("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),d.from?Dw({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):Nw(d))),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>Qw(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,h)=>e_(d,h)),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,h)=>t_(d,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>n_(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,h)=>r_(d,h)),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,h)=>o_(d,h));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 h;try{h=_r("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(S){k(S instanceof Error?S.message:String(S))}let v=fe(process.cwd(),h.relativePath);await io(v,h.content)==="skipped"&&k(`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 h;try{h=_r("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(S){k(S instanceof Error?S.message:String(S))}let v=fe(process.cwd(),h.relativePath);await io(v,h.content)==="skipped"&&k(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async d=>{let h;try{h=_r("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(S){k(S instanceof Error?S.message:String(S))}let v=fe(process.cwd(),h.relativePath);await io(v,h.content)==="skipped"&&k(`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,h)=>{let v=Ig(h.reporter),T=await vs(fe(process.cwd(),d)),S=fe(process.cwd(),h.samples),y=await _s(S);y.length===0&&!v&&_(`no samples found under ${S} \u2014 add JSON fixtures to dry-run against.`);let x;try{x=await ya(T,y.map(j=>j.fixture),{resolveDir:Zr(fe(process.cwd(),d))})}catch(j){k(`bundle failed: ${j instanceof Error?j.message:String(j)}`)}if(v){let j=zF(x);_(wa(j,v)),Ol(j.cases.some(M=>M.status==="failed")?1:0)}let E=0;for(let j of x){let M=j.pass?g.green("PASS"):g.red("FAIL");j.pass||(E+=1);let V=j.error?` (error: ${j.error})`:j.observed!==j.expected?` (expected ${j.expected}, observed ${j.observed})`:j.rejection?` (rejected: ${j.rejection.code??"rejected"})`:"";_(` ${M} ${j.name}${V}`)}let I=`${x.length-E}/${x.length} sample(s) passed.`;_(`
4436
+ ${E===0?g.green(I):g.yellow(I)}`),Ol(E>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,h)=>{if(h.to){let x=await Og(),{baseUrl:E,token:I}=await Y(h.baseUrl),j=new K({baseUrl:E,token:I});try{let M=await ie(`applying bundle to ${h.to}`,()=>j.configApply(x,{prune:h.prune}));_(`applied bundle to ${h.to}: +${M.applied.add} ~${M.applied.change} -${M.applied.destroy}`+(M.backfillsQueued.length?` (${M.backfillsQueued.length} backfill(s) queued)`:""));let V=M.skippedDestroys??[];if(V.length>0){D(`${V.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let F of V)D(` ${F.kind} ${F.id}`);D("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(M){M instanceof se&&M.status===403&&k("apply forbidden (403) \u2014 the stored PAT is not for an admin.");let V=M instanceof se?Fu(M.body):null;V&&k(`bundle apply failed \u2014 ${V}`),k(`bundle apply failed: ${M instanceof Error?M.message:String(M)}`)}return}d||k("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:v,token:T}=await Y(h.baseUrl),S=await jF(fe(process.cwd(),d)),y=new K({baseUrl:v,token:T});try{let x=await ie(`deploying ${zR(d)}`,()=>y.deploy(S)),E=uw(x.outcome);ot()?_(Qr("Deployed",[`${g.bold(x.id)} ${ko(x.status)} ${g.dim(E)}`])):_(`deployed ${x.id} \u2192 status=${x.status} (${E}).`)}catch(x){x instanceof se&&x.status===403&&k("deploy forbidden (403) \u2014 the stored PAT is not for an admin.");let E=x instanceof se?Fu(x.body,d):null;E&&k(E),k(`deploy failed: ${x instanceof Error?x.message:String(x)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--no-source","Do not record this directory as the app's newest source revision. The app stays un-pullable and a user's change request cannot be applied to it.").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,h,v)=>{let T=!!(v.preview||v.replace||v.replaceLabel);v.replace&&v.replaceLabel&&k("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let S=fe(process.cwd(),h??".");await be.mkdir(S,{recursive:!0});let y=v.proposal??await $(S),{baseUrl:x,token:E}=await Y(v.baseUrl),I=new K({baseUrl:x,token:E}),j=!1;try{j=(await I.appsList()).some(Se=>Se.slug===d||Se.id===d)}catch(Se){re(Se,"extensions:deploy","deploy"),k(`could not reach ${x}: ${Se instanceof Error?Se.message:String(Se)}`)}if(!j){v.create||k(`no app "${d}" on ${x} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let Se=await ie(`creating app ${d}`,()=>p(x,E,{slug:d},{tolerateExisting:!0}));Se.existed||_(`created ${Se.slug??d}.`)}let M;if(v.replace)if(typeof v.replace=="string")M=v.replace;else{let{previews:Se}=await De(x,E,d);if(Se.length===0&&k(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),Se.length>1){for(let nt of Se)_(` ${nt.previewId} v${nt.version}${nt.label?` ${nt.label}`:""} ${nt.url}`);k(`${d} has ${Se.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${Se[0].previewId}\`.`)}M=Se[0].previewId}let V;if(v.replaceLabel){let Se=v.replaceLabel,{previews:nt}=await De(x,E,d),gr=nt.filter(zl=>zl.label===Se);gr.length>0?(M=gr[0].previewId,gr.length>1&&D(`${gr.length} open previews carry the label "${Se}"; replacing the newest (${M}). Close the others with \`turbobase apps preview discard\`.`)):_(`no open preview labelled "${Se}" \u2014 opening one.`),V=Se}let F=Se=>be.stat(jt(S,Se)).then(()=>!0).catch(()=>!1),ne=d,Ee=S,le=v.build!==!1,Ie=!1;if(le&&!await F("package.json"))if(await F("index.html"))_("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),le=!1;else if(v.pull===!1)k(`${S} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let Se=await ie(`pulling ${d}`,()=>w(x,E,d));ne=Se.slug??d,await f(S,Se.files,!0),Ie=!0,_(`pulled generated source (rev ${Se.rev}).`)}let rt;if(le){let Se=i_();if(rt={buildId:Se,assetBase:a_(Se)},v.install!==!1&&!await F("node_modules")){_("installing dependencies\u2026");try{await O(["install"],S)}catch(nt){k(`npm install failed: ${nt instanceof Error?nt.message:String(nt)}`)}}_("building\u2026");try{await O(["run","build"],S,{TURBOBASE_ASSET_BASE:rt.assetBase})}catch(nt){k(`build failed: ${nt instanceof Error?nt.message:String(nt)}`)}await F("dist")||k(`no dist/ after build in ${S} \u2014 check the app's build script.`),Ee=jt(S,"dist")}T&&!rt&&k(`--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 Je=await Qe(x,E,ne,Ee,v.entry,y,rt,T?{label:v.label??V,replacePreviewId:M}:void 0),Fi=null;if(v.source!==!1&&!Ie&&await F("package.json")&&(Fi=await A(x,E,ne,S,y)),T){let Se=Je.previewUrl??"(no url returned)",nt=Je.expiresAt?new Date(Je.expiresAt).toLocaleDateString():`${c_} days`,gr=Je.replacedVersion==null?null:`replaced v${Je.replacedVersion} \u2014 same URL`;if(ot())_(Qr(gr?"Preview replaced":"Preview deployed",[`${g.bold(ne)} ${g.green(`v${Je.version??"?"}`)} ${g.dim("not live")}`,`${g.bold(Se)}`,...gr?[g.dim(gr)]:[],g.dim(`expires ${nt}`)]));else{let zl=gr?`; ${gr}`:"";_(`preview ${ne} v${Je.version??"?"} \u2192 ${Se} (expires ${nt}; /a/${ne} unchanged${zl}).`)}Vr(Je),_(`next: turbobase apps promote ${ne} ${Je.previewId??"<preview-id>"} # make it live`),_(` turbobase apps preview discard ${Je.previewId??"<preview-id>"}`);return}ot()?_(Qr("Deployed",[`${g.bold(ne)} ${g.green(`v${Je.version??"?"}`)} ${g.dim(Je.url??`/a/${ne}`)}`])):_(`deployed ${ne} \u2192 v${Je.version??"?"} (${Je.url??`/a/${ne}`}).`),Vr(Je),fr(Je),await Hr(Je,S,Fi)}),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>`.").option("--app <slug>","The app this manifest belongs to (defaults to the slug in `--as app:<slug>`). Lets the plan tell this app's earlier role scopes from another app's, and list the content values a deploy would retire.").action(async(d,h)=>{let v=h.as?.startsWith("app:")?h.as.slice(4).trim():"";h.app!==void 0&&h.app.trim()===""&&k("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let T=h.app?.trim()??"";T&&v&&T!==v&&k(`--app ${T} and --as app:${v} name two different apps \u2014 pass one slug.`);let S=T||v||null,y=await qF(d??".");y||k(`no public/turbobase.json under ${fe(process.cwd(),d??".")}.`);let x=Array.isArray(y.manifest.tables)?y.manifest.tables:[],E=Array.isArray(y.manifest.writes)?y.manifest.writes:[],I=Array.isArray(y.manifest.roles)?y.manifest.roles:null,j=I??[],M=Array.isArray(y.manifest.labels)?y.manifest.labels:[],V=I!==null&&I.length===0;if(x.length===0&&E.length===0&&j.length===0&&M.length===0){if(!V)return _(`${y.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(S===null){for(let le of Nu({app:null,roles:I}))_(le.text);return}}let{baseUrl:F,token:ne}=await Y(h.baseUrl),Ee=new K({baseUrl:F,token:ne});if(x.length>0){let le;try{le=await ie("planning tables",()=>Ee.tablesPlan({claimedBy:h.as,tables:x}))}catch(Ie){re(Ie,"extensions:deploy","plan tables"),Ui(Ie)}_(`claiming as ${g.bold(le.claimedBy)}`);for(let Ie of le.tables)Mi(Ie,{showClaimants:!0})}if(E.length>0||j.length>0||M.length>0||V&&S!==null){let le;try{le=await ie("checking declared writes, roles and labels",()=>Ee.appsPlan({writes:E,...I!==null?{roles:I}:{},labels:M,...S!==null?{app:S}:{}}))}catch(Ie){re(Ie,"extensions:deploy","plan writes"),k(`plan writes failed: ${Ie instanceof Error?Ie.message:String(Ie)}`)}le.roles&&zt("plan",le.roles.verdicts,le.roles.retired);for(let Ie of Nu({app:S,roles:I,retired:le.roles?.retired??null}))_(Ie.text);if(le.labels&&le.labels.verdicts.length>0){_(""),_(g.bold("labels"));let Ie=Math.max(...le.labels.verdicts.map(rt=>rt.name.length));for(let rt of le.labels.verdicts){let Je=rt.name.padEnd(Ie);if(rt.action==="create")_(` create ${Je} ${g.dim(rt.color)}`);else{let Fi=rt.declaredColor?`${rt.color} \u2014 declared ${rt.declaredColor}, the instance's colour is kept`:rt.color;_(` ${g.dim("ok")} ${Je} ${g.dim(Fi)}`)}}_(g.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}E.length>0&&_("");for(let Ie of le.verdicts){let rt=`${Ie.source} ${Ie.recordType}.${Ie.op}`;Ie.allowed?Ie.heldForApproval?_(`${g.dim("HELD")} ${rt} \u2014 allowed, but each write waits for operator approval.`):_(`${g.dim("ok")} ${rt}`):D(`${g.bold("DENIED")} ${rt}${Ie.rule?` \u2014 guardrail "${Ie.rule}"`:""} (${Ie.reason})`)}le.ok||(_(""),k(le.message??(le.roles&&!le.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,h,v)=>{let{baseUrl:T,token:S}=await Y(v.baseUrl),y=await ie(`promoting ${h}`,()=>J(T,S,d,"promote",{previewId:h}));ot()?_(Qr("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}`}.`);let x=Gb(y);zt("applied",x.verdicts,x.retired),fr({labels:y.labels?{applied:!0,verdicts:y.labels}:null}),await Hr(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,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=await De(v,T,d);if(h.json)return _(JSON.stringify(S.previews,null,2));if(S.previews.length===0){_(`no open previews for ${d}.`);return}for(let y of S.previews){let x=y.label?` ${y.label}`:"",E=y.expiresAt?new Date(y.expiresAt).toLocaleDateString():"?";_(`v${y.version} ${y.previewId}${x} ${y.url} (expires ${E})`)}}),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,h,v)=>{let{baseUrl:T,token:S}=await Y(v.baseUrl);await ie(`discarding ${h}`,()=>J(T,S,d,"discard",{previewId:h})),_(`discarded ${h}.`)}),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,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=await ie(`creating ${d}`,()=>p(v,T,{slug:d,name:h.name,description:h.description})),y=S.slug??d;ot()?_(Qr("Created",[`${g.bold(y)} ${g.dim(S.url??`/a/${y}`)}`])):_(`created ${y} (${S.url??`/a/${y}`}).`),_(`next: turbobase apps push ${y} . # store the source`),_(` turbobase apps deploy ${y} # build + go live`)});let u=ua(fetch);async function p(d,h,v,T={}){let S=`${d.replace(/\/+$/,"")}/v1/apps`,y;try{y=await u(S,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:v.slug,name:v.name??v.slug,description:v.description})})}catch(x){k(`create request failed: ${x instanceof Error?x.message:String(x)}`)}if(y.status===401&&k("create unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&k("create forbidden (403) \u2014 the PAT is not for an admin."),y.status===409){if(T.tolerateExisting)return{slug:v.slug,existed:!0};k(`an app with slug "${v.slug}" already exists.`)}return y.ok||k(`create failed: HTTP ${y.status} ${(await y.text().catch(()=>"")).slice(0,200)}`),await y.json().catch(()=>({}))}async function w(d,h,v){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/pull`,S;try{S=await u(T,{headers:{Authorization:`Bearer ${h}`}})}catch(y){k(`pull request failed: ${y instanceof Error?y.message:String(y)}`)}return S.status===401&&k("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&k("pull forbidden (403) \u2014 the PAT is not for an admin."),S.status===404&&k(`no generated source for "${v}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),S.ok||k(`pull failed: HTTP ${S.status} ${(await S.text().catch(()=>"")).slice(0,200)}`),await S.json()}async function f(d,h,v){let T=fe(d),S=0;for(let[y,x]of Object.entries(h)){let E=fe(T,y);E!==T&&!E.startsWith(T+jg)&&k(`refusing to write outside ${T}: ${y}`),v||await be.stat(E).then(()=>!0).catch(()=>!1)&&k(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Zr(E),{recursive:!0}),await be.writeFile(E,x,"utf8"),S+=1}return S}function m(d){let h=d.indexOf(","),v=d.startsWith("data:")?h>=0?d.slice(h+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 b(d,h,v){let T=fe(d),S=async(x,E)=>{let I=fe(T,x);I!==T&&!I.startsWith(T+jg)&&k(`refusing to write outside ${T}: ${x}`),v||await be.stat(I).then(()=>!0).catch(()=>!1)&&k(`${I} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Zr(I),{recursive:!0}),await be.writeFile(I,E)},y=`# ${h.title||"App change request"}
4406
4437
 
4407
4438
  > Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
4408
4439
  > \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
@@ -4412,37 +4443,37 @@ ${h.bodyMarkdown||"_No description provided._"}
4412
4443
  ## Screen context
4413
4444
 
4414
4445
  `+(h.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.
4415
- `);if(await k("PROPOSAL.md",y),h.screenshot){let S=m(h.screenshot);S&&await k("proposal-screenshot.png",S)}await k(jt(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
4416
- `)}async function $(d){try{let h=await be.readFile(jt(d,".turbobase","proposal.json"),"utf8"),v=JSON.parse(h);return typeof v.proposalId=="string"&&v.proposalId?v.proposalId:void 0}catch{return}}async function R(d,h,v,T,k,y){let S=new K({baseUrl:d,token:h});try{return await S.appsPush(v,T,{note:k,proposalId:y})}catch(E){if(E instanceof se){let I=E.body;if(E.status===401&&x("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&I?.error==="admin_required"&&x("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&re(E,"extensions:deploy","push app source"),E.status===404&&x(`no app "${v}" on this instance \u2014 create it with \`turbobase apps create ${v}\`.`),E.status===413&&(I?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&x("push rejected: the request body exceeded the instance limit."),x(`push rejected: ${I?.error??"too large"} (limit ${I?.limit??"?"}).`)),E.status===400){let j=I?.path?` in ${I.path}`:"",M=I?.reason?` (${I.reason})`:"";x(`push rejected: ${I?.error??"bad request"}${M}${j}.`)}}x(`push failed: ${E instanceof Error?E.message:String(E)}`)}}async function A(d,h,v,T,k){let y;try{y=await Yu(T)}catch(V){return D(`source not recorded: could not read ${T} (${V instanceof Error?V.message:String(V)}).`),null}let{files:S,skipped:E,secrets:I,unstorable:j}=y,M=Object.keys(S).length;if(M===0)return D(`source not recorded: no source files found under ${T}.`),null;if(j.length>0){for(let V of j)D(`${V} contains a NUL byte (U+0000), which cannot be stored.`);return D(`source not recorded: ${j.length} ${j.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and run \`turbobase apps push ${v}\`.`),null}for(let V of E)D(g.dim(`skipped binary file ${V}`));for(let V of I)D(g.dim(`skipped ${V} (holds credentials \u2014 never pushed)`));try{let V=await new K({baseUrl:d,token:h}).appsPush(v,S,{...k?{proposalId:k}:{}});return _(`recorded ${M} source file${M===1?"":"s"} on the instance (rev ${V.rev}).`),typeof V.rev=="number"?V.rev:null}catch(V){return D(`source not recorded: ${V instanceof Error?V.message:String(V)} \u2014 the version is live; run \`turbobase apps push ${v}\` to record its source.`),null}}function O(d,h,v){return new Promise((T,k)=>{let y=jg("npm",d,{cwd:h,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 q(d,h,v,T){let k=`${d.replace(/\/+$/,"")}${v}`,y;try{y=await u(k,{method:T.method,headers:{Authorization:`Bearer ${h}`,...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(()=>""),E=S.slice(0,300);try{let I=JSON.parse(S);E=I.message??I.error??E}catch{}x(`failed: HTTP ${y.status} ${E}`)}return await y.json().catch(()=>({}))}async function Y(d,h,v,T,k){return await q(d,h,`/v1/apps/${encodeURIComponent(v)}/preview/${T}`,{method:"POST",body:k})}async function De(d,h,v){return{previews:(await q(d,h,`/v1/apps/${encodeURIComponent(v)}/previews`,{method:"GET"})).previews??[]}}async function Qe(d,h,v,T,k,y,S,E){let I;try{I=await ie(`zipping ${T}`,()=>wb(T))}catch(F){x(`could not zip ${T}: ${F instanceof Error?F.message:String(F)}`)}I.fileCount===0&&x(`${T} is empty \u2014 the build produced nothing.`),I.buffer.byteLength>ed&&x(`${T} zips to ${LR(I.buffer.byteLength)} \u2014 over the ${LR(ed)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let j={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};k&&(j["x-app-entry"]=k),y&&(j["x-proposal-id"]=y),S&&(j["x-app-build-id"]=S.buildId,j["x-app-asset-base"]=S.assetBase),E&&(j["x-app-channel"]="preview",E.label&&(j["x-app-preview-label"]=encodeURIComponent(E.label)),E.replacePreviewId&&(j["x-app-preview-replace"]=E.replacePreviewId));let M=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/deploy`,V;try{V=await ie(`deploying ${v} (${I.fileCount} file${I.fileCount===1?"":"s"})`,()=>u(M,{method:"POST",headers:j,body:new Uint8Array(I.buffer)}))}catch(F){x(`deploy request failed: ${F instanceof Error?F.message:String(F)}`)}if(V.status===401&&x("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),V.status===403&&x("deploy forbidden (403) \u2014 the PAT is not for an admin."),V.status===404){let F=await V.text().catch(()=>""),ne={};try{ne=JSON.parse(F)}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(!V.ok){let F=await V.text().catch(()=>""),ne=F.slice(0,300);try{let Ee=JSON.parse(F);ne=Ee.message??Ee.error??ne}catch{}x(`deploy failed: HTTP ${V.status} ${ne}`)}return await V.json().catch(()=>({}))}function zt(d,h,v){for(let T of Kb({mode:d,verdicts:h,retired:v}))(T.stream==="err"?D:_)(T.text)}function Vr(d){let h=d.roles;h&&zt(h.applied?"applied":"preview",h.verdicts??[],h.retired)}function fr(d){let h=d.labels;if(!h||h.verdicts.length===0)return;let v=h.verdicts.filter(k=>k.action!=="noop");if(v.length===0)return;_(""),_(g.bold(h.applied?"labels":"labels (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==="detach")_(` removed ${y} ${g.dim("no longer declared in the manifest")}`);else if(k.action==="create")_(` created ${y} ${g.dim(k.color)}`);else{let S=k.declaredColor?`${k.color} \u2014 declared ${k.declaredColor}, the instance's colour is kept`:k.color;_(` added ${y} ${g.dim(S)}`)}}_(g.dim(h.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function Hr(d,h,v){let T=Ub(d,{localDocsModifiedAt:await Di(h),recordedSourceRev:v});T&&_(T.level==="warn"?g.yellow(T.message):g.dim(T.message))}async function Di(d){if(!d)return null;let h=null;for(let v of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await be.stat(jt(d,v));(h===null||T.mtimeMs>h)&&(h=T.mtimeMs)}catch{}return h===null?null:new Date(h)}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,h,v)=>{let{baseUrl:T,token:k}=await G(v.baseUrl);if(v.proposal){let I=new K({baseUrl:T,token:k}),j;try{j=await ie(`fetching proposal ${v.proposal}`,()=>I.appPullContext(v.proposal))}catch(Ee){re(Ee,"extensions:deploy","pull proposal"),Ee instanceof se&&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 M=await ie(`pulling ${j.appSlug}`,()=>w(T,k,j.appSlug)),V=h??d,F=fe(process.cwd(),V??j.appSlug);await be.mkdir(F,{recursive:!0});let ne=await f(F,M.files,!!v.force);await b(F,j,!!v.force),_(`pulled ${ne} file${ne===1?"":"s"} \u2192 ${F} (rev ${M.rev}), linked to proposal ${j.proposalId}.`),_(`next: cd ${Nl(process.cwd(),F)||"."} && turbobase apps deploy ${j.appSlug}`);return}d||x("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let y=await ie(`pulling ${d}`,()=>w(T,k,d)),S=fe(process.cwd(),h??y.slug??d);await be.mkdir(S,{recursive:!0});let E=await f(S,y.files,!!v.force);_(`pulled ${E} file${E===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,h,v)=>{let T=fe(process.cwd(),h??d),k=await nr(v.baseUrl).catch(()=>null),{scaffoldAppFiles:y,starterApp:S}=await Promise.resolve().then(()=>(V_(),Z_)),E=v.title??d,I=y({slug:d,title:E,appTsx:S(E),instanceOrigin:k?.baseUrl});await be.mkdir(T,{recursive:!0});let j=await f(T,I,!!v.force);if(_(`scaffolded ${j} file${j===1?"":"s"} \u2192 ${T}`),v.claude!==!1){let V=zu({baseUrl:k?.baseUrl,token:k?.token,appSlug:d}),F=0;for(let ne of V){let Ee=await NR(jt(T,ne.path),ne);(Ee==="wrote"||Ee==="merged")&&(F+=1)}_(`wired Claude Code: ${F} file${F===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),k||D("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 M=Nl(process.cwd(),T)||".";_(`next: cd ${M} && 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:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),k;try{k=await T.appsList()}catch(y){re(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>`.");_(Ht(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,h,v)=>{let T=fe(process.cwd(),h??".");await be.stat(T).then(le=>le.isDirectory()).catch(()=>!1)||x(`${T} is not a directory.`);let{baseUrl:y,token:S}=await G(v.baseUrl),E=v.proposal??await $(T),{files:I,skipped:j,secrets:M,unstorable:V}=await Yu(T),F=Object.keys(I).length;if(F===0&&x(`no source files found under ${T} (build output and node_modules are skipped).`),V.length>0){for(let le of V)D(`${le} contains a NUL byte (U+0000), which cannot be stored.`);x(`push aborted: ${V.length} ${V.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let le of j)D(g.dim(`skipped binary file ${le}`));for(let le of M)D(g.dim(`skipped ${le} (holds credentials \u2014 never pushed)`));let ne=await ie(`pushing ${F} file${F===1?"":"s"}`,()=>R(y,S,d,I,v.note,E));_(`pushed ${ne.files} file${ne.files===1?"":"s"} \u2192 ${ne.slug} rev ${ne.rev} (source only, nothing deployed).`);let Ee=await Es(new K({baseUrl:y,token:S}),ne.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 ${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 h=await Ig(),{baseUrl:v,token:T}=await G(d.baseUrl),k=new K({baseUrl:v,token:T}),y;try{y=await ie(`planning against ${d.to??v}`,()=>k.configPlan(h))}catch(S){x(`plan failed: ${S instanceof Error?S.message:String(S)}`)}FF(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 h=await Ig(),{baseUrl:v,token:T}=await G(d.baseUrl),k=h.tenant??BF(v),y=iw(d.confirm,k);y.ok||x(`promote refused (fail-closed): ${y.reason}`);let S=new K({baseUrl:v,token:T});try{let E=await ie(`promoting ${d.from} \u2192 ${d.to} (${k})`,()=>S.configApply(h,{prune:d.prune}));if(ot()){let j=[`${g.bold(`${d.from} \u2192 ${d.to}`)} ${g.dim(k??"")}`,`${Xr.add(String(E.applied.add))} ${Xr.change(String(E.applied.change))} ${Xr.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&j.push(g.dim(`${E.backfillsQueued.length} backfill(s) queued`)),_(Qr("Promoted",j))}else _(`promoted ${d.from} \u2192 ${d.to} (${k}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""));let I=E.skippedDestroys??[];if(I.length>0){D(`${I.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let j of I)D(` ${j.kind} ${j.id}`);D("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof se&&E.status===403&&x("promote forbidden (403) \u2014 the stored PAT is not for an admin."),x(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),o.command("lint").argument("<file>","The hook, conduit or process definition file to lint").description("Statically lint a hook/conduit/process 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,h)=>{let v=Cg(h.reporter),T=fe(process.cwd(),d),k=await vs(T),y=xb(k);v?_(wa(zF(d,y),v)):_(kb(d,y,{warn:g.yellow,ok:g.green,dim:g.dim})),h.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,h)=>{let v=Cg(h.reporter),T=await hb(fe(process.cwd(),d));if(h.against){h.against!=="sandbox"&&x(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await db(Ru(T))}catch(S){x(S instanceof Error?S.message:String(S))}return}h.fixture||x("replay needs a --fixture <file> (offline) or --against sandbox (online).");let k;try{k=await pb(fe(process.cwd(),h.fixture))}catch(S){x(`could not read fixture ${h.fixture}: ${S instanceof Error?S.message:String(S)}`)}let y=await ub(T,k,h.fixture,{resolveDir:Zr(fe(process.cwd(),d))});if(v){let S=DF(y);_(wa(S,v)),Ol(S.cases.some(E=>E.status==="failed")?1:0)}_(mb(y,!!h.trace)),Ol(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:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v});try{await Ab(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:_})}catch(k){k instanceof se&&k.status===403&&x("forbidden (403) \u2014 binding --retry requires an admin PAT."),k instanceof se&&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 wn=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");wn.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 Zw(d)}),wn.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,h)=>{await Vw(d??[],h)}),wn.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,h)=>{await Hw(d,h)}),wn.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,h)=>{await Kw(d,h)}),o.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Ww(d,h)}),o.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Gw(d,h)}),o.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Jw(d,h)}),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,h)=>{let v=d.lastIndexOf("@"),T=v>0?d.slice(0,v):d,k=v>0?d.slice(v+1):void 0,y=xu();y||x(`marketplace not configured \u2014 set ${_o} and ${da}.
4417
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=ku(y.registryUrl);S&&x(S);let{baseUrl:E,token:I}=await G(h.baseUrl),j=new bs(y),M;try{M=await ie(`fetching ${d}`,()=>j.fetchBundle(T,k))}catch(le){x(`marketplace fetch failed for ${d}: ${le instanceof Error?le.message:String(le)}`)}let V=ea(M.manifest),F=null;if(V.length>0){if(!h.connection){let le=V.map(Ie=>Ie.source_system).join(", ");x(`${M.name}@${M.version} declares a connection input (source: ${le}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}F=h.connection}let ne=MF(M.bundle,M.name,M.kind),Ee=new K({baseUrl:E,token:I});try{let le=await ie(`installing ${M.name}@${M.version}`,()=>Ee.deploy({...ne,provenance:"marketplace",...F?{connectionId:F}:{}}));_(`installed ${M.name}@${M.version} \u2192 ${le.id} (status=${le.status}, ${le.outcome})`+(F?` bound to connection ${F}.`:"."))}catch(le){le instanceof se&&le.status===403&&x("install forbidden (403) \u2014 the stored PAT is not for an admin."),x(`install failed: ${le instanceof Error?le.message:String(le)}`)}}),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,h)=>{let v=xu();v||x(`marketplace not configured \u2014 set ${_o} and ${da}.
4418
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=ku(v.registryUrl);T&&x(T);let k=fe(process.cwd(),d),y=await vs(k),S=/\bdefineConduit\s*[<(]/.test(y)?"conduit":"hook",E={};if(h.manifest){let M=fe(process.cwd(),h.manifest),V;try{V=await be.readFile(M,"utf8")}catch{x(`manifest not found at ${h.manifest}.`)}let F;try{F=JSON.parse(V)}catch{x(`manifest is not valid JSON: ${h.manifest}.`)}(typeof F!="object"||F===null||Array.isArray(F))&&x("manifest must be a JSON object."),E=F}try{su(E,y)}catch(M){M instanceof Yr&&x(M.message),x(`manifest validation failed: ${M instanceof Error?M.message:String(M)}`)}let I=new bs(v);try{await ie(`publishing ${h.name}@${h.pkgVersion}`,()=>I.publish({name:h.name,version:h.pkgVersion,kind:S,bundle:y,manifest:E}))}catch(M){M instanceof se&&M.status===403&&x("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),M instanceof se&&M.status===409&&x(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),x(`publish failed: ${M instanceof Error?M.message:String(M)}`)}let j=ea(E);_(`published ${h.name}@${h.pkgVersion} (kind=${S}) to the marketplace.`),j.length>0&&_(` declares ${j.length} connection input(s): ${j.map(M=>M.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 h=await nr(d.baseUrl).catch(()=>null),v=zu({baseUrl:h?.baseUrl,token:h?.token}),T=0,k=0,y=0;for(let S of v){let E=fe(process.cwd(),S.path),I=await NR(E,S);I==="wrote"?(T+=1,_(` wrote ${S.path}`)):I==="merged"?(y+=1,_(` merged ${S.path} (added the .mcp.json rule)`)):(k+=1,_(` skipped ${S.path} (exists)`))}_(`
4419
- project init: ${T} written, ${y} merged, ${k} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Nu} (non-destructive).`).action(async()=>{let d=Gb(),h=0,v=0;for(let T of d){let k=fe(process.cwd(),T.path);await io(k,T.content,T.executable)==="wrote"?(h+=1,_(` wrote ${T.path}`)):(v+=1,_(` skipped ${T.path} (exists)`))}_(`
4446
+ `);if(await S("PROPOSAL.md",y),h.screenshot){let x=m(h.screenshot);x&&await S("proposal-screenshot.png",x)}await S(jt(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
4447
+ `)}async function $(d){try{let h=await be.readFile(jt(d,".turbobase","proposal.json"),"utf8"),v=JSON.parse(h);return typeof v.proposalId=="string"&&v.proposalId?v.proposalId:void 0}catch{return}}async function R(d,h,v,T,S,y){let x=new K({baseUrl:d,token:h});try{return await x.appsPush(v,T,{note:S,proposalId:y})}catch(E){if(E instanceof se){let I=E.body;if(E.status===401&&k("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&I?.error==="admin_required"&&k("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&re(E,"extensions:deploy","push app source"),E.status===404&&k(`no app "${v}" on this instance \u2014 create it with \`turbobase apps create ${v}\`.`),E.status===413&&(I?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&k("push rejected: the request body exceeded the instance limit."),k(`push rejected: ${I?.error??"too large"} (limit ${I?.limit??"?"}).`)),E.status===400){let j=I?.path?` in ${I.path}`:"",M=I?.reason?` (${I.reason})`:"";k(`push rejected: ${I?.error??"bad request"}${M}${j}.`)}}k(`push failed: ${E instanceof Error?E.message:String(E)}`)}}async function A(d,h,v,T,S){let y;try{y=await Xu(T)}catch(V){return D(`source not recorded: could not read ${T} (${V instanceof Error?V.message:String(V)}).`),null}let{files:x,skipped:E,secrets:I,unstorable:j}=y,M=Object.keys(x).length;if(M===0)return D(`source not recorded: no source files found under ${T}.`),null;if(j.length>0){for(let V of j)D(`${V} contains a NUL byte (U+0000), which cannot be stored.`);return D(`source not recorded: ${j.length} ${j.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and run \`turbobase apps push ${v}\`.`),null}for(let V of E)D(g.dim(`skipped binary file ${V}`));for(let V of I)D(g.dim(`skipped ${V} (holds credentials \u2014 never pushed)`));try{let V=await new K({baseUrl:d,token:h}).appsPush(v,x,{...S?{proposalId:S}:{}});return _(`recorded ${M} source file${M===1?"":"s"} on the instance (rev ${V.rev}).`),typeof V.rev=="number"?V.rev:null}catch(V){return D(`source not recorded: ${V instanceof Error?V.message:String(V)} \u2014 the version is live; run \`turbobase apps push ${v}\` to record its source.`),null}}function O(d,h,v){return new Promise((T,S)=>{let y=zg("npm",d,{cwd:h,stdio:"inherit",...v?{env:{...process.env,...v}}:{}});y.on("error",S),y.on("exit",x=>x===0?T():S(new Error(`npm ${d.join(" ")} exited ${x??"?"}`)))})}async function q(d,h,v,T){let S=`${d.replace(/\/+$/,"")}${v}`,y;try{y=await u(S,{method:T.method,headers:{Authorization:`Bearer ${h}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch(x){k(`request failed: ${x instanceof Error?x.message:String(x)}`)}if(y.status===401&&k("unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&k("forbidden (403) \u2014 the PAT is not for an admin."),!y.ok){let x=await y.text().catch(()=>""),E=x.slice(0,300);try{let I=JSON.parse(x);E=I.message??I.error??E}catch{}k(`failed: HTTP ${y.status} ${E}`)}return await y.json().catch(()=>({}))}async function J(d,h,v,T,S){return await q(d,h,`/v1/apps/${encodeURIComponent(v)}/preview/${T}`,{method:"POST",body:S})}async function De(d,h,v){return{previews:(await q(d,h,`/v1/apps/${encodeURIComponent(v)}/previews`,{method:"GET"})).previews??[]}}async function Qe(d,h,v,T,S,y,x,E){let I;try{I=await ie(`zipping ${T}`,()=>_b(T))}catch(F){k(`could not zip ${T}: ${F instanceof Error?F.message:String(F)}`)}I.fileCount===0&&k(`${T} is empty \u2014 the build produced nothing.`),I.buffer.byteLength>td&&k(`${T} zips to ${jR(I.buffer.byteLength)} \u2014 over the ${jR(td)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let j={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};S&&(j["x-app-entry"]=S),y&&(j["x-proposal-id"]=y),x&&(j["x-app-build-id"]=x.buildId,j["x-app-asset-base"]=x.assetBase),E&&(j["x-app-channel"]="preview",E.label&&(j["x-app-preview-label"]=encodeURIComponent(E.label)),E.replacePreviewId&&(j["x-app-preview-replace"]=E.replacePreviewId));let M=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/deploy`,V;try{V=await ie(`deploying ${v} (${I.fileCount} file${I.fileCount===1?"":"s"})`,()=>u(M,{method:"POST",headers:j,body:new Uint8Array(I.buffer)}))}catch(F){k(`deploy request failed: ${F instanceof Error?F.message:String(F)}`)}if(V.status===401&&k("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),V.status===403&&k("deploy forbidden (403) \u2014 the PAT is not for an admin."),V.status===404){let F=await V.text().catch(()=>""),ne={};try{ne=JSON.parse(F)}catch{}ne.error==="no_preview"&&k(`${ne.message??`no open preview to replace on ${v}`} \u2014 list them with \`turbobase apps preview list ${v}\`.`),k(`no app "${v}" on ${d} \u2014 create it with \`turbobase apps create ${v}\`.`)}if(!V.ok){let F=await V.text().catch(()=>""),ne=F.slice(0,300);try{let Ee=JSON.parse(F);ne=Ee.message??Ee.error??ne}catch{}k(`deploy failed: HTTP ${V.status} ${ne}`)}return await V.json().catch(()=>({}))}function zt(d,h,v){for(let T of Wb({mode:d,verdicts:h,retired:v}))(T.stream==="err"?D:_)(T.text)}function Vr(d){let h=d.roles;h&&zt(h.applied?"applied":"preview",h.verdicts??[],h.retired)}function fr(d){let h=d.labels;if(!h||h.verdicts.length===0)return;let v=h.verdicts.filter(S=>S.action!=="noop");if(v.length===0)return;_(""),_(g.bold(h.applied?"labels":"labels (preview \u2014 not applied)"));let T=Math.max(...v.map(S=>S.name.length));for(let S of v){let y=S.name.padEnd(T);if(S.action==="detach")_(` removed ${y} ${g.dim("no longer declared in the manifest")}`);else if(S.action==="create")_(` created ${y} ${g.dim(S.color)}`);else{let x=S.declaredColor?`${S.color} \u2014 declared ${S.declaredColor}, the instance's colour is kept`:S.color;_(` added ${y} ${g.dim(x)}`)}}_(g.dim(h.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function Hr(d,h,v){let T=qb(d,{localDocsModifiedAt:await Di(h),recordedSourceRev:v});T&&_(T.level==="warn"?g.yellow(T.message):g.dim(T.message))}async function Di(d){if(!d)return null;let h=null;for(let v of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await be.stat(jt(d,v));(h===null||T.mtimeMs>h)&&(h=T.mtimeMs)}catch{}return h===null?null:new Date(h)}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,h,v)=>{let{baseUrl:T,token:S}=await Y(v.baseUrl);if(v.proposal){let I=new K({baseUrl:T,token:S}),j;try{j=await ie(`fetching proposal ${v.proposal}`,()=>I.appPullContext(v.proposal))}catch(Ee){re(Ee,"extensions:deploy","pull proposal"),Ee instanceof se&&Ee.status===404&&k(`no widget proposal "${v.proposal}" on ${T}.`),k(`could not fetch proposal ${v.proposal}: ${Ee instanceof Error?Ee.message:String(Ee)}`)}let M=await ie(`pulling ${j.appSlug}`,()=>w(T,S,j.appSlug)),V=h??d,F=fe(process.cwd(),V??j.appSlug);await be.mkdir(F,{recursive:!0});let ne=await f(F,M.files,!!v.force);await b(F,j,!!v.force),_(`pulled ${ne} file${ne===1?"":"s"} \u2192 ${F} (rev ${M.rev}), linked to proposal ${j.proposalId}.`),_(`next: cd ${Nl(process.cwd(),F)||"."} && turbobase apps deploy ${j.appSlug}`);return}d||k("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let y=await ie(`pulling ${d}`,()=>w(T,S,d)),x=fe(process.cwd(),h??y.slug??d);await be.mkdir(x,{recursive:!0});let E=await f(x,y.files,!!v.force);_(`pulled ${E} file${E===1?"":"s"} \u2192 ${x} (rev ${y.rev}).`),_(`next: cd ${Nl(process.cwd(),x)||"."} && 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,h,v)=>{let T=fe(process.cwd(),h??d),S=await nr(v.baseUrl).catch(()=>null),{scaffoldAppFiles:y,starterApp:x}=await Promise.resolve().then(()=>(H_(),V_)),E=v.title??d,I=y({slug:d,title:E,appTsx:x(E),instanceOrigin:S?.baseUrl});await be.mkdir(T,{recursive:!0});let j=await f(T,I,!!v.force);if(_(`scaffolded ${j} file${j===1?"":"s"} \u2192 ${T}`),v.claude!==!1){let V=Du({baseUrl:S?.baseUrl,token:S?.token,appSlug:d}),F=0;for(let ne of V){let Ee=await LR(jt(T,ne.path),ne);(Ee==="wrote"||Ee==="merged")&&(F+=1)}_(`wired Claude Code: ${F} file${F===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),S||D("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 M=Nl(process.cwd(),T)||".";_(`next: cd ${M} && 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:h,token:v}=await Y(d.baseUrl),T=new K({baseUrl:h,token:v}),S;try{S=await T.appsList()}catch(y){re(y,"extensions:deploy","list apps"),k(`list apps failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(S,null,2));if(S.length===0)return _("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");_(Ht(S.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,h,v)=>{let T=fe(process.cwd(),h??".");await be.stat(T).then(le=>le.isDirectory()).catch(()=>!1)||k(`${T} is not a directory.`);let{baseUrl:y,token:x}=await Y(v.baseUrl),E=v.proposal??await $(T),{files:I,skipped:j,secrets:M,unstorable:V}=await Xu(T),F=Object.keys(I).length;if(F===0&&k(`no source files found under ${T} (build output and node_modules are skipped).`),V.length>0){for(let le of V)D(`${le} contains a NUL byte (U+0000), which cannot be stored.`);k(`push aborted: ${V.length} ${V.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let le of j)D(g.dim(`skipped binary file ${le}`));for(let le of M)D(g.dim(`skipped ${le} (holds credentials \u2014 never pushed)`));let ne=await ie(`pushing ${F} file${F===1?"":"s"}`,()=>R(y,x,d,I,v.note,E));_(`pushed ${ne.files} file${ne.files===1?"":"s"} \u2192 ${ne.slug} rev ${ne.rev} (source only, nothing deployed).`);let Ee=await Es(new K({baseUrl:y,token:x}),ne.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 ${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 h=await Og(),{baseUrl:v,token:T}=await Y(d.baseUrl),S=new K({baseUrl:v,token:T}),y;try{y=await ie(`planning against ${d.to??v}`,()=>S.configPlan(h))}catch(x){k(`plan failed: ${x instanceof Error?x.message:String(x)}`)}BF(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 h=await Og(),{baseUrl:v,token:T}=await Y(d.baseUrl),S=h.tenant??ZF(v),y=aw(d.confirm,S);y.ok||k(`promote refused (fail-closed): ${y.reason}`);let x=new K({baseUrl:v,token:T});try{let E=await ie(`promoting ${d.from} \u2192 ${d.to} (${S})`,()=>x.configApply(h,{prune:d.prune}));if(ot()){let j=[`${g.bold(`${d.from} \u2192 ${d.to}`)} ${g.dim(S??"")}`,`${Xr.add(String(E.applied.add))} ${Xr.change(String(E.applied.change))} ${Xr.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&j.push(g.dim(`${E.backfillsQueued.length} backfill(s) queued`)),_(Qr("Promoted",j))}else _(`promoted ${d.from} \u2192 ${d.to} (${S}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""));let I=E.skippedDestroys??[];if(I.length>0){D(`${I.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let j of I)D(` ${j.kind} ${j.id}`);D("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof se&&E.status===403&&k("promote forbidden (403) \u2014 the stored PAT is not for an admin."),k(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),o.command("lint").argument("<file>","The hook, conduit or process definition file to lint").description("Statically lint a hook/conduit/process 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,h)=>{let v=Ig(h.reporter),T=fe(process.cwd(),d),S=await vs(T),y=xb(S);v?_(wa(DF(d,y),v)):_(Sb(d,y,{warn:g.yellow,ok:g.green,dim:g.dim})),h.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,h)=>{let v=Ig(h.reporter),T=await mb(fe(process.cwd(),d));if(h.against){h.against!=="sandbox"&&k(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await pb(Eu(T))}catch(x){k(x instanceof Error?x.message:String(x))}return}h.fixture||k("replay needs a --fixture <file> (offline) or --against sandbox (online).");let S;try{S=await hb(fe(process.cwd(),h.fixture))}catch(x){k(`could not read fixture ${h.fixture}: ${x instanceof Error?x.message:String(x)}`)}let y=await db(T,S,h.fixture,{resolveDir:Zr(fe(process.cwd(),d))});if(v){let x=MF(y);_(wa(x,v)),Ol(x.cases.some(E=>E.status==="failed")?1:0)}_(fb(y,!!h.trace)),Ol(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:h,token:v}=await Y(d.baseUrl),T=new K({baseUrl:h,token:v});try{await Cb(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:_})}catch(S){S instanceof se&&S.status===403&&k("forbidden (403) \u2014 binding --retry requires an admin PAT."),S instanceof se&&S.status===409&&k("binding is not retryable (only divergent/blocked bindings can be retried)."),k(`ext binding failed: ${S instanceof Error?S.message:String(S)}`)}});let wn=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");wn.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 Vw(d)}),wn.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,h)=>{await Hw(d??[],h)}),wn.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,h)=>{await Kw(d,h)}),wn.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,h)=>{await Ww(d,h)}),o.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Gw(d,h)}),o.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Jw(d,h)}),o.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Yw(d,h)}),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,h)=>{let v=d.lastIndexOf("@"),T=v>0?d.slice(0,v):d,S=v>0?d.slice(v+1):void 0,y=xu();y||k(`marketplace not configured \u2014 set ${wo} and ${da}.
4448
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=Su(y.registryUrl);x&&k(x);let{baseUrl:E,token:I}=await Y(h.baseUrl),j=new bs(y),M;try{M=await ie(`fetching ${d}`,()=>j.fetchBundle(T,S))}catch(le){k(`marketplace fetch failed for ${d}: ${le instanceof Error?le.message:String(le)}`)}let V=ea(M.manifest),F=null;if(V.length>0){if(!h.connection){let le=V.map(Ie=>Ie.source_system).join(", ");k(`${M.name}@${M.version} declares a connection input (source: ${le}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}F=h.connection}let ne=UF(M.bundle,M.name,M.kind),Ee=new K({baseUrl:E,token:I});try{let le=await ie(`installing ${M.name}@${M.version}`,()=>Ee.deploy({...ne,provenance:"marketplace",...F?{connectionId:F}:{}}));_(`installed ${M.name}@${M.version} \u2192 ${le.id} (status=${le.status}, ${le.outcome})`+(F?` bound to connection ${F}.`:"."))}catch(le){le instanceof se&&le.status===403&&k("install forbidden (403) \u2014 the stored PAT is not for an admin."),k(`install failed: ${le instanceof Error?le.message:String(le)}`)}}),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,h)=>{let v=xu();v||k(`marketplace not configured \u2014 set ${wo} and ${da}.
4449
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=Su(v.registryUrl);T&&k(T);let S=fe(process.cwd(),d),y=await vs(S),x=/\bdefineConduit\s*[<(]/.test(y)?"conduit":"hook",E={};if(h.manifest){let M=fe(process.cwd(),h.manifest),V;try{V=await be.readFile(M,"utf8")}catch{k(`manifest not found at ${h.manifest}.`)}let F;try{F=JSON.parse(V)}catch{k(`manifest is not valid JSON: ${h.manifest}.`)}(typeof F!="object"||F===null||Array.isArray(F))&&k("manifest must be a JSON object."),E=F}try{iu(E,y)}catch(M){M instanceof Yr&&k(M.message),k(`manifest validation failed: ${M instanceof Error?M.message:String(M)}`)}let I=new bs(v);try{await ie(`publishing ${h.name}@${h.pkgVersion}`,()=>I.publish({name:h.name,version:h.pkgVersion,kind:x,bundle:y,manifest:E}))}catch(M){M instanceof se&&M.status===403&&k("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),M instanceof se&&M.status===409&&k(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),k(`publish failed: ${M instanceof Error?M.message:String(M)}`)}let j=ea(E);_(`published ${h.name}@${h.pkgVersion} (kind=${x}) to the marketplace.`),j.length>0&&_(` declares ${j.length} connection input(s): ${j.map(M=>M.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 h=await nr(d.baseUrl).catch(()=>null),v=Du({baseUrl:h?.baseUrl,token:h?.token}),T=0,S=0,y=0;for(let x of v){let E=fe(process.cwd(),x.path),I=await LR(E,x);I==="wrote"?(T+=1,_(` wrote ${x.path}`)):I==="merged"?(y+=1,_(` merged ${x.path} (added the .mcp.json rule)`)):(S+=1,_(` skipped ${x.path} (exists)`))}_(`
4450
+ project init: ${T} written, ${y} merged, ${S} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Lu} (non-destructive).`).action(async()=>{let d=Jb(),h=0,v=0;for(let T of d){let S=fe(process.cwd(),T.path);await io(S,T.content,T.executable)==="wrote"?(h+=1,_(` wrote ${T.path}`)):(v+=1,_(` skipped ${T.path} (exists)`))}_(`
4420
4451
  project ci: ${h} written, ${v} skipped.`),h>0&&(_(`
4421
- 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:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),k;try{k=await T.catalogRecords()}catch(j){j instanceof se&&(j.status===401||j.status===403)&&x("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),x(`catalog fetch failed: ${j instanceof Error?j.message:String(j)}`)}if(k.length===0){_("no records in the instance catalog \u2014 nothing to generate.");return}let y=fe(process.cwd(),d.out),S=gb(k,{event:d.event}),E=0,I=0;for(let{recordType:j,fixture:M}of S){let V=jt(y,`${j}.json`),F=`${JSON.stringify(M,null,2)}
4452
+ 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:h,token:v}=await Y(d.baseUrl),T=new K({baseUrl:h,token:v}),S;try{S=await T.catalogRecords()}catch(j){j instanceof se&&(j.status===401||j.status===403)&&k("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),k(`catalog fetch failed: ${j instanceof Error?j.message:String(j)}`)}if(S.length===0){_("no records in the instance catalog \u2014 nothing to generate.");return}let y=fe(process.cwd(),d.out),x=yb(S,{event:d.event}),E=0,I=0;for(let{recordType:j,fixture:M}of x){let V=jt(y,`${j}.json`),F=`${JSON.stringify(M,null,2)}
4422
4453
  `;d.force?(await be.mkdir(Zr(V),{recursive:!0}),await be.writeFile(V,F,{mode:420}),E+=1,_(` wrote ${d.out}/${j}.json`)):await io(V,F)==="wrote"?(E+=1,_(` wrote ${d.out}/${j}.json`)):(I+=1,_(` skipped ${d.out}/${j}.json (exists \u2014 use --force to overwrite)`))}_(`
4423
- samples init: ${E} written, ${I} skipped.`)});let Pr=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),zR=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??""],DR=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];Pr.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:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),k;try{k=await T.guardrailsList()}catch(y){re(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.
4424
- `+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(Ht(k.map(zR),{head:DR})),_(g.dim(" first match wins; lower PRIO is evaluated first."))}),Pr.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,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T}),y;try{y=await k.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){re(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>`))}),Pr.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,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&x("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T}),y;try{y=await k.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(S){re(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,h,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Pr.command(`${d} <name>`).description(h==="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 G(k.baseUrl),E=new K({baseUrl:y,token:S});try{await E.guardrailUpdate(T,{status:h})}catch(I){re(I,"extensions:deploy",`${d} a guardrail`),x(`${d} guardrail failed: ${I instanceof Error?I.message:String(I)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(T)} ${v}`),h==="inactive"&&_(g.dim(" writes it was gating now fall through to the other rules."))});Pr.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,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T});try{await k.guardrailDelete(d)}catch(y){re(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`)}),Pr.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,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T}),y=I=>I==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let I;try{I=await k.guardrailPostureGet()}catch(j){re(j,"extensions:deploy","read the guardrail posture"),x(`read posture failed: ${j instanceof Error?j.message:String(j)}`)}_(`guardrail posture: ${g.bold(y(I.mode))}`),_(g.dim(I.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 E;try{E=await k.guardrailPostureSet(S)}catch(I){re(I,"extensions:deploy","set the guardrail posture"),x(`set posture failed: ${I instanceof Error?I.message:String(I)}`)}_(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(E.mode))}`),E.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>`."))}),Pr.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 h;if(d.fields)try{h=JSON.parse(d.fields)}catch(E){x(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:v,token:T}=await G(d.baseUrl),k=new K({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}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){re(E,"extensions:deploy","test guardrails"),x(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}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 as=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Mi=(d,h={})=>{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=h.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";_(` ${T.column.padEnd(28)} ${T.type}${k?` (${k})`:""}${y}`)}h.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Ui(d){if(d instanceof se&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(D(h.message),process.exit(1))}x(`tables: ${d instanceof Error?d.message:String(d)}`)}let Dg=async d=>{let h=jt(fe(process.cwd(),d),"public","turbobase.json"),v=await be.readFile(h,"utf8").catch(()=>null);if(v===null)return null;let T;try{T=JSON.parse(v)}catch(y){x(`${h} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let k=T.tables;return k===void 0?{tables:[],manifestPath:h}:(Array.isArray(k)||x(`${h}: "tables" must be an array.`),{tables:k,manifestPath:h})};as.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:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),k;try{k=await T.tablesList()}catch(y){re(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>`.");_(Ht(k.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),as.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,h)=>{let v=await Dg(d??".");if(v||x(`no public/turbobase.json under ${fe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:k}=await G(h.baseUrl),y=new K({baseUrl:T,token:k}),S;try{S=await ie("planning tables",()=>y.tablesPlan({claimedBy:h.as,tables:v.tables}))}catch(E){re(E,"extensions:deploy","plan tables"),Ui(E)}_(`claiming as ${g.bold(S.claimedBy)}`);for(let E of S.tables)Mi(E,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),as.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,h)=>{let v=await Dg(d??".");if(v||x(`no public/turbobase.json under ${fe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:k}=await G(h.baseUrl),y=new K({baseUrl:T,token:k}),S;try{S=await ie("applying tables",()=>y.tablesApply({claimedBy:h.as,tables:v.tables}))}catch(E){re(E,"extensions:deploy","apply tables"),Ui(E)}for(let E of S.tables)Mi(E,{showClaimants:!0});_(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),as.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,h)=>[...h??[],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,h)=>{let v=h.field.map(E=>{let[I,j,M]=E.split(":");return(!I||!j)&&x(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),M!==void 0&&M!=="required"&&x(`--field "${E}": the third part may only be "required".`),{name:I,type:j,...M==="required"?{required:!0}:{}}}),{baseUrl:T,token:k}=await G(h.baseUrl),y=new K({baseUrl:T,token:k}),S;try{S=await ie(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:v,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){re(E,"extensions:deploy","create a table"),Ui(E)}for(let E of S.tables)Mi(E);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),as.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,h)=>{h.confirm!==d&&x(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T}),y;try{y=await ie(`dropping cr_${d}`,()=>k.tablesDrop(d,h.confirm))}catch(S){re(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 Ll=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ll.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 h=Og(),v;try{v=await f_(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof As&&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}`)}),Ll.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 h=Og();await ud(h).catch(()=>[]);let v;try{v=await g_(h,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}).`)}),Ll.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Og(),h=await ud(d).catch(()=>[]),v=await za(),{active:T}=ld(v);if(T.length===0)_("no active sandboxes.");else{for(let k of T)_(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);_(`
4425
- ${T.length} active sandbox(es).`)}h.length>0&&_(`(reaped ${h.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.",$a).action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),k;try{k=await ie("exporting instance config",()=>T.configExport())}catch(E){E instanceof se&&(E.status===401||E.status===403)&&x("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),x(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let y=typeof k.serialized=="string"?k.serialized:`${JSON.stringify(k.manifest??k,null,2)}
4426
- `,S=fe(process.cwd(),d.out,$s);await be.mkdir(Zr(S),{recursive:!0}),await be.writeFile(S,y,"utf8"),_(`wrote ${d.out}/${$s} (${y.split(`
4427
- `).length} lines).`)});let Mg=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),MR=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Ug=()=>process.env.TURBOBASE_HOME?.trim()||jt(AF(),".turbobase"),UR=()=>"1.48.1",qi=async()=>Promise.all(MR.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Mg.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await qi();for(let h of d)_(`${h.present?Ne.success("installed"):Ne.warn("missing")} ${g.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&_(`
4428
- run \`${To} ext extras install\` to fetch them into ${Ug()}.`)}),Mg.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await qi();if(d.every(I=>I.present)){_(Ne.success("extras already installed \u2014 nothing to do."));return}let h=Ug();await be.mkdir(h,{recursive:!0});let v=d.filter(I=>!I.present).map(I=>I.name),T=nd(process.platform,process.arch),k=async(I,j)=>{let{code:M,stderr:V}=await zi("npm",["install","--prefix",h,"--no-audit","--no-fund",...I]);M!==0&&x(`extras install failed while installing ${j} (npm exited ${M}).
4454
+ samples init: ${E} written, ${I} skipped.`)});let Pr=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),DR=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??""],MR=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];Pr.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:h,token:v}=await Y(d.baseUrl),T=new K({baseUrl:h,token:v}),S;try{S=await T.guardrailsList()}catch(y){re(y,"extensions:deploy","list guardrails"),k(`list guardrails failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(S,null,2));if(S.length===0)return _(`no write guardrails \u2014 every record the admin entitlement allows is writable.
4455
+ `+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(Ht(S.map(DR),{head:MR})),_(g.dim(" first match wins; lower PRIO is evaluated first."))}),Pr.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,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T}),y;try{y=await S.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(x){re(x,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${x instanceof Error?x.message:String(x)}`)}_(`${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>`))}),Pr.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,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T}),y;try{y=await S.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(x){re(x,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${x instanceof Error?x.message:String(x)}`)}_(`${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,h,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Pr.command(`${d} <name>`).description(h==="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,S)=>{let{baseUrl:y,token:x}=await Y(S.baseUrl),E=new K({baseUrl:y,token:x});try{await E.guardrailUpdate(T,{status:h})}catch(I){re(I,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${I instanceof Error?I.message:String(I)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(T)} ${v}`),h==="inactive"&&_(g.dim(" writes it was gating now fall through to the other rules."))});Pr.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,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T});try{await S.guardrailDelete(d)}catch(y){re(y,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),Pr.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,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T}),y=I=>I==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let I;try{I=await S.guardrailPostureGet()}catch(j){re(j,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${j instanceof Error?j.message:String(j)}`)}_(`guardrail posture: ${g.bold(y(I.mode))}`),_(g.dim(I.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 x=d.trim().toLowerCase();x!=="allow"&&x!=="deny"&&k("posture must be 'allow' or 'deny'.");let E;try{E=await S.guardrailPostureSet(x)}catch(I){re(I,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${I instanceof Error?I.message:String(I)}`)}_(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(E.mode))}`),E.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>`."))}),Pr.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 h;if(d.fields)try{h=JSON.parse(d.fields)}catch(E){k(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:v,token:T}=await Y(d.baseUrl),S=new K({baseUrl:v,token:T}),y;try{y=await S.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){re(E,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return _(JSON.stringify(y,null,2));let x=`${d.source}/${y.op??d.record}`;y.degraded?(_(`${g.red("\u2717")} ${x} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(g.dim(` ${y.reason}`))):y.allowed?_(`${g.green("\u2713")} ${x} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(_(`${g.red("\u2717")} ${x} \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 is=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Mi=(d,h={})=>{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 S=[T.required?"required":null].filter(Boolean).join(", "),y=h.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";_(` ${T.column.padEnd(28)} ${T.type}${S?` (${S})`:""}${y}`)}h.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Ui(d){if(d instanceof se&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(D(h.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let Mg=async d=>{let h=jt(fe(process.cwd(),d),"public","turbobase.json"),v=await be.readFile(h,"utf8").catch(()=>null);if(v===null)return null;let T;try{T=JSON.parse(v)}catch(y){k(`${h} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let S=T.tables;return S===void 0?{tables:[],manifestPath:h}:(Array.isArray(S)||k(`${h}: "tables" must be an array.`),{tables:S,manifestPath:h})};is.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:h,token:v}=await Y(d.baseUrl),T=new K({baseUrl:h,token:v}),S;try{S=await T.tablesList()}catch(y){re(y,"extensions:deploy","list tables"),k(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(S,null,2));if(S.length===0)return _("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");_(Ht(S.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),is.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,h)=>{let v=await Mg(d??".");if(v||k(`no public/turbobase.json under ${fe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:S}=await Y(h.baseUrl),y=new K({baseUrl:T,token:S}),x;try{x=await ie("planning tables",()=>y.tablesPlan({claimedBy:h.as,tables:v.tables}))}catch(E){re(E,"extensions:deploy","plan tables"),Ui(E)}_(`claiming as ${g.bold(x.claimedBy)}`);for(let E of x.tables)Mi(E,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),is.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,h)=>{let v=await Mg(d??".");if(v||k(`no public/turbobase.json under ${fe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:S}=await Y(h.baseUrl),y=new K({baseUrl:T,token:S}),x;try{x=await ie("applying tables",()=>y.tablesApply({claimedBy:h.as,tables:v.tables}))}catch(E){re(E,"extensions:deploy","apply tables"),Ui(E)}for(let E of x.tables)Mi(E,{showClaimants:!0});_(`applied ${x.tables.length} table${x.tables.length===1?"":"s"} as ${x.claimedBy}.`)}),is.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,h)=>[...h??[],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,h)=>{let v=h.field.map(E=>{let[I,j,M]=E.split(":");return(!I||!j)&&k(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),M!==void 0&&M!=="required"&&k(`--field "${E}": the third part may only be "required".`),{name:I,type:j,...M==="required"?{required:!0}:{}}}),{baseUrl:T,token:S}=await Y(h.baseUrl),y=new K({baseUrl:T,token:S}),x;try{x=await ie(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:v,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){re(E,"extensions:deploy","create a table"),Ui(E)}for(let E of x.tables)Mi(E);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),is.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,h)=>{h.confirm!==d&&k(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T}),y;try{y=await ie(`dropping cr_${d}`,()=>S.tablesDrop(d,h.confirm))}catch(x){re(x,"extensions:deploy","drop a table"),k(`drop failed: ${x instanceof Error?x.message:String(x)}`)}if(!y.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${y.table} and every row in it.`)});let Ll=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ll.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 h=Ng(),v;try{v=await g_(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof As&&k(T.message),k(`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}`)}),Ll.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 h=Ng();await dd(h).catch(()=>[]);let v;try{v=await y_(h,d)}catch(T){k(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}v||k(`no sandbox named '${d}'.`),_(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),Ll.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Ng(),h=await dd(d).catch(()=>[]),v=await za(),{active:T}=ud(v);if(T.length===0)_("no active sandboxes.");else{for(let S of T)_(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);_(`
4456
+ ${T.length} active sandbox(es).`)}h.length>0&&_(`(reaped ${h.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.",$a).action(async d=>{let{baseUrl:h,token:v}=await Y(d.baseUrl),T=new K({baseUrl:h,token:v}),S;try{S=await ie("exporting instance config",()=>T.configExport())}catch(E){E instanceof se&&(E.status===401||E.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let y=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
4457
+ `,x=fe(process.cwd(),d.out,$s);await be.mkdir(Zr(x),{recursive:!0}),await be.writeFile(x,y,"utf8"),_(`wrote ${d.out}/${$s} (${y.split(`
4458
+ `).length} lines).`)});let Ug=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),UR=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],qg=()=>process.env.TURBOBASE_HOME?.trim()||jt(CF(),".turbobase"),qR=()=>"1.50.0",qi=async()=>Promise.all(UR.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Ug.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await qi();for(let h of d)_(`${h.present?Ne.success("installed"):Ne.warn("missing")} ${g.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&_(`
4459
+ run \`${$o} ext extras install\` to fetch them into ${qg()}.`)}),Ug.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await qi();if(d.every(I=>I.present)){_(Ne.success("extras already installed \u2014 nothing to do."));return}let h=qg();await be.mkdir(h,{recursive:!0});let v=d.filter(I=>!I.present).map(I=>I.name),T=od(process.platform,process.arch),S=async(I,j)=>{let{code:M,stderr:V}=await zi("npm",["install","--prefix",h,"--no-audit","--no-fund",...I]);M!==0&&k(`extras install failed while installing ${j} (npm exited ${M}).
4429
4460
  ${V.trim()}
4430
- These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=v.filter(I=>I!=="isolated-vm");if(y.length>0){let I=y.map(j=>`${j}@${td[j]??"latest"}`);_(`installing ${I.join(", ")} \u2192 ${h}/node_modules \u2026`),await k(I,y.join(", "))}if(v.includes("isolated-vm")){let I=`isolated-vm@${td["isolated-vm"]}`;if(_(`installing ${I} \u2192 ${h}/node_modules \u2026`),await k(["--ignore-scripts",I],"isolated-vm"),c_.includes(T)){let M=`${rd}@${UR()}`;_(`fetching ${M} (no upstream binary for ${T}) \u2026`);let{code:V}=await zi("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",M]);V!==0&&_(Ne.warn(`could not fetch ${M} \u2014 falling back to a source build.`))}let j=await l_({home:h});j.length>0&&_(` ${Ne.success("prebuilt")} ${j.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await qi(),E=S.filter(I=>!I.present).map(I=>I.name);if(E.includes("isolated-vm")){_(Ne.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${od()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:I}=await zi("npm",["rebuild","--prefix",h,"isolated-vm"]);I===0&&(S=await qi(),E=S.filter(j=>!j.present).map(j=>j.name))}E.length>0&&x(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${od()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(Ne.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let ao=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");ao.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 h=d.target==="approved"?"approved":d.target==="auto"?"auto":null;h||x(`--target must be 'auto' or 'approved' (got '${d.target}').`);let v=await ZF(fe(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 Ng(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Ng(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await Ng(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,I=d.prUrl??process.env.PR_URL??null,{baseUrl:j,token:M}=await G(d.baseUrl),V=new K({baseUrl:j,token:M}),F;try{F=await V.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:T>0?v:null,gitRepo:S,gitRef:E,gitSha:y,prUrl:I})}catch(ne){re(ne,"releases:write","release deploy"),ne instanceof se&&ne.status===404&&x("solution_not_found \u2014 no solution with that id."),x(`release deploy failed: ${ne instanceof Error?ne.message:String(ne)}`)}_(`release ${F.releaseId} enqueued \u2192 taskId=${F.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Zu(()=>V.releaseStatus(F.releaseId),`release ${F.releaseId}`,d.intervalMs)}),ao.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,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T}),y;try{y=await k.releaseFiles(d)}catch(I){I instanceof se&&I.status===404&&x(`release ${d} not found.`),I instanceof se&&I.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.`),re(I,"releases:write","pull a release"),x(`release pull failed: ${I instanceof Error?I.message:String(I)}`)}let S=fe(process.cwd(),h.dir),E=0;for(let[I,j]of[["owned",y.owned],["context",y.context]])for(let[M,V]of Object.entries(j)){let F=jt(S,I,M);await be.mkdir(Zr(F),{recursive:!0}),await be.writeFile(F,V,"utf8"),E++}await be.writeFile(jt(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}
4461
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=v.filter(I=>I!=="isolated-vm");if(y.length>0){let I=y.map(j=>`${j}@${rd[j]??"latest"}`);_(`installing ${I.join(", ")} \u2192 ${h}/node_modules \u2026`),await S(I,y.join(", "))}if(v.includes("isolated-vm")){let I=`isolated-vm@${rd["isolated-vm"]}`;if(_(`installing ${I} \u2192 ${h}/node_modules \u2026`),await S(["--ignore-scripts",I],"isolated-vm"),l_.includes(T)){let M=`${nd}@${qR()}`;_(`fetching ${M} (no upstream binary for ${T}) \u2026`);let{code:V}=await zi("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",M]);V!==0&&_(Ne.warn(`could not fetch ${M} \u2014 falling back to a source build.`))}let j=await u_({home:h});j.length>0&&_(` ${Ne.success("prebuilt")} ${j.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let x=await qi(),E=x.filter(I=>!I.present).map(I=>I.name);if(E.includes("isolated-vm")){_(Ne.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${sd()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:I}=await zi("npm",["rebuild","--prefix",h,"isolated-vm"]);I===0&&(x=await qi(),E=x.filter(j=>!j.present).map(j=>j.name))}E.length>0&&k(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${sd()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(Ne.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let ao=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");ao.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 h=d.target==="approved"?"approved":d.target==="auto"?"auto":null;h||k(`--target must be 'auto' or 'approved' (got '${d.target}').`);let v=await VF(fe(process.cwd(),d.project??".")),T=Object.keys(v).length;!d.solution&&T===0&&k("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 Lg(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Lg(["rev-parse","HEAD"]),x=d.gitRepo??process.env.GITHUB_REPOSITORY??await Lg(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,I=d.prUrl??process.env.PR_URL??null,{baseUrl:j,token:M}=await Y(d.baseUrl),V=new K({baseUrl:j,token:M}),F;try{F=await V.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:T>0?v:null,gitRepo:x,gitRef:E,gitSha:y,prUrl:I})}catch(ne){re(ne,"releases:write","release deploy"),ne instanceof se&&ne.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${ne instanceof Error?ne.message:String(ne)}`)}_(`release ${F.releaseId} enqueued \u2192 taskId=${F.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Vu(()=>V.releaseStatus(F.releaseId),`release ${F.releaseId}`,d.intervalMs)}),ao.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,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T}),y;try{y=await S.releaseFiles(d)}catch(I){I instanceof se&&I.status===404&&k(`release ${d} not found.`),I instanceof se&&I.status===409&&k(`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.`),re(I,"releases:write","pull a release"),k(`release pull failed: ${I instanceof Error?I.message:String(I)}`)}let x=fe(process.cwd(),h.dir),E=0;for(let[I,j]of[["owned",y.owned],["context",y.context]])for(let[M,V]of Object.entries(j)){let F=jt(x,I,M);await be.mkdir(Zr(F),{recursive:!0}),await be.writeFile(F,V,"utf8"),E++}await be.writeFile(jt(x,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),_(`pulled release ${y.releaseId} (${y.status}) \u2192 ${x}
4431
4462
  ${Object.keys(y.owned).length} owned file(s), ${Object.keys(y.context).length} context file(s), ${E} total
4432
4463
  `+(y.logTail?`
4433
4464
  the failure these bytes produced:
4434
4465
  ${y.logTail.trim()}
4435
4466
  `:"")+`
4436
4467
  edit the files under owned/, then:
4437
- turbobase release push ${y.releaseId} --dir ${h.dir}`)}),ao.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,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T}),y=fe(process.cwd(),h.dir),S;try{S=await k.releaseFiles(d)}catch(F){F instanceof se&&F.status===404&&x(`release ${d} not found.`),re(F,"releases:write","push a release"),x(`release push failed: ${F instanceof Error?F.message:String(F)}`)}let E=async(F,ne)=>{try{return await be.readFile(jt(y,F,ne),"utf8")}catch{return null}},I=[];for(let[F,ne]of Object.entries(S.context)){let Ee=await E("context",F);Ee!==null&&Ee!==ne&&I.push(F)}I.length>0&&x(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
4468
+ turbobase release push ${y.releaseId} --dir ${h.dir}`)}),ao.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,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T}),y=fe(process.cwd(),h.dir),x;try{x=await S.releaseFiles(d)}catch(F){F instanceof se&&F.status===404&&k(`release ${d} not found.`),re(F,"releases:write","push a release"),k(`release push failed: ${F instanceof Error?F.message:String(F)}`)}let E=async(F,ne)=>{try{return await be.readFile(jt(y,F,ne),"utf8")}catch{return null}},I=[];for(let[F,ne]of Object.entries(x.context)){let Ee=await E("context",F);Ee!==null&&Ee!==ne&&I.push(F)}I.length>0&&k(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
4438
4469
  `+I.map(F=>` context/${F}`).join(`
4439
- `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let j={...S.context},M=0;for(let[F,ne]of Object.entries(S.owned)){let Ee=await E("owned",F);j[F]=Ee??ne,Ee!==null&&Ee!==ne&&M++}M===0&&_("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let V=h.target==="approved"?"approved":"auto";try{let F=await k.releasePush(d,{files:j,target:V,...h.approvedBy?{approvedBy:h.approvedBy}:{}});_(`pushed ${Object.keys(j).length} file(s) (${M} edited) \u2192 release ${F.releaseId} (task ${F.taskId}).
4470
+ `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let j={...x.context},M=0;for(let[F,ne]of Object.entries(x.owned)){let Ee=await E("owned",F);j[F]=Ee??ne,Ee!==null&&Ee!==ne&&M++}M===0&&_("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let V=h.target==="approved"?"approved":"auto";try{let F=await S.releasePush(d,{files:j,target:V,...h.approvedBy?{approvedBy:h.approvedBy}:{}});_(`pushed ${Object.keys(j).length} file(s) (${M} edited) \u2192 release ${F.releaseId} (task ${F.taskId}).
4440
4471
  follow it with:
4441
- turbobase release status ${F.releaseId} --follow`)}catch(F){F instanceof se&&F.status===403&&x("an approved target needs --approved-by (the deploy gate fails closed)."),F instanceof se&&F.status===409&&x("that solution already has an active release \u2014 roll it back or wait for it."),re(F,"releases:write","push a release"),x(`release push failed: ${F instanceof Error?F.message:String(F)}`)}}),ao.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,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T});if(h.follow){await Zu(()=>k.releaseStatus(d),`release ${d}`,h.intervalMs);return}let y;try{y=await k.releaseStatus(d)}catch(S){re(S,"releases:write","release status"),S instanceof se&&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+$/,""))}),ao.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,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T}),y;try{y=await k.releaseRollback(d)}catch(S){re(S,"releases:write","release rollback"),S instanceof se&&S.status===404&&x(`release ${d} not found.`),S instanceof se&&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"}.`)}),ao.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:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),k;try{k=await T.releaseList()}catch(y){re(y,"releases:write","release list"),x(`release list failed: ${y instanceof Error?y.message:String(y)}`)}if(k.length===0){_("no releases.");return}if(ot())_(Ht(k.map(y=>[y.id,ko(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}`)}_(`
4442
- ${k.length} release(s).`)});let co=e.command("processes").description("See what processes are deployed, how they are triggered, and what they have done.");co.command("list").description("Every deployed process with its trigger, its schedule and its last runs.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v});try{let k=await T.processes();d.json?_(JSON.stringify(k,null,2)):Nb(k,_)}catch(k){x(`processes list failed: ${k instanceof Error?k.message:String(k)}`)}}),co.command("runs").description("One process's run history, newest first.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T});try{let y=await k.processRuns(d);h.json?_(JSON.stringify(y,null,2)):Lb(d,y,_)}catch(y){x(`processes runs failed: ${y instanceof Error?y.message:String(y)}`)}}),co.command("run").description("One run and its step ledger.").argument("<run-id>","The run id the invoke answered with.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T});try{let y=await k.processRun(d);h.json?_(JSON.stringify(y,null,2)):xa(y,_)}catch(y){x(`processes run failed: ${y instanceof Error?y.message:String(y)}`)}}),co.command("invoke").description("Start a run of a deployed process \u2014 queued by default, or waited for with --sync.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--input <json>",`The process input as a JSON object, e.g. '{"customerId":"42"}'.`).option("--input-file <path>","Read the process input from a JSON file instead.").option("--sync","Wait for the run to settle (bounded by the instance's budget) and print its outcome.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the response as JSON.").action(async(d,h)=>{h.input!==void 0&&h.inputFile!==void 0&&x("pass --input or --input-file, not both.");let v={};if(h.input!==void 0||h.inputFile!==void 0){let S,E=h.input!==void 0?"--input":"--input-file";if(h.input!==void 0)S=h.input;else try{S=await be.readFile(fe(process.cwd(),h.inputFile),"utf8")}catch{x(`input file not found at ${h.inputFile}.`)}let I=zb(S,E);I.ok||x(I.message),v=I.input}let{baseUrl:T,token:k}=await G(h.baseUrl),y=new K({baseUrl:T,token:k});try{let S=await y.invokeProcess(d,v,h.sync?"sync":"async");h.json?_(JSON.stringify(S,null,2)):Db(S,d,To,_)}catch(S){S instanceof se&&S.status===403&&S.body?.reason==="admin_required"&&x("processes invoke forbidden (403) \u2014 the token's owner must be an administrator to start a process."),re(S,"extensions:deploy","processes invoke"),x(`processes invoke failed: ${S instanceof Error?S.message:String(S)}`)}}),co.command("cancel").description("Stop one run \u2014 a queued run never executes, a running one stops at its next step.").argument("<run-id>","The run to stop.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T});try{let y=await k.cancelProcessRun(d);_(`cancelled ${y.runId??d} (${y.state??"cancelled"}).`),_("A run already going stops at its next step boundary; writes it has already made stay.")}catch(y){x(`processes cancel failed: ${y instanceof Error?y.message:String(y)}`)}}),co.command("rollback").description("Undo a finished run \u2014 delete, newest first, the records its ledger proves it created.").argument("<run-id>","The finished run to roll back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T});try{let y=await k.rollbackProcessRun(d);if(!y.queued){_(`${y.runId??d} is already rolled back \u2014 nothing to do.`);return}_(`rollback queued for ${y.runId??d} (was ${y.state}).`),_(`Only records this run created are deleted; records it updated are left alone. Source deletes are paced by the rollback cap \u2014 follow with \`turbobase processes run ${y.runId??d}\`.`)}catch(y){x(`processes rollback failed: ${y instanceof Error?y.message:String(y)}`)}}),e.command("data").description("Act on one record in your instance \u2014 today, link a row after a settle conflict.").command("settle").description("Link a row to the record the connected system already created, after a write_settle_conflict.").argument("<record-type>","The record type, e.g. salesOrder or nonInventorySaleItem.").argument("<pg-row-id>","The row's pg_row_id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the answer as JSON.").action(async(d,h,v)=>{let{baseUrl:T,token:k}=await G(v.baseUrl),y=new K({baseUrl:T,token:k});try{let S=await y.settleRow(d,h);if(v.json){_(JSON.stringify(S,null,2));return}_(`linked ${d} ${S.pgRowId} to ${S.externalId}.`),S.discarded.length>0&&_(`discarded the inbound copy of the same record: ${S.discarded.join(", ")}.`)}catch(S){x(`data settle failed: ${S instanceof Error?S.message:String(S)}`)}});let qg=e.command("relationships").description('List the linked record pairs on your instance and switch either "re-read" on or off.'),Fg=d=>d===null?g.dim("off"):`${g.green("on")} ${g.dim(new Date(d).toISOString().replace("T"," ").replace(/:\d\d\.\d+Z$/," UTC"))}`,qR=d=>[d.source_system,d.source_table,d.source_jsonb_key??g.dim("(none)"),d.target_table,Fg(d.children_refresh_marked_at),Fg(d.rollup_marked_at)],FR=["SOURCE","LINE TABLE","LINK FIELD","PARENT","LINES","PARENT RE-READ"];return qg.command("list").description("List every linked record pair, and which of its two re-reads is switched on.").option("--source <system>","Only this connected source (default: every 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:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),k;try{k=await T.relationshipsList(d.source)}catch(y){re(y,"extensions:deploy","list relationships"),x(`relationships list failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(k,null,2));if(k.length===0)return _(`no linked record pairs are declared on this instance yet.
4443
- `+g.dim(" pairs are discovered when a source is reconciled; nothing can be switched on until one is."));_(Ht(k.map(qR),{head:FR})),_(g.dim(" LINES = re-read the lines when their parent is saved. PARENT RE-READ = re-read the parent when one of its lines is saved."))}),qg.command("refresh").description("Switch one of a pair's two re-reads on or off.").argument("<CHILD:KEY:PARENT>","The relation: the line table, the field on it that holds the parent, and the parent table.").option("--children","The re-read of the LINES when their parent is saved.").option("--parent","The re-read of the PARENT when one of its lines is saved.").option("--on","Switch that re-read on.").option("--off","Switch that re-read off.").option("--source <system>","Which connected source declares the link (default: whichever does).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the answer as JSON.").action(async(d,h)=>{h.children===h.parent&&x("say which re-read: --children (the lines) or --parent (the parent), not both."),h.on===h.off&&x("say which way: --on or --off, not both.");let v=h.children?"children":"parent",{baseUrl:T,token:k}=await G(h.baseUrl),y=new K({baseUrl:T,token:k});try{let S=await y.relationshipRefresh(d,{marker:v,enabled:h.on===!0,...h.source?{source:h.source}:{}});if(h.json)return _(JSON.stringify(S,null,2));let E=v==="children"?"the lines are re-read when their parent is saved":"the parent is re-read when one of its lines is saved";if(!S.changed)return _(`${S.relation.alias} was already ${h.on?"on":"off"} \u2014 nothing changed.
4444
- `+g.dim(` ${E}: ${h.on?"on":"off"}`));_(`${S.relation.alias}: ${h.on?g.green("on"):g.dim("off")} \u2014 ${E}.`),h.on&&_(g.dim(" this costs one source query per parent commit plus one re-read per line."))}catch(S){re(S,"extensions:deploy","change a relationship refresh"),x(`relationships refresh failed: ${S instanceof Error?S.message:String(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("--process-run <runId>","One process run's step ledger. With --follow it streams and EXITS when the run finishes.").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:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),k=d.limit?Number(d.limit):void 0,y=d.intervalMs?Number(d.intervalMs):void 0;if(d.processRun){try{await jb(T,d.processRun,{...d.follow?{follow:!0}:{},...y!==void 0?{intervalMs:y}:{},sink:_})}catch(S){x(`logs --process-run failed: ${S instanceof Error?S.message:String(S)}`)}return}if(d.conduit){try{await Pb(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 E of S)_(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(S){x(`logs --extension failed: ${S instanceof Error?S.message:String(S)}`)}return}try{await Cb(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:h}=await Promise.resolve().then(()=>(OR(),IR));await h({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(`
4445
- `)),t&&void 0,e}function MF(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 UF(t){let e=jt(fe(process.cwd(),t),"public","turbobase.json"),r=await be.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 qF(){let t=fe(process.cwd(),$a,$s),e;try{e=await be.readFile(t,"utf8")}catch{x(`no config found \u2014 this project authors none (no ${Ra}/, ${Ea}/, ${en} or ${tn}) and there is no ${$a}/${$s}.
4446
- Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return sw(e)}catch(r){x(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function Ig(){let t=process.cwd();if(!await uw(t))return qF();let e;try{e=await dw(t,{inline:Su})}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)D(`${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 FF(t,e){_(`plan against ${e}:`);for(let r of t.add)_(` ${Xr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)_(` ${Xr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)_(` ${Xr.destroy(`${r.kind} ${r.id}`)}`);_(`
4447
- ${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 BF(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function zi(t,e,r){return new Promise(n=>{let o=jg(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 Og(){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 zi("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 zi("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 ZF(t){let e=fe(t,"src"),r={},n=async o=>{let s;try{s=await be.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=jt(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=Nl(e,a).split(Lg).join("/");r[c]=await be.readFile(a,"utf8")}}};return await n(e),r}function Ng(t){return new Promise(e=>{let r=jg("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 VF=!1;VF&&zg().parseAsync(process.argv).catch(t=>x(t instanceof Error?t.message:String(t)));zg().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
4472
+ turbobase release status ${F.releaseId} --follow`)}catch(F){F instanceof se&&F.status===403&&k("an approved target needs --approved-by (the deploy gate fails closed)."),F instanceof se&&F.status===409&&k("that solution already has an active release \u2014 roll it back or wait for it."),re(F,"releases:write","push a release"),k(`release push failed: ${F instanceof Error?F.message:String(F)}`)}}),ao.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,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T});if(h.follow){await Vu(()=>S.releaseStatus(d),`release ${d}`,h.intervalMs);return}let y;try{y=await S.releaseStatus(d)}catch(x){re(x,"releases:write","release status"),x instanceof se&&x.status===404&&k(`release ${d} not found.`),k(`release status failed: ${x instanceof Error?x.message:String(x)}`)}_(`release ${d}: status=${y.releaseStatus??"?"} stage=${y.stage} ${y.percent}%`+(y.runStatus?` (${y.runStatus})`:"")),y.outputTail&&_(y.outputTail.replace(/\n+$/,""))}),ao.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,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T}),y;try{y=await S.releaseRollback(d)}catch(x){re(x,"releases:write","release rollback"),x instanceof se&&x.status===404&&k(`release ${d} not found.`),x instanceof se&&x.status===409&&k(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),k(`release rollback failed: ${x instanceof Error?x.message:String(x)}`)}_(`release ${y.releaseId} rolled back \u2192 status=${y.release?.status??"rolled_back"}.`)}),ao.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:h,token:v}=await Y(d.baseUrl),T=new K({baseUrl:h,token:v}),S;try{S=await T.releaseList()}catch(y){re(y,"releases:write","release list"),k(`release list failed: ${y instanceof Error?y.message:String(y)}`)}if(S.length===0){_("no releases.");return}if(ot())_(Ht(S.map(y=>[y.id,ko(y.status),y.target,y.backend,y.solutionTitles?.length?y.solutionTitles.map(x=>`"${x}"`).join(", "):g.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let y of S){let x=y.solutionTitles?.length?` "${y.solutionTitles.join('", "')}"`:"";_(` ${y.id} ${y.status.padEnd(11)} target=${y.target} backend=${y.backend}${x}`)}_(`
4473
+ ${S.length} release(s).`)});let as=e.command("processes").description("See what processes are deployed, how they are triggered, and what they have done.");as.command("list").description("Every deployed process with its trigger, its schedule and its last runs.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async d=>{let{baseUrl:h,token:v}=await Y(d.baseUrl),T=new K({baseUrl:h,token:v});try{let S=await T.processes();d.json?_(JSON.stringify(S,null,2)):Lb(S,_)}catch(S){k(`processes list failed: ${S instanceof Error?S.message:String(S)}`)}}),as.command("runs").description("One process's run history, newest first.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(d,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T});try{let y=await S.processRuns(d);h.json?_(JSON.stringify(y,null,2)):jb(d,y,_)}catch(y){k(`processes runs failed: ${y instanceof Error?y.message:String(y)}`)}}),as.command("run").description("One run and its step ledger.").argument("<run-id>","The run id the invoke answered with.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(d,h)=>{let{baseUrl:v,token:T}=await Y(h.baseUrl),S=new K({baseUrl:v,token:T});try{let y=await S.processRun(d);h.json?_(JSON.stringify(y,null,2)):ka(y,_)}catch(y){k(`processes run failed: ${y instanceof Error?y.message:String(y)}`)}}),as.command("invoke").description("Start a run of a deployed process \u2014 queued by default, or waited for with --sync.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--input <json>",`The process input as a JSON object, e.g. '{"customerId":"42"}'.`).option("--input-file <path>","Read the process input from a JSON file instead.").option("--sync","Wait for the run to settle (bounded by the instance's budget) and print its outcome.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the response as JSON.").action(async(d,h)=>{h.input!==void 0&&h.inputFile!==void 0&&k("pass --input or --input-file, not both.");let v={};if(h.input!==void 0||h.inputFile!==void 0){let x,E=h.input!==void 0?"--input":"--input-file";if(h.input!==void 0)x=h.input;else try{x=await be.readFile(fe(process.cwd(),h.inputFile),"utf8")}catch{k(`input file not found at ${h.inputFile}.`)}let I=Db(x,E);I.ok||k(I.message),v=I.input}let{baseUrl:T,token:S}=await Y(h.baseUrl),y=new K({baseUrl:T,token:S});try{let x=await y.invokeProcess(d,v,h.sync?"sync":"async");h.json?_(JSON.stringify(x,null,2)):Mb(x,d,$o,_)}catch(x){x instanceof se&&x.status===403&&x.body?.reason==="admin_required"&&k("processes invoke forbidden (403) \u2014 the token's owner must be an administrator to start a process."),re(x,"extensions:deploy","processes invoke"),k(`processes invoke failed: ${x instanceof Error?x.message:String(x)}`)}});let jl=d=>{as.command(d.name).description(d.description).argument("<run-id>",d.argument).option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(h,v)=>{let{baseUrl:T,token:S}=await Y(v.baseUrl),y=new K({baseUrl:T,token:S});try{d.report(await d.call(y,h),h)}catch(x){k(`processes ${d.name} failed: ${x instanceof Error?x.message:String(x)}`)}})};jl({name:"cancel",description:"Stop one run \u2014 a queued run never executes, a running one stops at its next step.",argument:"The run to stop.",call:(d,h)=>d.cancelProcessRun(h),report:(d,h)=>{_(`cancelled ${d.runId??h} (${d.state??"cancelled"}).`),_("A run already going stops at its next step boundary; writes it has already made stay.")}}),jl({name:"rollback",description:"Undo a finished run \u2014 delete, newest first, the records its ledger proves it created.",argument:"The finished run to roll back.",call:(d,h)=>d.rollbackProcessRun(h),report:(d,h)=>{if(!d.queued){_(`${d.runId??h} is already rolled back \u2014 nothing to do.`);return}_(`rollback queued for ${d.runId??h} (was ${d.state}).`),_(`Only records this run created are deleted; records it updated are left alone. Source deletes are paced by the rollback cap \u2014 follow with \`turbobase processes run ${d.runId??h}\`.`)}}),jl({name:"resume",description:"Carry on a run that stopped waiting on the connected system \u2014 it writes nothing twice.",argument:"The stopped run to carry on.",call:(d,h)=>d.resumeProcessRun(h),report:(d,h)=>{_(`resume queued for ${d.runId??h} (now ${d.state??"running"}).`),_(`The same run carries on at the step it stopped on, so nothing it already wrote is written again \u2014 follow with \`turbobase processes run ${d.runId??h}\`.`)}}),e.command("data").description("Act on one record in your instance \u2014 today, link a row after a settle conflict.").command("settle").description("Link a row to the record the connected system already created, after a write_settle_conflict.").argument("<record-type>","The record type, e.g. salesOrder or nonInventorySaleItem.").argument("<pg-row-id>","The row's pg_row_id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the answer as JSON.").action(async(d,h,v)=>{let{baseUrl:T,token:S}=await Y(v.baseUrl),y=new K({baseUrl:T,token:S});try{let x=await y.settleRow(d,h);if(v.json){_(JSON.stringify(x,null,2));return}_(`linked ${d} ${x.pgRowId} to ${x.externalId}.`),x.discarded.length>0&&_(`discarded the inbound copy of the same record: ${x.discarded.join(", ")}.`)}catch(x){k(`data settle failed: ${x instanceof Error?x.message:String(x)}`)}});let Fg=e.command("relationships").description('List the linked record pairs on your instance and switch either "re-read" on or off.'),Bg=d=>d===null?g.dim("off"):`${g.green("on")} ${g.dim(new Date(d).toISOString().replace("T"," ").replace(/:\d\d\.\d+Z$/," UTC"))}`,FR=d=>[d.source_system,d.source_table,d.source_jsonb_key??g.dim("(none)"),d.target_table,Bg(d.children_refresh_marked_at),Bg(d.rollup_marked_at)],BR=["SOURCE","LINE TABLE","LINK FIELD","PARENT","LINES","PARENT RE-READ"];return Fg.command("list").description("List every linked record pair, and which of its two re-reads is switched on.").option("--source <system>","Only this connected source (default: every 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:h,token:v}=await Y(d.baseUrl),T=new K({baseUrl:h,token:v}),S;try{S=await T.relationshipsList(d.source)}catch(y){re(y,"extensions:deploy","list relationships"),k(`relationships list failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(S,null,2));if(S.length===0)return _(`no linked record pairs are declared on this instance yet.
4474
+ `+g.dim(" pairs are discovered when a source is reconciled; nothing can be switched on until one is."));_(Ht(S.map(FR),{head:BR})),_(g.dim(" LINES = re-read the lines when their parent is saved. PARENT RE-READ = re-read the parent when one of its lines is saved."))}),Fg.command("refresh").description("Switch one of a pair's two re-reads on or off.").argument("<CHILD:KEY:PARENT>","The relation: the line table, the field on it that holds the parent, and the parent table.").option("--children","The re-read of the LINES when their parent is saved.").option("--parent","The re-read of the PARENT when one of its lines is saved.").option("--on","Switch that re-read on.").option("--off","Switch that re-read off.").option("--source <system>","Which connected source declares the link (default: whichever does).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the answer as JSON.").action(async(d,h)=>{h.children===h.parent&&k("say which re-read: --children (the lines) or --parent (the parent), not both."),h.on===h.off&&k("say which way: --on or --off, not both.");let v=h.children?"children":"parent",{baseUrl:T,token:S}=await Y(h.baseUrl),y=new K({baseUrl:T,token:S});try{let x=await y.relationshipRefresh(d,{marker:v,enabled:h.on===!0,...h.source?{source:h.source}:{}});if(h.json)return _(JSON.stringify(x,null,2));let E=v==="children"?"the lines are re-read when their parent is saved":"the parent is re-read when one of its lines is saved";if(!x.changed)return _(`${x.relation.alias} was already ${h.on?"on":"off"} \u2014 nothing changed.
4475
+ `+g.dim(` ${E}: ${h.on?"on":"off"}`));_(`${x.relation.alias}: ${h.on?g.green("on"):g.dim("off")} \u2014 ${E}.`),h.on&&_(g.dim(" this costs one source query per parent commit plus one re-read per line."))}catch(x){re(x,"extensions:deploy","change a relationship refresh"),k(`relationships refresh failed: ${x instanceof Error?x.message:String(x)}`)}}),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("--process-run <runId>","One process run's step ledger. With --follow it streams and EXITS when the run finishes.").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:h,token:v}=await Y(d.baseUrl),T=new K({baseUrl:h,token:v}),S=d.limit?Number(d.limit):void 0,y=d.intervalMs?Number(d.intervalMs):void 0;if(d.processRun){try{await zb(T,d.processRun,{...d.follow?{follow:!0}:{},...y!==void 0?{intervalMs:y}:{},sink:_})}catch(x){k(`logs --process-run failed: ${x instanceof Error?x.message:String(x)}`)}return}if(d.conduit){try{await Ab(T,d.conduit,{...d.follow?{follow:!0}:{},...S!==void 0?{limit:S}:{},...y!==void 0?{intervalMs:y}:{},sink:_})}catch(x){k(`logs --conduit failed: ${x instanceof Error?x.message:String(x)}`)}return}if(d.extension){try{let x=await T.logs(d.extension,S);x.length===0&&_(`no logs for ${d.extension}.`);for(let E of x)_(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(x){k(`logs --extension failed: ${x instanceof Error?x.message:String(x)}`)}return}try{await Ib(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}:{},...S!==void 0?{limit:S}:{},...y!==void 0?{intervalMs:y}:{},sink:_})}catch(x){k(`logs failed: ${x instanceof Error?x.message:String(x)}`)}}),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:h}=await Promise.resolve().then(()=>(NR(),OR));await h({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(`
4476
+ `)),t&&void 0,e}function UF(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 qF(t){let e=jt(fe(process.cwd(),t),"public","turbobase.json"),r=await be.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){k(`${e} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&k(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function FF(){let t=fe(process.cwd(),$a,$s),e;try{e=await be.readFile(t,"utf8")}catch{k(`no config found \u2014 this project authors none (no ${Ra}/, ${Ea}/, ${en} or ${tn}) and there is no ${$a}/${$s}.
4477
+ Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return iw(e)}catch(r){k(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function Og(){let t=process.cwd();if(!await dw(t))return FF();let e;try{e=await pw(t,{inline:$u})}catch(r){k(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)D(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&k(`${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 BF(t,e){_(`plan against ${e}:`);for(let r of t.add)_(` ${Xr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)_(` ${Xr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)_(` ${Xr.destroy(`${r.kind} ${r.id}`)}`);_(`
4478
+ ${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 ZF(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function zi(t,e,r){return new Promise(n=>{let o=zg(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 Ng(){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 zi("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 zi("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 VF(t){let e=fe(t,"src"),r={},n=async o=>{let s;try{s=await be.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=jt(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=Nl(e,a).split(jg).join("/");r[c]=await be.readFile(a,"utf8")}}};return await n(e),r}function Lg(t){return new Promise(e=>{let r=zg("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 HF=!1;HF&&Dg().parseAsync(process.argv).catch(t=>k(t instanceof Error?t.message:String(t)));Dg().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
4448
4479
  `),process.exit(1)});